UNPKG

xstate

Version:

Finite State Machines and Statecharts for the Modern Web.

3 lines (2 loc) 18.3 kB
!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).XStateActions={})}(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 n(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const o=t=>{const e=n();e&&e.register(t)};function i(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function r(t){setTimeout((()=>{throw t}))}const c="function"==typeof Symbol&&Symbol.observable||"@@observable";function a(t,e){const s=u(t),n=u(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every((t=>t in n&&a(s[t],n[t])))}function h(t){if(e=t,Array.isArray(e))return t;var e;const s=[];let n="";for(let e=0;e<t.length;e++){switch(t.charCodeAt(e)){case 92:n+=t[e+1],e++;continue;case 46:s.push(n),n="";continue}n+=t[e]}return s.push(n),s}function u(t){if((e=t)&&"object"==typeof e&&"machine"in e&&"value"in e)return t.value;var e;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(h(t))}function d(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function p(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function l(t,e){return`${t.sessionId}.${e}`}let f=0;let y=!1;let _=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const v={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class g{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=_.NotStarted,this._parent=void 0,this._syncSnapshot=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 n={...v,...s},{clock:o,logger:i,parent:r,syncSnapshot:c,id:a,systemId:h,inspect:u}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:c,logger:a}=e,h={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},a=l(t,o);u._snapshot._scheduledEvents[a]=i;const h=c.setTimeout((()=>{delete r[a],delete u._snapshot._scheduledEvents[a],u._relay(t,e,s)}),n);r[a]=h},cancel:(t,e)=>{const s=l(t,e),n=r[s];delete r[s],delete u._snapshot._scheduledEvents[s],void 0!==n&&c.clearTimeout(n)},cancelAll:t=>{for(const e in u._snapshot._scheduledEvents){const s=u._snapshot._scheduledEvents[e];s.source===t&&h.cancel(t,s.id)}}},u={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+f++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=d(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach((t=>t.next?.(s)))},_relay:(t,e,s)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:h,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const t=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];h.schedule(s,n,o,i,r)}},_clock:c,_logger:a};return u}(this,{clock:o,logger:i}),u&&!r&&this.system.inspect(d(u)),this.sessionId=this.system._bookId(),this.id=a??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,this.options=n,this.src=n.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()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)e(t)},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=y;try{y=!0,t.exec(t.info,t.params)}finally{y=e}};this._processingStatus===_.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this._systemId=h,this.system._set(h,this)),this._initState(s?.snapshot??s?.state),h&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){r(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){r(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=d(t,e,s);if(this._processingStatus!==_.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){r(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){r(t)}else r(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}start(){if(this._processingStatus===_.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=_.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._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,n;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){n={err:t}}if(n){const{err:t}=n;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===s&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===_.Stopped?this:(this.mailbox.clear(),this._processingStatus===_.NotStarted?(this._processingStatus=_.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){r(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||r(t));let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){r(t)}}this.observers.clear(),e&&r(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,i(this.id,t))}_stopProcedure(){return this._processingStatus!==_.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=_.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==_.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:o)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[c](){return this}getSnapshot(){return this._snapshot}}function m(t,...[e]){return new g(t,e)}function x(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function b(t,e){t.defer((()=>{t.system.scheduler.cancel(t.self,e.sendId)}))}function S(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=x,e.execute=b,e}function w(t,e,s,n,{id:o,systemId:i,src:r,input:c,syncSnapshot:a}){const h="string"==typeof r?p(e.machine,r):r,u="function"==typeof o?o(s):o;let d,l;return h&&(l="function"==typeof c?c({context:e.context,event:s.event,self:t.self}):c,d=m(h,{id:u,src:r,parent:t.self,syncSnapshot:a,systemId:i,input:l})),[W(e,{children:{...e.children,[u]:d}}),{id:o,systemId:i,actorRef:d,src:r,input:l},void 0]}function I(t,{actorRef:e}){e&&t.defer((()=>{e._processingStatus!==_.Stopped&&e.start()}))}function E(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=w,i.execute=I,i}function k(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let c=e.children;return r&&(c={...c},delete c[r.id]),[W(e,{children:c}),r,void 0]}function T(t,e){e&&(t.system._unregister(e),e._processingStatus===_.Running?t.defer((()=>{t.stopChild(e)})):t.stopChild(e))}function R(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=k,e.execute=T,e}const $=R;function A(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return A(r,e,s,n);const c={context:e,event:s},a=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(c,a);return r.check(n,c,r)}const C=t=>"atomic"===t.type||"final"===t.type;function P(t){return Object.values(t.states).filter((t=>"history"!==t.type))}function j(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function O(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(C(t))return t.key}const n={};for(const t of s)n[t.key]=O(t,e);return n}function M(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function N(t,e){const s=function(t){const e=new Set(t),s=M(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of P(t))if("history"!==s.type&&!e.has(s)){const t=q(s);for(const s of t)e.add(s)}}else q(t).forEach((t=>e.add(t)));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}(e);return O(t,M(s))}function q(t){const e=function(t){const e=new Set;function s(t){if(!e.has(t))if(e.add(t),"compound"===t.type)s(t.initial.target[0]);else if("parallel"===t.type)for(const e of P(t))s(e)}return s(t),e}(t);for(const s of e)for(const n of j(s,t))e.add(n);return e}const D=function(t){return a(t,this.value)},L=function(t){return this.tags.has(t)},J=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some((t=>void 0!==t.target||t.actions.length))},z=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:c,...a}=this;return{...a,tags:Array.from(e)}},V=function(){return this._nodes.reduce(((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t)),{})};function W(t,e={}){return function(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:N(e.root,t._nodes),tags:new Set(t._nodes.flatMap((t=>t.tags))),children:t.children,historyValue:t.historyValue||{},matches:D,hasTag:L,can:J,getMeta:V,toJSON:z}}({...t,...e},t.machine)}function B(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=p(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=m(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[a.id]=a,a}return m(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[c.id]=c,t.defer((()=>{c._processingStatus!==_.Stopped&&c.start()})),c}}function G(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:B(t,e,s.event,i),self:t.self,system:t.system};let c={};if("function"==typeof o)c=o(r,n);else for(const t of Object.keys(o)){const e=o[t];c[t]="function"==typeof e?e(r,n):e}return[W(e,{context:Object.assign({},e.context,c),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Q(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=G,e}function U(t,e,s,n,{event:o}){return[e,{event:"function"==typeof o?o(s,n):o},void 0]}function X(t,{event:e}){t.defer((()=>t.emit(e)))}function F(t){function e(t,e){}return e.type="xstate.emit",e.event=t,e.resolve=U,e.execute=X,e}function H(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:c}){const a=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const h="function"==typeof o?o(s,n):o;let u;if("string"==typeof r){const t=a&&a[r];u="function"==typeof t?t(s,n):t}else u="function"==typeof r?r(s,n):r;return"number"!=typeof u&&c.push(h),[e,{event:h,id:i,delay:u},void 0]}function K(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer((()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)}))}function Y(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=H,s.execute=K,s}let Z=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function tt(t,e,s,n,{to:o,event:i,id:r,delay:c},a){const h=e.machine.implementations.delays;if("string"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const u="function"==typeof i?i(s,n):i;let d;if("string"==typeof c){const t=h&&h[c];d="function"==typeof t?t(s,n):t}else d="function"==typeof c?c(s,n):c;const p="function"==typeof o?o(s,n):o;let l;if("string"==typeof p){if(l=p===Z.Parent?t.self._parent:p===Z.Internal?t.self:p.startsWith("#_")?e.children[p.slice(2)]:a.deferredActorIds?.includes(p)?p:e.children[p],!l)throw new Error(`Unable to send event to actor '${p}' from machine '${e.machine.id}'.`)}else l=p||t.self;return[e,{to:l,targetId:"string"==typeof p?p:void 0,event:u,id:r,delay:d},void 0]}function et(t,e,s){"string"==typeof s.to&&(s.to=e.children[s.to])}function st(t,e){t.defer((()=>{const{to:s,event:n,delay:o,id:r}=e;"number"!=typeof o?t.system._relay(t.self,s,"xstate.error"===n.type?i(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,r)}))}function nt(t,e,s){function n(t,e){}return n.type="xstate.sendTo",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=tt,n.retryResolve=et,n.execute=st,n}function ot(t,e){return nt(Z.Parent,t,e)}function it(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(Q(...t))},r.cancel=(...t)=>{i.push(S(...t))},r.raise=(...t)=>{i.push(Y(...t))},r.sendTo=(...t)=>{i.push(nt(...t))},r.sendParent=(...t)=>{i.push(ot(...t))},r.spawnChild=(...t)=>{i.push(E(...t))},r.stopChild=(...t)=>{i.push(R(...t))},r.emit=(...t)=>{i.push(F(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>A(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function rt(t,e,s,n,{value:o,label:i}){return[e,{value:"function"==typeof o?o(s,n):o,label:i},void 0]}function ct({logger:t},{value:e,label:s}){s?t(s,e):t(e)}t.assign=Q,t.cancel=S,t.emit=F,t.enqueueActions=function(t){function e(t,e){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=it,e},t.forwardTo=function(t,e){return nt(t,(({event:t})=>t),e)},t.log=function(t=({context:t,event:e})=>({context:t,event:e}),e){function s(t,e){}return s.type="xstate.log",s.value=t,s.label=e,s.resolve=rt,s.execute=ct,s},t.raise=Y,t.sendParent=ot,t.sendTo=nt,t.spawnChild=E,t.stop=$,t.stopChild=R,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=xstate-actions.umd.min.js.map