xstate 4.7.7 → 4.9.1

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.
@@ -1,4 +1,4 @@
1
- const t=".",e={},i="xstate.guard",s="";function n(t){return Object.keys(t)}function o(e,i,s=t){const r=c(e,s),a=c(i,s);return x(a)?!!x(r)&&a===r:x(r)?r in a:n(r).every(t=>t in a&&o(r[t],a[t]))}function r(t){try{return x(t)||"number"==typeof t?`${t}`:t.type}catch(t){throw new Error("Events must be strings or objects with a string event.type property.")}}function a(t,e){try{return w(t)?t:t.toString().split(e)}catch(e){throw new Error(`'${t}' is not a valid state path.`)}}function c(t,e){if("object"==typeof(i=t)&&"value"in i&&"context"in i&&"event"in i&&"_event"in i)return t.value;var i;if(w(t))return h(t);if("string"!=typeof t)return t;return h(a(t,e))}function h(t){if(1===t.length)return t[0];const e={};let i=e;for(let e=0;e<t.length-1;e++)e===t.length-2?i[t[e]]=t[e+1]:(i[t[e]]={},i=i[t[e]]);return e}function d(t,e){const i={},s=n(t);for(let n=0;n<s.length;n++){const o=s[n];i[o]=e(t[o],o,t,n)}return i}function u(t,e,i){const s={};for(const o of n(t)){const n=t[o];i(n)&&(s[o]=e(n,o,t))}return s}const l=t=>e=>{let i=e;for(const e of t)i=i[e];return i};function f(t){if(!t)return[[]];if(x(t))return[[t]];return p(n(t).map(e=>{const i=t[e];return"string"==typeof i||i&&Object.keys(i).length?f(t[e]).map(t=>[e].concat(t)):[[e]]}))}function p(t){return[].concat(...t)}function v(t){return w(t)?t:[t]}function g(t){return void 0===t?[]:v(t)}function y(t,e,i){if(_(t))return t(e,i.data);const s={};for(const o of n(t)){const n=t[o];_(n)?s[o]=n(e,i.data):s[o]=n}return s}function m(t){return t instanceof Promise||!(null===t||!_(t)&&"object"!=typeof t||!_(t.then))}function b(t,e){const[i,s]=[[],[]];for(const n of t)e(n)?i.push(n):s.push(n);return[i,s]}function S(t,e){return d(t.states,(t,i)=>{if(!t)return;const s=(x(e)?void 0:e[i])||(t?t.current:void 0);return s?{current:s,states:S(t,s)}:void 0})}function w(t){return Array.isArray(t)}function _(t){return"function"==typeof t}function x(t){return"string"==typeof t}function O(t,e){if(t)return x(t)?{type:i,name:t,predicate:e?e[t]:void 0}:_(t)?{type:i,name:t.name,predicate:t}:t}function E(t){try{return"subscribe"in t&&_(t.subscribe)}catch(t){return!1}}const j=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")();function N(t){try{return"__xstatenode"in t}catch(t){return!1}}const $=(()=>{let t=0;return()=>(++t).toString(16)})();function T(t,e){return x(t)||"number"==typeof t?Object.assign({type:t},e):t}function k(t,e){if(!x(t)&&"$$type"in t&&"scxml"===t.$$type)return t;const i=T(t);return Object.assign({name:i.type,data:i,$$type:"scxml",type:"external"},e)}function P(t,e){return v(e).map(e=>void 0===e||"string"==typeof e||N(e)?{target:e,event:t}:Object.assign(Object.assign({},e),{event:t}))}function V(t,e){let i;for(const s of n(t))o(s,e)&&(!i||e.length>i.length)&&(i=s);return t[i]}
1
+ const t={};function e(t){return Object.keys(t)}function i(t,s,n="."){const r=o(t,n),a=o(s,n);return S(a)?!!S(r)&&a===r:S(r)?r in a:e(r).every(t=>t in a&&i(r[t],a[t]))}function s(t){try{return S(t)||"number"==typeof t?`${t}`:t.type}catch(t){throw new Error("Events must be strings or objects with a string event.type property.")}}function n(t,e){try{return m(t)?t:t.toString().split(e)}catch(e){throw new Error(`'${t}' is not a valid state path.`)}}function o(t,e){if("object"==typeof(i=t)&&"value"in i&&"context"in i&&"event"in i&&"_event"in i)return t.value;var i;if(m(t))return r(t);if("string"!=typeof t)return t;return r(n(t,e))}function r(t){if(1===t.length)return t[0];const e={};let i=e;for(let e=0;e<t.length-1;e++)e===t.length-2?i[t[e]]=t[e+1]:(i[t[e]]={},i=i[t[e]]);return e}function a(t,i){const s={},n=e(t);for(let e=0;e<n.length;e++){const o=n[e];s[o]=i(t[o],o,t,e)}return s}function c(t,i,s){const n={};for(const o of e(t)){const e=t[o];s(e)&&(n[o]=i(e,o,t))}return n}const h=t=>e=>{let i=e;for(const e of t)i=i[e];return i};function d(t){if(!t)return[[]];if(S(t))return[[t]];return u(e(t).map(e=>{const i=t[e];return"string"==typeof i||i&&Object.keys(i).length?d(t[e]).map(t=>[e].concat(t)):[[e]]}))}function u(t){return[].concat(...t)}function l(t){return m(t)?t:[t]}function f(t){return void 0===t?[]:l(t)}function p(t,i,s){if(b(t))return t(i,s.data);const n={};for(const o of e(t)){const e=t[o];b(e)?n[o]=e(i,s.data):n[o]=e}return n}function g(t){return t instanceof Promise||!(null===t||!b(t)&&"object"!=typeof t||!b(t.then))}function v(t,e){const[i,s]=[[],[]];for(const n of t)e(n)?i.push(n):s.push(n);return[i,s]}function y(t,e){return a(t.states,(t,i)=>{if(!t)return;const s=(S(e)?void 0:e[i])||(t?t.current:void 0);return s?{current:s,states:y(t,s)}:void 0})}function m(t){return Array.isArray(t)}function b(t){return"function"==typeof t}function S(t){return"string"==typeof t}function w(t,e){if(t)return S(t)?{type:"xstate.guard",name:t,predicate:e?e[t]:void 0}:b(t)?{type:"xstate.guard",name:t.name,predicate:t}:t}function x(t){try{return"subscribe"in t&&b(t.subscribe)}catch(t){return!1}}const _="function"==typeof Symbol&&Symbol.observable||"@@observable";function O(t){try{return"__xstatenode"in t}catch(t){return!1}}const E=(()=>{let t=0;return()=>(t++,t.toString(16))})();function j(t,e){return S(t)||"number"==typeof t?Object.assign({type:t},e):t}function N(t,e){if(!S(t)&&"$$type"in t&&"scxml"===t.$$type)return t;const i=j(t);return Object.assign({name:i.type,data:i,$$type:"scxml",type:"external"},e)}function $(t,e){return l(e).map(e=>void 0===e||"string"==typeof e||O(e)?{target:e,event:t}:Object.assign(Object.assign({},e),{event:t}))}function T(t,e,i,s,n){const{guards:o}=t.options,r={state:n,cond:e,_event:s};if("xstate.guard"===e.type)return e.predicate(i,s.data,r);const a=o[e.type];if(!a)throw new Error(`Guard '${e.type}' is not implemented on machine '${t.id}'.`);return a(i,s.data,r)}function k(t,s){let n;for(const o of e(t))i(o,s)&&(!n||s.length>n.length)&&(n=o);return t[n]}
2
2
  /*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation. All rights reserved.
4
4
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -12,4 +12,4 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
12
12
 
13
13
  See the Apache Version 2.0 License for specific language governing permissions
14
14
  and limitations under the License.
15
- ***************************************************************************** */function I(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(i[s[n]]=t[s[n]])}return i}var L,C;!function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure"}(L||(L={})),function(t){t.Parent="#_parent",t.Internal="#_internal"}(C||(C={}));const A=t=>"atomic"===t.type||"final"===t.type;function R(t){return n(t.states).map(e=>t.states[e])}function M(t){const e=[t];return A(t)?e:e.concat(p(R(t).map(M)))}function D(t,e){const i=F(new Set(t)),s=new Set(e);for(const t of s){let e=t.parent;for(;e&&!s.has(e);)s.add(e),e=e.parent}const n=F(s);for(const t of s)if("compound"!==t.type||n.get(t)&&n.get(t).length){if("parallel"===t.type)for(const e of R(t))"history"!==e.type&&(s.has(e)||(s.add(e),i.get(e)?i.get(e).forEach(t=>s.add(t)):e.initialStateNodes.forEach(t=>s.add(t))))}else i.get(t)?i.get(t).forEach(t=>s.add(t)):t.initialStateNodes.forEach(t=>s.add(t));for(const t of s){let e=t.parent;for(;e&&!s.has(e);)s.add(e),e=e.parent}return s}function F(t){const e=new Map;for(const i of t)e.has(i)||e.set(i,[]),i.parent&&(e.has(i.parent)||e.set(i.parent,[]),e.get(i.parent).push(i));return e}function z(t,e){return function t(e,i){const s=i.get(e);if(!s)return{};if("compound"===e.type){const t=s[0];if(!t)return{};if(A(t))return t.key}const n={};return s.forEach(e=>{n[e.key]=t(e,i)}),n}(t,F(D([t],e)))}function U(t,e){return Array.isArray(t)?t.some(t=>t===e):t instanceof Set&&t.has(e)}function J(t,e){return"compound"===e.type?R(e).some(e=>"final"===e.type&&U(t,e)):"parallel"===e.type&&R(e).every(e=>J(t,e))}const B=L.Start,q=L.Stop,X=L.Raise,G=L.Send,H=L.Cancel,K=L.NullEvent,Q=L.Assign,W=(L.After,L.DoneState,L.Log),Y=L.Init,Z=L.Invoke,tt=(L.ErrorExecution,L.ErrorPlatform),et=L.ErrorCustom,it=L.Update,st=L.Pure,nt=k({type:Y});function ot(t,e){return e&&e[t]||void 0}function rt(t,e){let i;if(x(t)||"number"==typeof t){const s=ot(t,e);i=_(s)?{type:t,exec:s}:s||{type:t,exec:void 0}}else if(_(t))i={type:t.name||t.toString(),exec:t};else{const s=ot(t.type,e);if(_(s))i=Object.assign(Object.assign({},t),{exec:s});else if(s){const{type:e}=t,n=I(t,["type"]);i=Object.assign(Object.assign({type:e},s),n)}else i=t}return Object.defineProperty(i,"toString",{value:()=>i.type,enumerable:!1,configurable:!0}),i}const at=(t,e)=>{if(!t)return[];return(w(t)?t:[t]).map(t=>rt(t,e))};function ct(t){const e=rt(t);return Object.assign(Object.assign({id:x(t)?t:e.id},e),{type:e.type})}function ht(t){return x(t)?{type:X,event:t}:dt(t,{to:C.Internal})}function dt(t,e){return{to:e?e.to:void 0,type:G,event:_(t)?t:T(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:_(t)?t.name:r(t)}}function ut(t,e){return dt(t,Object.assign(Object.assign({},e),{to:C.Parent}))}function lt(){return ut(it)}const ft=(t,e)=>({context:t,event:e});const pt=(t,e,i)=>Object.assign(Object.assign({},t),{value:x(t.expr)?t.expr:t.expr(e,i.data,{_event:i})}),vt=t=>({type:H,sendId:t});function gt(t){const e=ct(t);return{type:L.Start,activity:e,exec:void 0}}function yt(t){const e=ct(t);return{type:L.Stop,activity:e,exec:void 0}}const mt=t=>({type:Q,assignment:t});function bt(t,e){const i=e?`#${e}`:"";return`${L.After}(${t})${i}`}function St(t,e){const i=`${L.DoneState}.${t}`,s={type:i,data:e,toString:()=>i};return s}function wt(t,e){const i=`${L.DoneInvoke}.${t}`,s={type:i,data:e,toString:()=>i};return s}function _t(t,e){const i=`${L.ErrorPlatform}.${t}`,s={type:i,data:e,toString:()=>i};return s}function xt(t,e){return dt((t,e)=>e,Object.assign(Object.assign({},e),{to:t}))}function Ot(t,e){const{exec:i}=t;return Object.assign(Object.assign({},t),{exec:void 0!==i?()=>i(e.context,e.event,{action:t,state:e,_event:e._event}):void 0})}class Et{constructor(t){this.actions=[],this.activities=e,this.meta={},this.events=[],this.value=t.value,this.context=t.context,this._event=t._event,this._sessionid=t._sessionid,this.event=this._event.data,this.historyValue=t.historyValue,this.history=t.history,this.actions=t.actions||[],this.activities=t.activities||e,this.meta=t.meta||{},this.events=t.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=t.configuration,this.transitions=t.transitions,this.children=t.children,this.done=!!t.done,Object.defineProperty(this,"nextEvents",{get:()=>(function(t){return p([...new Set(t.map(t=>t.ownEvents))])})(t.configuration)})}static from(t,e){if(t instanceof Et)return t.context!==e?new Et({value:t.value,context:e,_event:t._event,_sessionid:null,historyValue:t.historyValue,history:t.history,actions:[],activities:t.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):t;return new Et({value:t,context:e,_event:nt,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})}static create(t){return new Et(t)}static inert(t,e){if(t instanceof Et){if(!t.actions.length)return t;const i=nt;return new Et({value:t.value,context:e,_event:i,_sessionid:null,historyValue:t.historyValue,history:t.history,activities:t.activities,configuration:t.configuration,transitions:[],children:{}})}return Et.from(t,e)}toStrings(t=this.value,e="."){if(x(t))return[t];const i=n(t);return i.concat(...i.map(i=>this.toStrings(t[i],e).map(t=>i+e+t)))}toJSON(){return I(this,["configuration","transitions"])}matches(t){return o(t,this.value)}}function jt(t){try{return"function"==typeof t.send}catch(t){return!1}}const Nt="",$t="#",Tt="*",kt={},Pt=t=>t[0]===$t,Vt=()=>({actions:{},guards:{},services:{},activities:{},delays:{}});class It{constructor(e,i,s){this.config=e,this.context=s,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.options=Object.assign(Vt(),i),this.parent=this.options._parent,this.key=this.config.key||this.options._key||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:t),this.id=this.config.id||[this.machine.key,...this.path].join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&n(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.initial=this.config.initial,this.states=this.config.states?d(this.config.states,(t,e)=>{const i=new It(t,{_parent:this,_key:e});return Object.assign(this.idMap,Object.assign({[i.id]:i},i.idMap)),i}):kt;let o=0;!function t(e){e.order=o++;for(const i of R(e))t(i)}(this),this.history=!0===this.config.history?"shallow":this.config.history||!1,this._transient=!!this.config.on&&(Array.isArray(this.config.on)?this.config.on.some(({event:t})=>t===Nt):Nt in this.config.on),this.strict=!!this.config.strict,this.onEntry=g(this.config.entry||this.config.onEntry).map(t=>rt(t)),this.onExit=g(this.config.exit||this.config.onExit).map(t=>rt(t)),this.meta=this.config.meta,this.data="final"===this.type?this.config.data:void 0,this.invoke=g(this.config.invoke).map((t,e)=>{if(N(t))return this.machine.options.services=Object.assign({[t.id]:t},this.machine.options.services),{type:Z,src:t.id,id:t.id};if("string"!=typeof t.src){const i=`${this.id}:invocation[${e}]`;return this.machine.options.services=Object.assign({[i]:t.src},this.machine.options.services),Object.assign(Object.assign({type:Z,id:i},t),{src:i})}return Object.assign(Object.assign({},t),{type:Z,id:t.id||t.src,src:t.src})}),this.activities=g(this.config.activities).concat(this.invoke).map(t=>ct(t)),this.transition=this.transition.bind(this)}_init(){this.__cache.transitions||M(this).forEach(t=>t.on)}withConfig(t,e=this.context){const{actions:i,activities:s,guards:n,services:o,delays:r}=this.options;return new It(this.config,{actions:Object.assign(Object.assign({},i),t.actions),activities:Object.assign(Object.assign({},s),t.activities),guards:Object.assign(Object.assign({},n),t.guards),services:Object.assign(Object.assign({},o),t.services),delays:Object.assign(Object.assign({},r),t.delays)},e)}withContext(t){return new It(this.config,this.options,t)}get definition(){return{id:this.id,key:this.key,version:this.version,type:this.type,initial:this.initial,history:this.history,states:d(this.states,t=>t.definition),on:this.on,transitions:this.transitions,onEntry:this.onEntry,onExit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.data,invoke:this.invoke}}toJSON(){return this.definition}get on(){if(this.__cache.on)return this.__cache.on;const t=this.transitions;return this.__cache.on=t.reduce((t,e)=>(t[e.eventType]=t[e.eventType]||[],t[e.eventType].push(e),t),{})}get after(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)}get transitions(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)}getCandidates(t){if(this.__cache.candidates[t])return this.__cache.candidates[t];const e=t===Nt,i=this.transitions.filter(i=>{const s=i.eventType===t;return e?s:s||i.eventType===Tt});return this.__cache.candidates[t]=i,i}getDelayedTransitions(){const t=this.config.after;if(!t)return[];const e=(t,e)=>{const i=bt(_(t)?`${this.id}:delay[${e}]`:t,this.id);return this.onEntry.push(dt(i,{delay:t})),this.onExit.push(vt(i)),i};return(w(t)?t.map((t,i)=>{const s=e(t.delay,i);return Object.assign(Object.assign({},t),{event:s})}):p(n(t).map((i,s)=>{const n=t[i],o=x(n)?{target:n}:n,r=isNaN(+i)?i:+i,a=e(r,s);return g(o).map(t=>Object.assign(Object.assign({},t),{event:a,delay:r}))}))).map(t=>{const{delay:e}=t;return Object.assign(Object.assign({},this.formatTransition(t)),{delay:e})})}getStateNodes(t){if(!t)return[];const e=t instanceof Et?t.value:c(t,this.delimiter);if(x(e)){const t=this.getStateNode(e).initial;return void 0!==t?this.getStateNodes({[e]:t}):[this.states[e]]}const i=n(e);return i.map(t=>this.getStateNode(t)).concat(i.reduce((t,i)=>{const s=this.getStateNode(i).getStateNodes(e[i]);return t.concat(s)},[]))}handles(t){const e=r(t);return this.events.includes(e)}resolveState(t){const e=Array.from(D([],this.getStateNodes(t.value)));return new Et(Object.assign(Object.assign({},t),{value:this.resolve(t.value),configuration:e}))}transitionLeafNode(t,e,i){const s=this.getStateNode(t).next(e,i);return s&&s.transitions.length?s:this.next(e,i)}transitionCompoundNode(t,e,i){const s=n(t),o=this.getStateNode(s[0])._transition(t[s[0]],e,i);return o&&o.transitions.length?o:this.next(e,i)}transitionParallelNode(t,e,i){const s={};for(const o of n(t)){const n=t[o];if(!n)continue;const r=this.getStateNode(o)._transition(n,e,i);r&&(s[o]=r)}const o=n(s).map(t=>s[t]),r=p(o.map(t=>t.transitions));if(!o.some(t=>t.transitions.length>0))return this.next(e,i);const a=p(o.map(t=>t.entrySet)),c=p(n(s).map(t=>s[t].configuration));return{transitions:r,entrySet:a,exitSet:p(o.map(t=>t.exitSet)),configuration:c,source:e,actions:p(n(s).map(t=>s[t].actions))}}_transition(t,e,i){return x(t)?this.transitionLeafNode(t,e,i):1===n(t).length?this.transitionCompoundNode(t,e,i):this.transitionParallelNode(t,e,i)}next(t,e){const i=e.name,s=[];let n,r=[];for(const a of this.getCandidates(i)){const{cond:h,in:d}=a,u=t.context,f=!d||(x(d)&&Pt(d)?t.matches(c(this.getStateNodeById(d).path,this.delimiter)):o(c(d,this.delimiter),l(this.path.slice(0,-2))(t.value)));let p=!1;try{p=!h||this.evaluateGuard(h,u,e,t)}catch(t){throw new Error(`Unable to evaluate guard '${h.name||h.type}' in transition for event '${i}' in state node '${this.id}':\n${t.message}`)}if(p&&f){void 0!==a.target&&(r=a.target),s.push(...a.actions),n=a;break}}if(!n)return;if(!r.length)return{transitions:[n],entrySet:[],exitSet:[],configuration:t.value?[this]:[],source:t,actions:s};const a=p(r.map(e=>this.getRelativeStateNodes(e,t.historyValue))),h=!!n.internal;return{transitions:[n],entrySet:h?[]:p(a.map(t=>this.nodesFromChild(t))),exitSet:h?[]:[this],configuration:a,source:t,actions:s}}nodesFromChild(t){if(t.escapes(this))return[];const e=[];let i=t;for(;i&&i!==this;)e.push(i),i=i.parent;return e.push(this),e}escapes(t){if(this===t)return!1;let e=this.parent;for(;e;){if(e===t)return!1;e=e.parent}return!0}evaluateGuard(t,e,s,n){const{guards:o}=this.machine.options,r={state:n,cond:t,_event:s};if(t.type===i)return t.predicate(e,s.data,r);const a=o[t.type];if(!a)throw new Error(`Guard '${t.type}' is not implemented on machine '${this.machine.id}'.`);return a(e,s.data,r)}getActions(t,e,i,s){const n=D([],s?this.getStateNodes(s.value):[this]),o=t.configuration.length?D(n,t.configuration):n;for(const e of o)U(n,e)||t.entrySet.push(e);for(const e of n)U(o,e)&&!U(t.exitSet,e.parent)||t.exitSet.push(e);t.source||(t.exitSet=[],t.entrySet.push(this));const r=p(t.entrySet.map(s=>{const n=[];if("final"!==s.type)return n;const o=s.parent;if(n.push(St(s.id,s.data),St(o.id,s.data?y(s.data,e,i):void 0)),o.parent){const e=o.parent;"parallel"===e.type&&R(e).every(e=>J(t.configuration,e))&&n.push(St(e.id,e.data))}return n}));t.exitSet.sort((t,e)=>e.order-t.order),t.entrySet.sort((t,e)=>t.order-e.order);const a=new Set(t.entrySet),c=new Set(t.exitSet),[h,d]=[p(Array.from(a).map(t=>[...t.activities.map(t=>gt(t)),...t.onEntry])).concat(r.map(ht)),p(Array.from(c).map(t=>[...t.onExit,...t.activities.map(t=>yt(t))]))];return at(d.concat(t.actions).concat(h),this.machine.options.actions)}transition(t=this.initialState,e,i){const s=k(e);let n;if(t instanceof Et)n=void 0===i?t:this.resolveState(Et.from(t,i));else{const e=x(t)?this.resolve(h(this.getResolvedPath(t))):this.resolve(t),s=i||this.machine.context;n=this.resolveState(Et.from(e,s))}if(this.strict&&!this.events.includes(s.name)&&(o=s.name,!/^(done|error)\./.test(o)))throw new Error(`Machine '${this.id}' does not accept event '${s.name}'`);var o;const r=this._transition(n.value,n,s)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:n,actions:[]},a=D([],this.getStateNodes(n.value)),c=r.configuration.length?D(a,r.configuration):a;return r.configuration=[...c],this.resolveTransition(r,n,s)}resolveRaisedTransition(t,e,i){const s=t.actions;return(t=this.transition(t,e))._event=i,t.event=i.data,t.actions.unshift(...s),t}resolveTransition(t,e,i=nt,s=this.machine.context){const{configuration:o}=t,r=!e||t.transitions.length>0?z(this.machine,o):void 0,a=e?e.historyValue?e.historyValue:t.source?this.machine.historyValue(e.value):void 0:void 0,c=e?e.context:s,h=this.getActions(t,c,i,e),d=e?Object.assign({},e.activities):{};for(const t of h)t.type===B?d[t.activity.type]=t:t.type===q&&(d[t.activity.type]=!1);const[u,l]=b(h,t=>t.type===Q),f=u.length?function(t,e,i,s){return t?i.reduce((t,i)=>{const{assignment:o}=i,r={state:s,action:i,_event:e};let a={};if(_(o))a=o(t,e.data,r);else for(const i of n(o)){const s=o[i];a[i]=_(s)?s(t,e.data,r):s}return Object.assign({},t,a)},t):t}(c,i,u,e):c,v=p(l.map(t=>{switch(t.type){case X:return function(t){return{type:X,_event:k(t.event)}}(t);case G:return function(t,e,i,s){const n={_event:i},o=k(_(t.event)?t.event(e,i.data,n):t.event);let r;if(x(t.delay)){const o=s&&s[t.delay];r=_(o)?o(e,i.data,n):o}else r=_(t.delay)?t.delay(e,i.data,n):t.delay;const a=_(t.to)?t.to(e,i.data,n):t.to;return Object.assign(Object.assign({},t),{to:a,_event:o,event:o.data,delay:r})}(t,f,i,this.machine.options.delays);case W:return pt(t,f,i);case st:return t.get(f,i.data)||[];default:return rt(t,this.options.actions)}})),[g,y]=b(v,t=>t.type===X||t.type===G&&t.to===C.Internal),m=v.filter(t=>t.type===B&&t.activity.type===Z).reduce((t,e)=>(t[e.activity.id]=function(t){const e={id:i=t.id,send:()=>void 0,subscribe:()=>({unsubscribe:()=>void 0}),toJSON:()=>({id:i})};var i;return e.meta=t,e}(e.activity),t),e?Object.assign({},e.children):{}),w=r?t.configuration:e?e.configuration:[],O=w.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{}),E=J(w,this),j=new Et({value:r||e.value,context:f,_event:i,_sessionid:e?e._sessionid:null,historyValue:r?a?(N=a,$=r,{current:$,states:S(N,$)}):void 0:e?e.historyValue:void 0,history:!r||t.source?e:void 0,actions:r?y:[],activities:r?d:e?e.activities:{},meta:r?O:e?e.meta:void 0,events:[],configuration:w,transitions:t.transitions,children:m,done:E});var N,$;j.changed=i.name===it||!!u.length;const{history:T}=j;if(T&&delete T.history,!r)return j;let P=j;if(!E){for((this._transient||o.some(t=>t._transient))&&(P=this.resolveRaisedTransition(P,{type:K},i));g.length;){const t=g.shift();P=this.resolveRaisedTransition(P,t._event,i)}}const V=P.changed||(T?!!P.actions.length||!!u.length||typeof T.value!=typeof P.value||!function t(e,i){if(e===i)return!0;if(void 0===e||void 0===i)return!1;if(x(e)||x(i))return e===i;const s=n(e),o=n(i);return s.length===o.length&&s.every(s=>t(e[s],i[s]))}(P.value,T.value):void 0);return P.changed=V,P.historyValue=j.historyValue,P.history=T,P}getStateNode(t){if(Pt(t))return this.machine.getStateNodeById(t);if(!this.states)throw new Error(`Unable to retrieve child state '${t}' from '${this.id}'; no child states exist.`);const e=this.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${this.id}'`);return e}getStateNodeById(t){const e=Pt(t)?t.slice($t.length):t;if(e===this.id)return this;const i=this.machine.idMap[e];if(!i)throw new Error(`Child state node '#${e}' does not exist on machine '${this.id}'`);return i}getStateNodeByPath(t){if("string"==typeof t&&Pt(t))try{return this.getStateNodeById(t.slice(1))}catch(t){}const e=a(t,this.delimiter).slice();let i=this;for(;e.length;){const t=e.shift();if(!t.length)break;i=i.getStateNode(t)}return i}resolve(t){if(!t)return this.initialStateValue||kt;switch(this.type){case"parallel":return d(this.initialStateValue,(e,i)=>e?this.getStateNode(i).resolve(t[i]||e):kt);case"compound":if(x(t)){const e=this.getStateNode(t);return"parallel"===e.type||"compound"===e.type?{[t]:e.initialStateValue}:t}return n(t).length?d(t,(t,e)=>t?this.getStateNode(e).resolve(t):kt):this.initialStateValue||{};default:return t||kt}}getResolvedPath(t){if(Pt(t)){const e=this.machine.idMap[t.slice($t.length)];if(!e)throw new Error(`Unable to find state node '${t}'`);return e.path}return a(t,this.delimiter)}get initialStateValue(){if(this.__cache.initialStateValue)return this.__cache.initialStateValue;let t;if("parallel"===this.type)t=u(this.states,t=>t.initialStateValue||kt,t=>!("history"===t.type));else if(void 0!==this.initial){if(!this.states[this.initial])throw new Error(`Initial state '${this.initial}' not found on '${this.key}'`);t=A(this.states[this.initial])?this.initial:{[this.initial]:this.states[this.initial].initialStateValue}}return this.__cache.initialStateValue=t,this.__cache.initialStateValue}getInitialState(t,e){const i=this.getStateNodes(t);return this.resolveTransition({configuration:i,entrySet:i,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,void 0,e)}get initialState(){this._init();const{initialStateValue:t}=this;if(!t)throw new Error(`Cannot retrieve initial state from simple state '${this.id}'.`);return this.getInitialState(t)}get target(){let t;if("history"===this.type){const e=this.config;t=x(e.target)&&Pt(e.target)?h(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t}getRelativeStateNodes(t,e,i=!0){return i?"history"===t.type?t.resolveHistory(e):t.initialStateNodes:[t]}get initialStateNodes(){if(A(this))return[this];if("compound"===this.type&&!this.initial)return[this];return p(f(this.initialStateValue).map(t=>this.getFromRelativePath(t)))}getFromRelativePath(t){if(!t.length)return[this];const[e,...i]=t;if(!this.states)throw new Error(`Cannot retrieve subPath '${e}' from node with no states`);const s=this.getStateNode(e);if("history"===s.type)return s.resolveHistory();if(!this.states[e])throw new Error(`Child state '${e}' does not exist on '${this.id}'`);return this.states[e].getFromRelativePath(i)}historyValue(t){if(n(this.states).length)return{current:t||this.initialStateValue,states:u(this.states,(e,i)=>{if(!t)return e.historyValue();const s=x(t)?void 0:t[i];return e.historyValue(s||e.initialStateValue)},t=>!t.history)}}resolveHistory(t){if("history"!==this.type)return[this];const e=this.parent;if(!t){const t=this.target;return t?p(f(t).map(t=>e.getFromRelativePath(t))):e.initialStateNodes}const i=(s=e.path,n="states",t=>{let e=t;for(const t of s)e=e[n][t];return e})(t).current;var s,n;return x(i)?[e.getStateNode(i)]:p(f(i).map(t=>"deep"===this.history?e.getFromRelativePath(t):[e.states[t[0]]]))}get stateIds(){const t=p(n(this.states).map(t=>this.states[t].stateIds));return[this.id].concat(t)}get events(){if(this.__cache.events)return this.__cache.events;const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const i of n(t)){const s=t[i];if(s.states)for(const t of s.events)e.add(`${t}`)}return this.__cache.events=Array.from(e)}get ownEvents(){const t=new Set(this.transitions.filter(t=>!(!t.target&&!t.actions.length&&t.internal)).map(t=>t.eventType));return Array.from(t)}resolveTarget(t){if(void 0!==t)return t.map(t=>{if(!x(t))return t;const e=t[0]===this.delimiter;if(e&&!this.parent)return this.getStateNodeByPath(t.slice(1));const i=e?this.key+t:t;if(!this.parent)return this.getStateNodeByPath(i);try{return this.parent.getStateNodeByPath(i)}catch(t){throw new Error(`Invalid transition definition for state node '${this.id}':\n${t.message}`)}})}formatTransition(t){const e=function(t){if(void 0!==t&&t!==s)return g(t)}(t.target),i="internal"in t?t.internal:!e||e.some(t=>x(t)&&t[0]===this.delimiter),{guards:n}=this.machine.options,o=this.resolveTarget(e);return Object.assign(Object.assign({},t),{actions:at(g(t.actions)),cond:O(t.cond,n),target:o,source:this,internal:i,eventType:t.event})}formatTransitions(){let t;if(this.config.on)if(Array.isArray(this.config.on))t=this.config.on;else{const e=this.config.on,i=Tt,s=e[i],o=void 0===s?[]:s,r=I(e,[i+""]);t=p(n(r).map(t=>{return P(t,r[t])}).concat(P(Tt,o)))}else t=[];const e=this.config.onDone?P(String(St(this.id)),this.config.onDone):[],i=p(this.invoke.map(t=>{const e=[];return t.onDone&&e.push(...P(String(wt(t.id)),t.onDone)),t.onError&&e.push(...P(String(_t(t.id)),t.onError)),e})),s=this.after,o=p([...e,...i,...t].map(t=>g(t).map(t=>this.formatTransition(t))));for(const t of s)o.push(t);return o}}function Lt(t,e,i=t.context){const s="function"==typeof i?i():i;return new It(t,e,s)}function Ct(t,e){const i="function"==typeof t.context?t.context():t.context;return new It(t,e,i)}const At={deferEvents:!1};class Rt{constructor(t){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=Object.assign(Object.assign({},At),t)}initialize(t){if(this.initialized=!0,t){if(!this.options.deferEvents)return void this.schedule(t);this.process(t)}this.flushEvents()}schedule(t){if(this.initialized&&!this.processingEvent){if(0!==this.queue.length)throw new Error("Event queue should be empty when it is not processing events");this.process(t),this.flushEvents()}else this.queue.push(t)}clear(){this.queue=[]}flushEvents(){let t=this.queue.shift();for(;t;)this.process(t),t=this.queue.shift()}process(t){this.processingEvent=!0;try{t()}catch(t){throw this.clear(),t}finally{this.processingEvent=!1}}}const Mt=new Map;let Dt=0;const Ft={bookId:()=>`x:${Dt++}`,register:(t,e)=>(Mt.set(t,e),t),get:t=>Mt.get(t),free(t){Mt.delete(t)}},zt={sync:!1,autoForward:!1},Ut=(()=>{const t=[];return(e,i)=>{e&&t.push(e);const s=i(e||t[t.length-1]);return e&&t.pop(),s}})();var Jt;!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(Jt||(Jt={}));class Bt{constructor(t,e=Bt.defaultOptions){this.machine=t,this.scheduler=new Rt,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this._status=Jt.NotStarted,this.children=new Map,this.forwardTo=new Set,this.init=this.start,this.send=(t,e)=>{if(w(t))return this.batch(t),this.state;const i=k(T(t,e));if(this._status===Jt.Stopped)return this.state;if(this._status===Jt.NotStarted&&this.options.deferEvents);else if(this._status!==Jt.Running)throw new Error(`Event "${i.name}" was sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ${JSON.stringify(i.data)}`);return this.scheduler.schedule(()=>{this.forward(i);const t=this.nextState(i);this.update(t,i)}),this._state},this.sendTo=(t,e)=>{const i=this.parent&&(e===C.Parent||this.parent.id===e),s=i?this.parent:jt(e)?e:this.children.get(e)||Ft.get(e);if(s)"machine"in s?s.send(Object.assign(Object.assign({},t),{name:t.name===et?`${_t(this.id)}`:t.name,origin:this.sessionId})):s.send(t.data);else if(!i)throw new Error(`Unable to send event to child '${e}' from service '${this.id}'.`)};const i=Object.assign(Object.assign({},Bt.defaultOptions),e),{clock:s,logger:n,parent:o,id:r}=i,a=void 0!==r?r:t.id;this.id=a,this.logger=n,this.clock=s,this.parent=o,this.options=i,this.scheduler=new Rt({deferEvents:this.options.deferEvents}),this.sessionId=Ft.bookId()}get initialState(){return this._initialState?this._initialState:Ut(this,()=>(this._initialState=this.machine.initialState,this._initialState))}get state(){return this._state}execute(t,e){for(const i of t.actions)this.exec(i,t,e)}update(t,e){if(t._sessionid=this.sessionId,this._state=t,this.options.execute&&this.execute(this.state),this.devTools&&this.devTools.send(e.data,t),t.event)for(const e of this.eventListeners)e(t.event);for(const e of this.listeners)e(t,t.event);for(const t of this.contextListeners)t(this.state.context,this.state.history?this.state.history.context:void 0);const i=J(t.configuration||[],this.machine);if(this.state.configuration&&i){const i=t.configuration.find(t=>"final"===t.type&&t.parent===this.machine),s=i&&i.data?y(i.data,t.context,e):void 0;for(const t of this.doneListeners)t(wt(this.id,s));this.stop()}}onTransition(t){return this.listeners.add(t),this._status===Jt.Running&&t(this.state,this.state.event),this}subscribe(t,e,i){if(!t)return{unsubscribe:()=>void 0};let s,n=i;return"function"==typeof t?s=t:(s=t.next.bind(t),n=t.complete.bind(t)),this.listeners.add(s),this._status===Jt.Running&&s(this.state),n&&this.onDone(n),{unsubscribe:()=>{s&&this.listeners.delete(s),n&&this.doneListeners.delete(n)}}}onEvent(t){return this.eventListeners.add(t),this}onSend(t){return this.sendListeners.add(t),this}onChange(t){return this.contextListeners.add(t),this}onStop(t){return this.stopListeners.add(t),this}onDone(t){return this.doneListeners.add(t),this}off(t){return this.listeners.delete(t),this.eventListeners.delete(t),this.sendListeners.delete(t),this.stopListeners.delete(t),this.doneListeners.delete(t),this.contextListeners.delete(t),this}start(t){if(this._status===Jt.Running)return this;Ft.register(this.sessionId,this),this.initialized=!0,this._status=Jt.Running;const e=void 0===t?this.initialState:Ut(this,()=>(function(t){return!x(t)&&("value"in t&&"history"in t)})(t)?this.machine.resolveState(t):this.machine.resolveState(Et.from(t,this.machine.context)));return this.options.devTools&&this.attachDev(),this.scheduler.initialize(()=>{this.update(e,nt)}),this}stop(){for(const t of this.listeners)this.listeners.delete(t);for(const t of this.stopListeners)t(),this.stopListeners.delete(t);for(const t of this.contextListeners)this.contextListeners.delete(t);for(const t of this.doneListeners)this.doneListeners.delete(t);this.children.forEach(t=>{_(t.stop)&&t.stop()});for(const t of n(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.scheduler.clear(),this.initialized=!1,this._status=Jt.Stopped,Ft.free(this.sessionId),this}batch(t){if(this._status===Jt.NotStarted&&this.options.deferEvents);else if(this._status!==Jt.Running)throw new Error(`${t.length} event(s) were sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.`);this.scheduler.schedule(()=>{let e=this.state,i=!1;const s=[];for(const n of t){const t=k(n);this.forward(t),e=Ut(this,()=>this.machine.transition(e,t)),s.push(...e.actions.map(t=>Ot(t,e))),i=i||!!e.changed}e.changed=i,e.actions=s,this.update(e,k(t[t.length-1]))})}sender(t){return this.send.bind(this,t)}nextState(t){const e=k(t);if(0===e.name.indexOf(tt)&&!this.state.nextEvents.some(t=>0===t.indexOf(tt)))throw e.data.data;return Ut(this,()=>this.machine.transition(this.state,e))}forward(t){for(const e of this.forwardTo){const i=this.children.get(e);if(!i)throw new Error(`Unable to forward event '${t}' from interpreter '${this.id}' to nonexistant child '${e}'.`);i.send(t)}}defer(t){this.delayedEventsMap[t.id]=this.clock.setTimeout(()=>{t.to?this.sendTo(t._event,t.to):this.send(t._event)},t.delay)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}exec(t,e,i){const{context:s,_event:n}=e,o=ot(t.type,i)||t.exec,r=_(o)?o:o?o.exec:t.exec;if(r)try{return r(s,n.data,{action:t,state:this.state,_event:n})}catch(t){throw this.parent&&this.parent.send({type:"xstate.error",data:t}),t}switch(t.type){case G:const e=t;if("number"==typeof e.delay)return void this.defer(e);e.to?this.sendTo(e._event,e.to):this.send(e._event);break;case H:this.cancel(t.sendId);break;case B:{const e=t.activity;if(!this.state.activities[e.type])break;if(e.type===L.Invoke){const t=this.machine.options.services?this.machine.options.services[e.src]:void 0,{id:i,data:o}=e,r="autoForward"in e?e.autoForward:!!e.forward;if(!t)return;const a=_(t)?t(s,n.data):t;m(a)?this.state.children[i]=this.spawnPromise(Promise.resolve(a),i):_(a)?this.state.children[i]=this.spawnCallback(a,i):E(a)?this.state.children[i]=this.spawnObservable(a,i):N(a)&&(this.state.children[i]=this.spawnMachine(o?a.withContext(y(o,s,n)):a,{id:i,autoForward:r}))}else this.spawnActivity(e);break}case q:this.stopChild(t.activity.id);break;case W:const{label:i,value:o}=t;i?this.logger(i,o):this.logger(o)}}stopChild(t){const e=this.children.get(t);e&&(this.children.delete(t),this.forwardTo.delete(t),delete this.state.children[t],_(e.stop)&&e.stop())}spawn(t,e,i){if(m(t))return this.spawnPromise(Promise.resolve(t),e);if(_(t))return this.spawnCallback(t,e);if(jt(t))return this.spawnActor(t);if(E(t))return this.spawnObservable(t,e);if(N(t))return this.spawnMachine(t,Object.assign(Object.assign({},i),{id:e}));throw new Error(`Unable to spawn entity "${e}" of type "${typeof t}".`)}spawnMachine(t,e={}){const i=new Bt(t,Object.assign(Object.assign({},this.options),{parent:this,id:e.id||t.id})),s=Object.assign(Object.assign({},zt),e);s.sync&&i.onTransition(t=>{this.send(it,{state:t,id:i.id})}),i.onDone(t=>{this.send(k(t,{origin:i.id}))}).start();const n=i;return this.children.set(i.id,n),s.autoForward&&this.forwardTo.add(i.id),n}spawnPromise(t,e){let i=!1;t.then(t=>{i||this.send(k(wt(e,t),{origin:e}))},t=>{if(!i){const i=_t(e,t);try{this.send(k(i,{origin:e}))}catch(t){this.devTools&&this.devTools.send(i,this.state),this.machine.strict&&this.stop()}}});const s={id:e,send:()=>void 0,subscribe:(e,i,s)=>{let n=!1;return t.then(t=>{n||(e&&e(t),n||s&&s())},t=>{n||i(t)}),{unsubscribe:()=>n=!0}},stop:()=>{i=!0},toJSON:()=>({id:e})};return this.children.set(e,s),s}spawnCallback(t,e){let i=!1;const s=new Set,n=new Set,o=t=>{n.forEach(e=>e(t)),i||this.send(t)};let r;try{r=t(o,t=>{s.add(t)})}catch(t){this.send(_t(e,t))}if(m(r))return this.spawnPromise(r,e);const a={id:e,send:t=>s.forEach(e=>e(t)),subscribe:t=>(n.add(t),{unsubscribe:()=>{n.delete(t)}}),stop:()=>{i=!0,_(r)&&r()},toJSON:()=>({id:e})};return this.children.set(e,a),a}spawnObservable(t,e){const i=t.subscribe(t=>{this.send(k(t,{origin:e}))},t=>{this.send(k(_t(e,t),{origin:e}))},()=>{this.send(k(wt(e),{origin:e}))}),s={id:e,send:()=>void 0,subscribe:(e,i,s)=>t.subscribe(e,i,s),stop:()=>i.unsubscribe(),toJSON:()=>({id:e})};return this.children.set(e,s),s}spawnActor(t){return this.children.set(t.id,t),t}spawnActivity(t){const e=this.machine.options&&this.machine.options.activities?this.machine.options.activities[t.type]:void 0;if(!e)return;const i=e(this.state.context,t);this.spawnEffect(t.id,i)}spawnEffect(t,e){this.children.set(t,{id:t,send:()=>void 0,subscribe:()=>({unsubscribe:()=>void 0}),stop:e||void 0,toJSON:()=>({id:t})})}attachDev(){if(this.options.devTools&&"undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__){const t="object"==typeof this.options.devTools?this.options.devTools:void 0;this.devTools=window.__REDUX_DEVTOOLS_EXTENSION__.connect(Object.assign(Object.assign({name:this.id,autoPause:!0,stateSanitizer:t=>({value:t.value,context:t.context,actions:t.actions})},t),{features:Object.assign({jump:!1,skip:!1},t?t.features:void 0)}),this.machine),this.devTools.init(this.state)}}toJSON(){return{id:this.id}}[j](){return this}}Bt.defaultOptions=(t=>({execute:!0,deferEvents:!0,clock:{setTimeout:(e,i)=>t.setTimeout.call(null,e,i),clearTimeout:e=>t.clearTimeout.call(null,e)},logger:t.console.log.bind(console),devTools:!1}))("undefined"==typeof window?global:window),Bt.interpret=Ht;const qt=(t="null")=>({id:t,send:()=>void 0,subscribe:()=>({unsubscribe:()=>{}}),toJSON:()=>({id:t})}),Xt=t=>x(t)?Object.assign(Object.assign({},zt),{name:t}):Object.assign(Object.assign(Object.assign({},zt),{name:$()}),t);function Gt(t,e){const i=Xt(e);return Ut(void 0,e=>e?e.spawn(t,i.name,i):qt(i.name))}function Ht(t,e){return new Bt(t,e)}function Kt(t,e,i){const s=Et.from(t,t instanceof Et?t.context:void 0);for(const[t,i]of e)if(s.matches(t))return i(s);return i(s)}const Qt={raise:ht,send:dt,sendParent:ut,sendUpdate:lt,log:function(t=ft,e){return{type:W,label:e,expr:t}},cancel:vt,start:gt,stop:yt,assign:mt,after:bt,done:St,respond:function(t,e){return dt(t,Object.assign(Object.assign({},e),{to:(t,e,{_event:i})=>i.origin}))},forwardTo:xt,escalate:function(t,e){return ut((e,i,s)=>({type:et,data:_(t)?t(e,i,s):t}),Object.assign(Object.assign({},e),{to:C.Parent}))}};export{L as ActionTypes,Bt as Interpreter,Lt as Machine,C as SpecialTargets,Et as State,It as StateNode,Qt as actions,mt as assign,Ct as createMachine,wt as doneInvoke,xt as forwardTo,Ht as interpret,V as mapState,Kt as matchState,o as matchesState,dt as send,ut as sendParent,lt as sendUpdate,Gt as spawn};
15
+ ***************************************************************************** */function P(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(i[s[n]]=t[s[n]])}return i}var V,C;!function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"}(V||(V={})),function(t){t.Parent="#_parent",t.Internal="#_internal"}(C||(C={}));const I=t=>"atomic"===t.type||"final"===t.type;function L(t){return e(t.states).map(e=>t.states[e])}function A(t){const e=[t];return I(t)?e:e.concat(u(L(t).map(A)))}function R(t,e){const i=M(new Set(t)),s=new Set(e);for(const t of s){let e=t.parent;for(;e&&!s.has(e);)s.add(e),e=e.parent}const n=M(s);for(const t of s)if("compound"!==t.type||n.get(t)&&n.get(t).length){if("parallel"===t.type)for(const e of L(t))"history"!==e.type&&(s.has(e)||(s.add(e),i.get(e)?i.get(e).forEach(t=>s.add(t)):e.initialStateNodes.forEach(t=>s.add(t))))}else i.get(t)?i.get(t).forEach(t=>s.add(t)):t.initialStateNodes.forEach(t=>s.add(t));for(const t of s){let e=t.parent;for(;e&&!s.has(e);)s.add(e),e=e.parent}return s}function M(t){const e=new Map;for(const i of t)e.has(i)||e.set(i,[]),i.parent&&(e.has(i.parent)||e.set(i.parent,[]),e.get(i.parent).push(i));return e}function D(t,e){return function t(e,i){const s=i.get(e);if(!s)return{};if("compound"===e.type){const t=s[0];if(!t)return{};if(I(t))return t.key}const n={};return s.forEach(e=>{n[e.key]=t(e,i)}),n}(t,M(R([t],e)))}function F(t,e){return Array.isArray(t)?t.some(t=>t===e):t instanceof Set&&t.has(e)}function z(t,e){return"compound"===e.type?L(e).some(e=>"final"===e.type&&F(t,e)):"parallel"===e.type&&L(e).every(e=>z(t,e))}const J=V.Start,U=V.Stop,B=V.Raise,q=V.Send,X=V.Cancel,H=V.NullEvent,G=V.Assign,K=(V.After,V.DoneState,V.Log),Q=V.Init,W=V.Invoke,Y=(V.ErrorExecution,V.ErrorPlatform),Z=V.ErrorCustom,tt=V.Update,et=V.Choose,it=V.Pure,st=N({type:Q});function nt(t,e){return e&&e[t]||void 0}function ot(t,e){let i;if(S(t)||"number"==typeof t){const s=nt(t,e);i=b(s)?{type:t,exec:s}:s||{type:t,exec:void 0}}else if(b(t))i={type:t.name||t.toString(),exec:t};else{const s=nt(t.type,e);if(b(s))i=Object.assign(Object.assign({},t),{exec:s});else if(s){const{type:e}=t,n=P(t,["type"]);i=Object.assign(Object.assign({type:e},s),n)}else i=t}return Object.defineProperty(i,"toString",{value:()=>i.type,enumerable:!1,configurable:!0}),i}const rt=(t,e)=>{if(!t)return[];return(m(t)?t:[t]).map(t=>ot(t,e))};function at(t){const e=ot(t);return Object.assign(Object.assign({id:S(t)?t:e.id},e),{type:e.type})}function ct(t){return S(t)?{type:B,event:t}:ht(t,{to:C.Internal})}function ht(t,e){return{to:e?e.to:void 0,type:q,event:b(t)?t:j(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:b(t)?t.name:s(t)}}function dt(t,e){return ht(t,Object.assign(Object.assign({},e),{to:C.Parent}))}function ut(){return dt(tt)}const lt=(t,e)=>({context:t,event:e});const ft=t=>({type:X,sendId:t});function pt(t){const e=at(t);return{type:V.Start,activity:e,exec:void 0}}function gt(t){const e=at(t);return{type:V.Stop,activity:e,exec:void 0}}const vt=t=>({type:G,assignment:t});function yt(t,e){const i=e?`#${e}`:"";return`${V.After}(${t})${i}`}function mt(t,e){const i=`${V.DoneState}.${t}`,s={type:i,data:e,toString:()=>i};return s}function bt(t,e){const i=`${V.DoneInvoke}.${t}`,s={type:i,data:e,toString:()=>i};return s}function St(t,e){const i=`${V.ErrorPlatform}.${t}`,s={type:i,data:e,toString:()=>i};return s}function wt(t,e){return ht((t,e)=>e,Object.assign(Object.assign({},e),{to:t}))}function xt(t,i,s,n,o){const[r,a]=v(o,t=>t.type===G);let c=r.length?function(t,i,s,n){return t?s.reduce((t,s)=>{const{assignment:o}=s,r={state:n,action:s,_event:i};let a={};if(b(o))a=o(t,i.data,r);else for(const s of e(o)){const e=o[s];a[s]=b(e)?e(t,i.data,r):e}return Object.assign({},t,a)},t):t}(s,n,r,i):s;return[u(a.map(e=>{var s;switch(e.type){case B:return{type:B,_event:N(e.event)};case q:return function(t,e,i,s){const n={_event:i},o=N(b(t.event)?t.event(e,i.data,n):t.event);let r;if(S(t.delay)){const o=s&&s[t.delay];r=b(o)?o(e,i.data,n):o}else r=b(t.delay)?t.delay(e,i.data,n):t.delay;const a=b(t.to)?t.to(e,i.data,n):t.to;return Object.assign(Object.assign({},t),{to:a,_event:o,event:o.data,delay:r})}(e,c,n,t.options.delays);case K:return((t,e,i)=>Object.assign(Object.assign({},t),{value:S(t.expr)?t.expr:t.expr(e,i.data,{_event:i})}))(e,c,n);case et:{const o=null===(s=e.conds.find(e=>{const s=w(e.cond,t.options.guards);return!s||T(t,s,c,n,i)}))||void 0===s?void 0:s.actions;if(!o)return[];const r=xt(t,i,c,n,rt(f(o)));return c=r[1],r[0]}case it:{const s=e.get(c,n.data);if(!s)return[];const o=xt(t,i,c,n,rt(f(s)));return c=o[1],o[0]}default:return ot(e,t.options.actions)}})),c]}function _t(t,e){const{exec:i}=t;return Object.assign(Object.assign({},t),{exec:void 0!==i?()=>i(e.context,e.event,{action:t,state:e,_event:e._event}):void 0})}class Ot{constructor(e){this.actions=[],this.activities=t,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||t,this.meta=e.meta||{},this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,Object.defineProperty(this,"nextEvents",{get:()=>{return t=this.configuration,u([...new Set(t.map(t=>t.ownEvents))]);var t}})}static from(t,e){if(t instanceof Ot)return t.context!==e?new Ot({value:t.value,context:e,_event:t._event,_sessionid:null,historyValue:t.historyValue,history:t.history,actions:[],activities:t.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):t;return new Ot({value:t,context:e,_event:st,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})}static create(t){return new Ot(t)}static inert(t,e){if(t instanceof Ot){if(!t.actions.length)return t;const i=st;return new Ot({value:t.value,context:e,_event:i,_sessionid:null,historyValue:t.historyValue,history:t.history,activities:t.activities,configuration:t.configuration,transitions:[],children:{}})}return Ot.from(t,e)}toStrings(t=this.value,i="."){if(S(t))return[t];const s=e(t);return s.concat(...s.map(e=>this.toStrings(t[e],i).map(t=>e+i+t)))}toJSON(){return P(this,["configuration","transitions"])}matches(t){return i(t,this.value)}}function Et(t){try{return"function"==typeof t.send}catch(t){return!1}}const jt={},Nt=t=>"#"===t[0];class $t{constructor(t,i,s){this.config=t,this.context=s,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.options=Object.assign({actions:{},guards:{},services:{},activities:{},delays:{}},i),this.parent=this.options._parent,this.key=this.config.key||this.options._key||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:"."),this.id=this.config.id||[this.machine.key,...this.path].join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&e(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.initial=this.config.initial,this.states=this.config.states?a(this.config.states,(t,e)=>{const i=new $t(t,{_parent:this,_key:e});return Object.assign(this.idMap,Object.assign({[i.id]:i},i.idMap)),i}):jt;let n=0;!function t(e){e.order=n++;for(const i of L(e))t(i)}(this),this.history=!0===this.config.history?"shallow":this.config.history||!1,this._transient=!!this.config.on&&(Array.isArray(this.config.on)?this.config.on.some(({event:t})=>""===t):""in this.config.on),this.strict=!!this.config.strict,this.onEntry=f(this.config.entry||this.config.onEntry).map(t=>ot(t)),this.onExit=f(this.config.exit||this.config.onExit).map(t=>ot(t)),this.meta=this.config.meta,this.data="final"===this.type?this.config.data:void 0,this.invoke=f(this.config.invoke).map((t,e)=>{if(O(t))return this.machine.options.services=Object.assign({[t.id]:t},this.machine.options.services),{type:W,src:t.id,id:t.id};if("string"!=typeof t.src){const i=`${this.id}:invocation[${e}]`;return this.machine.options.services=Object.assign({[i]:t.src},this.machine.options.services),Object.assign(Object.assign({type:W,id:i},t),{src:i})}return Object.assign(Object.assign({},t),{type:W,id:t.id||t.src,src:t.src})}),this.activities=f(this.config.activities).concat(this.invoke).map(t=>at(t)),this.transition=this.transition.bind(this)}_init(){this.__cache.transitions||A(this).forEach(t=>t.on)}withConfig(t,e=this.context){const{actions:i,activities:s,guards:n,services:o,delays:r}=this.options;return new $t(this.config,{actions:Object.assign(Object.assign({},i),t.actions),activities:Object.assign(Object.assign({},s),t.activities),guards:Object.assign(Object.assign({},n),t.guards),services:Object.assign(Object.assign({},o),t.services),delays:Object.assign(Object.assign({},r),t.delays)},e)}withContext(t){return new $t(this.config,this.options,t)}get definition(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:a(this.states,t=>t.definition),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.data,invoke:this.invoke}}toJSON(){return this.definition}get on(){if(this.__cache.on)return this.__cache.on;const t=this.transitions;return this.__cache.on=t.reduce((t,e)=>(t[e.eventType]=t[e.eventType]||[],t[e.eventType].push(e),t),{})}get after(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)}get transitions(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)}getCandidates(t){if(this.__cache.candidates[t])return this.__cache.candidates[t];const e=""===t,i=this.transitions.filter(i=>{const s=i.eventType===t;return e?s:s||"*"===i.eventType});return this.__cache.candidates[t]=i,i}getDelayedTransitions(){const t=this.config.after;if(!t)return[];const i=(t,e)=>{const i=yt(b(t)?`${this.id}:delay[${e}]`:t,this.id);return this.onEntry.push(ht(i,{delay:t})),this.onExit.push(ft(i)),i};return(m(t)?t.map((t,e)=>{const s=i(t.delay,e);return Object.assign(Object.assign({},t),{event:s})}):u(e(t).map((e,s)=>{const n=t[e],o=S(n)?{target:n}:n,r=isNaN(+e)?e:+e,a=i(r,s);return f(o).map(t=>Object.assign(Object.assign({},t),{event:a,delay:r}))}))).map(t=>{const{delay:e}=t;return Object.assign(Object.assign({},this.formatTransition(t)),{delay:e})})}getStateNodes(t){if(!t)return[];const i=t instanceof Ot?t.value:o(t,this.delimiter);if(S(i)){const t=this.getStateNode(i).initial;return void 0!==t?this.getStateNodes({[i]:t}):[this.states[i]]}const s=e(i);return s.map(t=>this.getStateNode(t)).concat(s.reduce((t,e)=>{const s=this.getStateNode(e).getStateNodes(i[e]);return t.concat(s)},[]))}handles(t){const e=s(t);return this.events.includes(e)}resolveState(t){const e=Array.from(R([],this.getStateNodes(t.value)));return new Ot(Object.assign(Object.assign({},t),{value:this.resolve(t.value),configuration:e}))}transitionLeafNode(t,e,i){const s=this.getStateNode(t).next(e,i);return s&&s.transitions.length?s:this.next(e,i)}transitionCompoundNode(t,i,s){const n=e(t),o=this.getStateNode(n[0])._transition(t[n[0]],i,s);return o&&o.transitions.length?o:this.next(i,s)}transitionParallelNode(t,i,s){const n={};for(const o of e(t)){const e=t[o];if(!e)continue;const r=this.getStateNode(o)._transition(e,i,s);r&&(n[o]=r)}const o=e(n).map(t=>n[t]),r=u(o.map(t=>t.transitions));if(!o.some(t=>t.transitions.length>0))return this.next(i,s);const a=u(o.map(t=>t.entrySet)),c=u(e(n).map(t=>n[t].configuration));return{transitions:r,entrySet:a,exitSet:u(o.map(t=>t.exitSet)),configuration:c,source:i,actions:u(e(n).map(t=>n[t].actions))}}_transition(t,i,s){return S(t)?this.transitionLeafNode(t,i,s):1===e(t).length?this.transitionCompoundNode(t,i,s):this.transitionParallelNode(t,i,s)}next(t,e){const s=e.name,n=[];let r,a=[];for(const c of this.getCandidates(s)){const{cond:d,in:u}=c,l=t.context,f=!u||(S(u)&&Nt(u)?t.matches(o(this.getStateNodeById(u).path,this.delimiter)):i(o(u,this.delimiter),h(this.path.slice(0,-2))(t.value)));let p=!1;try{p=!d||T(this.machine,d,l,e,t)}catch(t){throw new Error(`Unable to evaluate guard '${d.name||d.type}' in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(p&&f){void 0!==c.target&&(a=c.target),n.push(...c.actions),r=c;break}}if(!r)return;if(!a.length)return{transitions:[r],entrySet:[],exitSet:[],configuration:t.value?[this]:[],source:t,actions:n};const c=u(a.map(e=>this.getRelativeStateNodes(e,t.historyValue))),d=!!r.internal;return{transitions:[r],entrySet:d?[]:u(c.map(t=>this.nodesFromChild(t))),exitSet:d?[]:[this],configuration:c,source:t,actions:n}}nodesFromChild(t){if(t.escapes(this))return[];const e=[];let i=t;for(;i&&i!==this;)e.push(i),i=i.parent;return e.push(this),e}escapes(t){if(this===t)return!1;let e=this.parent;for(;e;){if(e===t)return!1;e=e.parent}return!0}getActions(t,e,i,s){const n=R([],s?this.getStateNodes(s.value):[this]),o=t.configuration.length?R(n,t.configuration):n;for(const e of o)F(n,e)||t.entrySet.push(e);for(const e of n)F(o,e)&&!F(t.exitSet,e.parent)||t.exitSet.push(e);t.source||(t.exitSet=[],t.entrySet.push(this));const r=u(t.entrySet.map(s=>{const n=[];if("final"!==s.type)return n;const o=s.parent;if(!o.parent)return n;n.push(mt(s.id,s.data),mt(o.id,s.data?p(s.data,e,i):void 0));const r=o.parent;return"parallel"===r.type&&L(r).every(e=>z(t.configuration,e))&&n.push(mt(r.id,r.data)),n}));t.exitSet.sort((t,e)=>e.order-t.order),t.entrySet.sort((t,e)=>t.order-e.order);const a=new Set(t.entrySet),c=new Set(t.exitSet),[h,d]=[u(Array.from(a).map(t=>[...t.activities.map(t=>pt(t)),...t.onEntry])).concat(r.map(ct)),u(Array.from(c).map(t=>[...t.onExit,...t.activities.map(t=>gt(t))]))];return rt(d.concat(t.actions).concat(h),this.machine.options.actions)}transition(t=this.initialState,e,i){const s=N(e);let n;if(t instanceof Ot)n=void 0===i?t:this.resolveState(Ot.from(t,i));else{const e=S(t)?this.resolve(r(this.getResolvedPath(t))):this.resolve(t),s=i||this.machine.context;n=this.resolveState(Ot.from(e,s))}if(this.strict&&!this.events.includes(s.name)&&(o=s.name,!/^(done|error)\./.test(o)))throw new Error(`Machine '${this.id}' does not accept event '${s.name}'`);var o;const a=this._transition(n.value,n,s)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:n,actions:[]},c=R([],this.getStateNodes(n.value)),h=a.configuration.length?R(c,a.configuration):c;return a.configuration=[...h],this.resolveTransition(a,n,s)}resolveRaisedTransition(t,e,i){const s=t.actions;return(t=this.transition(t,e))._event=i,t.event=i.data,t.actions.unshift(...s),t}resolveTransition(t,i,s=st,n=this.machine.context){const{configuration:o}=t,r=!i||t.transitions.length>0?D(this.machine,o):void 0,a=i?i.historyValue?i.historyValue:t.source?this.machine.historyValue(i.value):void 0:void 0,c=i?i.context:n,h=this.getActions(t,c,s,i),d=i?Object.assign({},i.activities):{};for(const t of h)t.type===J?d[t.activity.type]=t:t.type===U&&(d[t.activity.type]=!1);const[u,l]=xt(this,i,c,s,h),[f,p]=v(u,t=>t.type===B||t.type===q&&t.to===C.Internal),g=u.filter(t=>t.type===J&&t.activity.type===W).reduce((t,e)=>(t[e.activity.id]=function(t){const e={id:i=t.id,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),toJSON:()=>({id:i})};var i;return e.meta=t,e}(e.activity),t),i?Object.assign({},i.children):{}),m=r?t.configuration:i?i.configuration:[],b=m.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{}),w=z(m,this),x=new Ot({value:r||i.value,context:l,_event:s,_sessionid:i?i._sessionid:null,historyValue:r?a?(_=a,O=r,{current:O,states:y(_,O)}):void 0:i?i.historyValue:void 0,history:!r||t.source?i:void 0,actions:r?p:[],activities:r?d:i?i.activities:{},meta:r?b:i?i.meta:void 0,events:[],configuration:m,transitions:t.transitions,children:g,done:w});var _,O;const E=c!==l;x.changed=s.name===tt||E;const{history:j}=x;if(j&&delete j.history,!r)return x;let N=x;if(!w){for((this._transient||o.some(t=>t._transient))&&(N=this.resolveRaisedTransition(N,{type:H},s));f.length;){const t=f.shift();N=this.resolveRaisedTransition(N,t._event,s)}}const $=N.changed||(j?!!N.actions.length||E||typeof j.value!=typeof N.value||!function t(i,s){if(i===s)return!0;if(void 0===i||void 0===s)return!1;if(S(i)||S(s))return i===s;const n=e(i),o=e(s);return n.length===o.length&&n.every(e=>t(i[e],s[e]))}(N.value,j.value):void 0);return N.changed=$,N.historyValue=x.historyValue,N.history=j,N}getStateNode(t){if(Nt(t))return this.machine.getStateNodeById(t);if(!this.states)throw new Error(`Unable to retrieve child state '${t}' from '${this.id}'; no child states exist.`);const e=this.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${this.id}'`);return e}getStateNodeById(t){const e=Nt(t)?t.slice("#".length):t;if(e===this.id)return this;const i=this.machine.idMap[e];if(!i)throw new Error(`Child state node '#${e}' does not exist on machine '${this.id}'`);return i}getStateNodeByPath(t){if("string"==typeof t&&Nt(t))try{return this.getStateNodeById(t.slice(1))}catch(t){}const e=n(t,this.delimiter).slice();let i=this;for(;e.length;){const t=e.shift();if(!t.length)break;i=i.getStateNode(t)}return i}resolve(t){if(!t)return this.initialStateValue||jt;switch(this.type){case"parallel":return a(this.initialStateValue,(e,i)=>e?this.getStateNode(i).resolve(t[i]||e):jt);case"compound":if(S(t)){const e=this.getStateNode(t);return"parallel"===e.type||"compound"===e.type?{[t]:e.initialStateValue}:t}return e(t).length?a(t,(t,e)=>t?this.getStateNode(e).resolve(t):jt):this.initialStateValue||{};default:return t||jt}}getResolvedPath(t){if(Nt(t)){const e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error(`Unable to find state node '${t}'`);return e.path}return n(t,this.delimiter)}get initialStateValue(){if(this.__cache.initialStateValue)return this.__cache.initialStateValue;let t;if("parallel"===this.type)t=c(this.states,t=>t.initialStateValue||jt,t=>!("history"===t.type));else if(void 0!==this.initial){if(!this.states[this.initial])throw new Error(`Initial state '${this.initial}' not found on '${this.key}'`);t=I(this.states[this.initial])?this.initial:{[this.initial]:this.states[this.initial].initialStateValue}}return this.__cache.initialStateValue=t,this.__cache.initialStateValue}getInitialState(t,e){const i=this.getStateNodes(t);return this.resolveTransition({configuration:i,entrySet:i,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,void 0,e)}get initialState(){this._init();const{initialStateValue:t}=this;if(!t)throw new Error(`Cannot retrieve initial state from simple state '${this.id}'.`);return this.getInitialState(t)}get target(){let t;if("history"===this.type){const e=this.config;t=S(e.target)&&Nt(e.target)?r(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t}getRelativeStateNodes(t,e,i=!0){return i?"history"===t.type?t.resolveHistory(e):t.initialStateNodes:[t]}get initialStateNodes(){if(I(this))return[this];if("compound"===this.type&&!this.initial)return[this];return u(d(this.initialStateValue).map(t=>this.getFromRelativePath(t)))}getFromRelativePath(t){if(!t.length)return[this];const[e,...i]=t;if(!this.states)throw new Error(`Cannot retrieve subPath '${e}' from node with no states`);const s=this.getStateNode(e);if("history"===s.type)return s.resolveHistory();if(!this.states[e])throw new Error(`Child state '${e}' does not exist on '${this.id}'`);return this.states[e].getFromRelativePath(i)}historyValue(t){if(e(this.states).length)return{current:t||this.initialStateValue,states:c(this.states,(e,i)=>{if(!t)return e.historyValue();const s=S(t)?void 0:t[i];return e.historyValue(s||e.initialStateValue)},t=>!t.history)}}resolveHistory(t){if("history"!==this.type)return[this];const e=this.parent;if(!t){const t=this.target;return t?u(d(t).map(t=>e.getFromRelativePath(t))):e.initialStateNodes}const i=(s=e.path,n="states",t=>{let e=t;for(const t of s)e=e[n][t];return e})(t).current;var s,n;return S(i)?[e.getStateNode(i)]:u(d(i).map(t=>"deep"===this.history?e.getFromRelativePath(t):[e.states[t[0]]]))}get stateIds(){const t=u(e(this.states).map(t=>this.states[t].stateIds));return[this.id].concat(t)}get events(){if(this.__cache.events)return this.__cache.events;const{states:t}=this,i=new Set(this.ownEvents);if(t)for(const s of e(t)){const e=t[s];if(e.states)for(const t of e.events)i.add(`${t}`)}return this.__cache.events=Array.from(i)}get ownEvents(){const t=new Set(this.transitions.filter(t=>!(!t.target&&!t.actions.length&&t.internal)).map(t=>t.eventType));return Array.from(t)}resolveTarget(t){if(void 0!==t)return t.map(t=>{if(!S(t))return t;const e=t[0]===this.delimiter;if(e&&!this.parent)return this.getStateNodeByPath(t.slice(1));const i=e?this.key+t:t;if(!this.parent)return this.getStateNodeByPath(i);try{return this.parent.getStateNodeByPath(i)}catch(t){throw new Error(`Invalid transition definition for state node '${this.id}':\n${t.message}`)}})}formatTransition(t){const e=function(t){if(void 0!==t&&""!==t)return f(t)}(t.target),i="internal"in t?t.internal:!e||e.some(t=>S(t)&&t[0]===this.delimiter),{guards:s}=this.machine.options,n=this.resolveTarget(e),o=Object.assign(Object.assign({},t),{actions:rt(f(t.actions)),cond:w(t.cond,s),target:n,source:this,internal:i,eventType:t.event});return Object.defineProperty(o,"toJSON",{value:()=>Object.assign(Object.assign({},o),{target:o.target?o.target.map(t=>`#${t.id}`):void 0,source:"#{this.id}"})}),o}formatTransitions(){let t;if(this.config.on)if(Array.isArray(this.config.on))t=this.config.on;else{const i=this.config.on,s="*",n=i[s],o=void 0===n?[]:n,r=P(i,[s+""]);t=u(e(r).map(t=>$(t,r[t])).concat($("*",o)))}else t=[];const i=this.config.onDone?$(String(mt(this.id)),this.config.onDone):[],s=u(this.invoke.map(t=>{const e=[];return t.onDone&&e.push(...$(String(bt(t.id)),t.onDone)),t.onError&&e.push(...$(String(St(t.id)),t.onError)),e})),n=this.after,o=u([...i,...s,...t].map(t=>f(t).map(t=>this.formatTransition(t))));for(const t of n)o.push(t);return o}}function Tt(t,e,i=t.context){const s="function"==typeof i?i():i;return new $t(t,e,s)}function kt(t,e){const i="function"==typeof t.context?t.context():t.context;return new $t(t,e,i)}const Pt={deferEvents:!1};class Vt{constructor(t){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=Object.assign(Object.assign({},Pt),t)}initialize(t){if(this.initialized=!0,t){if(!this.options.deferEvents)return void this.schedule(t);this.process(t)}this.flushEvents()}schedule(t){if(this.initialized&&!this.processingEvent){if(0!==this.queue.length)throw new Error("Event queue should be empty when it is not processing events");this.process(t),this.flushEvents()}else this.queue.push(t)}clear(){this.queue=[]}flushEvents(){let t=this.queue.shift();for(;t;)this.process(t),t=this.queue.shift()}process(t){this.processingEvent=!0;try{t()}catch(t){throw this.clear(),t}finally{this.processingEvent=!1}}}const Ct=new Map;let It=0;const Lt={bookId:()=>`x:${It++}`,register:(t,e)=>(Ct.set(t,e),t),get:t=>Ct.get(t),free(t){Ct.delete(t)}},At={sync:!1,autoForward:!1},Rt=(()=>{const t=[];return(e,i)=>{e&&t.push(e);const s=i(e||t[t.length-1]);return e&&t.pop(),s}})();var Mt;!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(Mt||(Mt={}));class Dt{constructor(t,e=Dt.defaultOptions){this.machine=t,this.scheduler=new Vt,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this._status=Mt.NotStarted,this.children=new Map,this.forwardTo=new Set,this.init=this.start,this.send=(t,e)=>{if(m(t))return this.batch(t),this.state;const i=N(j(t,e));if(this._status===Mt.Stopped)return this.state;if(this._status===Mt.NotStarted&&this.options.deferEvents);else if(this._status!==Mt.Running)throw new Error(`Event "${i.name}" was sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ${JSON.stringify(i.data)}`);return this.scheduler.schedule(()=>{this.forward(i);const t=this.nextState(i);this.update(t,i)}),this._state},this.sendTo=(t,e)=>{const i=this.parent&&(e===C.Parent||this.parent.id===e),s=i?this.parent:Et(e)?e:this.children.get(e)||Lt.get(e);if(s)"machine"in s?s.send(Object.assign(Object.assign({},t),{name:t.name===Z?`${St(this.id)}`:t.name,origin:this.sessionId})):s.send(t.data);else if(!i)throw new Error(`Unable to send event to child '${e}' from service '${this.id}'.`)};const i=Object.assign(Object.assign({},Dt.defaultOptions),e),{clock:s,logger:n,parent:o,id:r}=i,a=void 0!==r?r:t.id;this.id=a,this.logger=n,this.clock=s,this.parent=o,this.options=i,this.scheduler=new Vt({deferEvents:this.options.deferEvents}),this.sessionId=Lt.bookId()}get initialState(){return this._initialState?this._initialState:Rt(this,()=>(this._initialState=this.machine.initialState,this._initialState))}get state(){return this._state}execute(t,e){for(const i of t.actions)this.exec(i,t,e)}update(t,e){if(t._sessionid=this.sessionId,this._state=t,this.options.execute&&this.execute(this.state),this.devTools&&this.devTools.send(e.data,t),t.event)for(const e of this.eventListeners)e(t.event);for(const e of this.listeners)e(t,t.event);for(const t of this.contextListeners)t(this.state.context,this.state.history?this.state.history.context:void 0);const i=z(t.configuration||[],this.machine);if(this.state.configuration&&i){const i=t.configuration.find(t=>"final"===t.type&&t.parent===this.machine),s=i&&i.data?p(i.data,t.context,e):void 0;for(const t of this.doneListeners)t(bt(this.id,s));this.stop()}}onTransition(t){return this.listeners.add(t),this._status===Mt.Running&&t(this.state,this.state.event),this}subscribe(t,e,i){if(!t)return{unsubscribe:()=>{}};let s,n=i;return"function"==typeof t?s=t:(s=t.next.bind(t),n=t.complete.bind(t)),this.listeners.add(s),this._status===Mt.Running&&s(this.state),n&&this.onDone(n),{unsubscribe:()=>{s&&this.listeners.delete(s),n&&this.doneListeners.delete(n)}}}onEvent(t){return this.eventListeners.add(t),this}onSend(t){return this.sendListeners.add(t),this}onChange(t){return this.contextListeners.add(t),this}onStop(t){return this.stopListeners.add(t),this}onDone(t){return this.doneListeners.add(t),this}off(t){return this.listeners.delete(t),this.eventListeners.delete(t),this.sendListeners.delete(t),this.stopListeners.delete(t),this.doneListeners.delete(t),this.contextListeners.delete(t),this}start(t){if(this._status===Mt.Running)return this;Lt.register(this.sessionId,this),this.initialized=!0,this._status=Mt.Running;const e=void 0===t?this.initialState:Rt(this,()=>{return!S(e=t)&&"value"in e&&"history"in e?this.machine.resolveState(t):this.machine.resolveState(Ot.from(t,this.machine.context));var e});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(()=>{this.update(e,st)}),this}stop(){for(const t of this.listeners)this.listeners.delete(t);for(const t of this.stopListeners)t(),this.stopListeners.delete(t);for(const t of this.contextListeners)this.contextListeners.delete(t);for(const t of this.doneListeners)this.doneListeners.delete(t);this.children.forEach(t=>{b(t.stop)&&t.stop()});for(const t of e(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.scheduler.clear(),this.initialized=!1,this._status=Mt.Stopped,Lt.free(this.sessionId),this}batch(t){if(this._status===Mt.NotStarted&&this.options.deferEvents);else if(this._status!==Mt.Running)throw new Error(`${t.length} event(s) were sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.`);this.scheduler.schedule(()=>{let e=this.state,i=!1;const s=[];for(const n of t){const t=N(n);this.forward(t),e=Rt(this,()=>this.machine.transition(e,t)),s.push(...e.actions.map(t=>_t(t,e))),i=i||!!e.changed}e.changed=i,e.actions=s,this.update(e,N(t[t.length-1]))})}sender(t){return this.send.bind(this,t)}nextState(t){const e=N(t);if(0===e.name.indexOf(Y)&&!this.state.nextEvents.some(t=>0===t.indexOf(Y)))throw e.data.data;return Rt(this,()=>this.machine.transition(this.state,e))}forward(t){for(const e of this.forwardTo){const i=this.children.get(e);if(!i)throw new Error(`Unable to forward event '${t}' from interpreter '${this.id}' to nonexistant child '${e}'.`);i.send(t)}}defer(t){this.delayedEventsMap[t.id]=this.clock.setTimeout(()=>{t.to?this.sendTo(t._event,t.to):this.send(t._event)},t.delay)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}exec(t,e,i){const{context:s,_event:n}=e,o=nt(t.type,i)||t.exec,r=b(o)?o:o?o.exec:t.exec;if(r)try{return r(s,n.data,{action:t,state:this.state,_event:n})}catch(t){throw this.parent&&this.parent.send({type:"xstate.error",data:t}),t}switch(t.type){case q:const e=t;if("number"==typeof e.delay)return void this.defer(e);e.to?this.sendTo(e._event,e.to):this.send(e._event);break;case X:this.cancel(t.sendId);break;case J:{const e=t.activity;if(!this.state.activities[e.type])break;if(e.type===V.Invoke){const t=this.machine.options.services?this.machine.options.services[e.src]:void 0,{id:i,data:o}=e,r="autoForward"in e?e.autoForward:!!e.forward;if(!t)return;const a=b(t)?t(s,n.data):t;g(a)?this.state.children[i]=this.spawnPromise(Promise.resolve(a),i):b(a)?this.state.children[i]=this.spawnCallback(a,i):x(a)?this.state.children[i]=this.spawnObservable(a,i):O(a)&&(this.state.children[i]=this.spawnMachine(o?a.withContext(p(o,s,n)):a,{id:i,autoForward:r}))}else this.spawnActivity(e);break}case U:this.stopChild(t.activity.id);break;case K:const{label:i,value:o}=t;i?this.logger(i,o):this.logger(o)}}removeChild(t){this.children.delete(t),this.forwardTo.delete(t),delete this.state.children[t]}stopChild(t){const e=this.children.get(t);e&&(this.removeChild(t),b(e.stop)&&e.stop())}spawn(t,e,i){if(g(t))return this.spawnPromise(Promise.resolve(t),e);if(b(t))return this.spawnCallback(t,e);if(Et(t))return this.spawnActor(t);if(x(t))return this.spawnObservable(t,e);if(O(t))return this.spawnMachine(t,Object.assign(Object.assign({},i),{id:e}));throw new Error(`Unable to spawn entity "${e}" of type "${typeof t}".`)}spawnMachine(t,e={}){const i=new Dt(t,Object.assign(Object.assign({},this.options),{parent:this,id:e.id||t.id})),s=Object.assign(Object.assign({},At),e);s.sync&&i.onTransition(t=>{this.send(tt,{state:t,id:i.id})});const n=i;return this.children.set(i.id,n),s.autoForward&&this.forwardTo.add(i.id),i.onDone(t=>{this.removeChild(i.id),this.send(N(t,{origin:i.id}))}).start(),n}spawnPromise(t,e){let i=!1;t.then(t=>{i||(this.removeChild(e),this.send(N(bt(e,t),{origin:e})))},t=>{if(!i){this.removeChild(e);const i=St(e,t);try{this.send(N(i,{origin:e}))}catch(t){this.devTools&&this.devTools.send(i,this.state),this.machine.strict&&this.stop()}}});const s={id:e,send:()=>{},subscribe:(e,i,s)=>{let n=!1;return t.then(t=>{n||(e&&e(t),n||s&&s())},t=>{n||i(t)}),{unsubscribe:()=>n=!0}},stop:()=>{i=!0},toJSON:()=>({id:e})};return this.children.set(e,s),s}spawnCallback(t,e){let i=!1;const s=new Set,n=new Set,o=t=>{n.forEach(e=>e(t)),i||this.send(t)};let r;try{r=t(o,t=>{s.add(t)})}catch(t){this.send(St(e,t))}if(g(r))return this.spawnPromise(r,e);const a={id:e,send:t=>s.forEach(e=>e(t)),subscribe:t=>(n.add(t),{unsubscribe:()=>{n.delete(t)}}),stop:()=>{i=!0,b(r)&&r()},toJSON:()=>({id:e})};return this.children.set(e,a),a}spawnObservable(t,e){const i=t.subscribe(t=>{this.send(N(t,{origin:e}))},t=>{this.removeChild(e),this.send(N(St(e,t),{origin:e}))},()=>{this.removeChild(e),this.send(N(bt(e),{origin:e}))}),s={id:e,send:()=>{},subscribe:(e,i,s)=>t.subscribe(e,i,s),stop:()=>i.unsubscribe(),toJSON:()=>({id:e})};return this.children.set(e,s),s}spawnActor(t){return this.children.set(t.id,t),t}spawnActivity(t){const e=this.machine.options&&this.machine.options.activities?this.machine.options.activities[t.type]:void 0;if(!e)return;const i=e(this.state.context,t);this.spawnEffect(t.id,i)}spawnEffect(t,e){this.children.set(t,{id:t,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),stop:e||void 0,toJSON:()=>({id:t})})}attachDev(){if(this.options.devTools&&"undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__){const t="object"==typeof this.options.devTools?this.options.devTools:void 0;this.devTools=window.__REDUX_DEVTOOLS_EXTENSION__.connect(Object.assign(Object.assign({name:this.id,autoPause:!0,stateSanitizer:t=>({value:t.value,context:t.context,actions:t.actions})},t),{features:Object.assign({jump:!1,skip:!1},t?t.features:void 0)}),this.machine),this.devTools.init(this.state)}}toJSON(){return{id:this.id}}[_](){return this}}Dt.defaultOptions=(t=>({execute:!0,deferEvents:!0,clock:{setTimeout:(e,i)=>t.setTimeout.call(null,e,i),clearTimeout:e=>t.clearTimeout.call(null,e)},logger:t.console.log.bind(console),devTools:!1}))("undefined"==typeof window?global:window),Dt.interpret=zt;function Ft(t,e){const i=(t=>S(t)?Object.assign(Object.assign({},At),{name:t}):Object.assign(Object.assign(Object.assign({},At),{name:E()}),t))(e);return Rt(void 0,e=>e?e.spawn(t,i.name,i):((t="null")=>({id:t,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),toJSON:()=>({id:t})}))(i.name))}function zt(t,e){return new Dt(t,e)}function Jt(t,e,i){const s=Ot.from(t,t instanceof Ot?t.context:void 0);for(const[t,i]of e)if(s.matches(t))return i(s);return i(s)}const Ut={raise:ct,send:ht,sendParent:dt,sendUpdate:ut,log:function(t=lt,e){return{type:K,label:e,expr:t}},cancel:ft,start:pt,stop:gt,assign:vt,after:yt,done:mt,respond:function(t,e){return ht(t,Object.assign(Object.assign({},e),{to:(t,e,{_event:i})=>i.origin}))},forwardTo:wt,escalate:function(t,e){return dt((e,i,s)=>({type:Z,data:b(t)?t(e,i,s):t}),Object.assign(Object.assign({},e),{to:C.Parent}))},choose:function(t){return{type:V.Choose,conds:t}},pure:function(t){return{type:V.Pure,get:t}}};export{V as ActionTypes,Dt as Interpreter,Tt as Machine,C as SpecialTargets,Ot as State,$t as StateNode,Ut as actions,vt as assign,kt as createMachine,bt as doneInvoke,wt as forwardTo,zt as interpret,k as mapState,Jt as matchState,i as matchesState,ht as send,dt as sendParent,ut as sendUpdate,Ft as spawn};
package/es/State.js CHANGED
@@ -66,6 +66,8 @@ function () {
66
66
  * @param configuration
67
67
  */
68
68
  function State(config) {
69
+ var _this = this;
70
+
69
71
  this.actions = [];
70
72
  this.activities = EMPTY_ACTIVITY_MAP;
71
73
  this.meta = {};
@@ -89,7 +91,7 @@ function () {
89
91
  this.done = !!config.done;
90
92
  Object.defineProperty(this, 'nextEvents', {
91
93
  get: function () {
92
- return nextEvents(config.configuration);
94
+ return nextEvents(_this.configuration);
93
95
  }
94
96
  });
95
97
  }
package/es/StateNode.d.ts CHANGED
@@ -125,7 +125,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
125
125
  * @param options Options (actions, guards, activities, services) to recursively merge with the existing options.
126
126
  * @param context Custom context (will override predefined context)
127
127
  */
128
- withConfig(options: Partial<MachineOptions<TContext, TEvent>>, context?: TContext | undefined): StateNode<TContext, TStateSchema, TEvent>;
128
+ withConfig(options: Partial<MachineOptions<TContext, TEvent>>, context?: TContext | undefined): StateNode<TContext, TStateSchema, TEvent, TTypestate>;
129
129
  /**
130
130
  * Clones this state machine with custom context.
131
131
  *
@@ -182,7 +182,6 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
182
182
  * this state node, it does not escape.
183
183
  */
184
184
  private escapes;
185
- private evaluateGuard;
186
185
  private getActions;
187
186
  /**
188
187
  * Determines the next state given the current `state` and sent `event`.
package/es/StateNode.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { __assign, __values, __spread, __read, __rest } from './_virtual/_tslib.js';
2
- import { DEFAULT_GUARD_TYPE, STATE_DELIMITER } from './constants.js';
2
+ import { STATE_DELIMITER } from './constants.js';
3
3
  import { IS_PRODUCTION } from './environment.js';
4
- import { mapValues, isArray, flatten, keys, toArray, toStateValue, isString, getEventType, matchesState, path, mapContext, toSCXMLEvent, pathToStateValue, isBuiltInEvent, partition, updateContext, warn, updateHistoryValue, toStatePath, mapFilterValues, toStatePaths, nestedPath, normalizeTarget, toGuard, toTransitionConfigArray, isMachine, isFunction } from './utils.js';
4
+ import { mapValues, isArray, flatten, keys, toArray, toStateValue, isString, getEventType, matchesState, path, evaluateGuard, mapContext, toSCXMLEvent, pathToStateValue, isBuiltInEvent, partition, updateHistoryValue, toStatePath, mapFilterValues, warn, toStatePaths, nestedPath, normalizeTarget, toGuard, toTransitionConfigArray, isMachine, isFunction } from './utils.js';
5
5
  import { SpecialTargets } from './types.js';
6
6
  import { getAllStateNodes, getConfiguration, has, getChildren, isInFinalState, getValue, isLeafNode } from './stateUtils.js';
7
- import { start as start$1, stop as stop$1, pure, log, send, raise as raise$1, invoke, update, nullEvent, assign } from './actionTypes.js';
8
- import { done, start, raise, stop, toActionObjects, toActionObject, resolveLog, resolveSend, resolveRaise, doneInvoke, error, toActivityDefinition, after, send as send$1, cancel, initEvent } from './actions.js';
7
+ import { start as start$1, stop as stop$1, invoke, update, nullEvent, raise as raise$1, send as send$1 } from './actionTypes.js';
8
+ import { done, start, raise, stop, toActionObjects, resolveActions, doneInvoke, error, toActionObject, toActivityDefinition, after, send, cancel, initEvent } from './actions.js';
9
9
  import { State, stateValuesEqual } from './State.js';
10
10
  import { createInvocableActor } from './Actor.js';
11
11
  var NULL_EVENT = '';
@@ -229,6 +229,7 @@ function () {
229
229
  id: this.id,
230
230
  key: this.key,
231
231
  version: this.version,
232
+ context: this.context,
232
233
  type: this.type,
233
234
  initial: this.initial,
234
235
  history: this.history,
@@ -237,8 +238,8 @@ function () {
237
238
  }),
238
239
  on: this.on,
239
240
  transitions: this.transitions,
240
- onEntry: this.onEntry,
241
- onExit: this.onExit,
241
+ entry: this.onEntry,
242
+ exit: this.onExit,
242
243
  activities: this.activities || [],
243
244
  meta: this.meta,
244
245
  order: this.order || -1,
@@ -323,7 +324,7 @@ function () {
323
324
  var delayRef = isFunction(delay) ? _this.id + ":delay[" + i + "]" : delay;
324
325
  var eventType = after(delayRef, _this.id);
325
326
 
326
- _this.onEntry.push(send$1(eventType, {
327
+ _this.onEntry.push(send(eventType, {
327
328
  delay: delay
328
329
  }));
329
330
 
@@ -548,7 +549,7 @@ function () {
548
549
  var guardPassed = false;
549
550
 
550
551
  try {
551
- guardPassed = !cond || this.evaluateGuard(cond, resolvedContext, _event, state);
552
+ guardPassed = !cond || evaluateGuard(this.machine, cond, resolvedContext, _event, state);
552
553
  } catch (err) {
553
554
  throw new Error("Unable to evaluate guard '" + (cond.name || cond.type) + "' in transition for event '" + eventName + "' in state node '" + this.id + "':\n" + err.message);
554
555
  }
@@ -648,27 +649,6 @@ function () {
648
649
  return true;
649
650
  };
650
651
 
651
- StateNode.prototype.evaluateGuard = function (guard, context, _event, state) {
652
- var guards = this.machine.options.guards;
653
- var guardMeta = {
654
- state: state,
655
- cond: guard,
656
- _event: _event
657
- }; // TODO: do not hardcode!
658
-
659
- if (guard.type === DEFAULT_GUARD_TYPE) {
660
- return guard.predicate(context, _event.data, guardMeta);
661
- }
662
-
663
- var condFn = guards[guard.type];
664
-
665
- if (!condFn) {
666
- throw new Error("Guard '" + guard.type + "' is not implemented on machine '" + this.machine.id + "'.");
667
- }
668
-
669
- return condFn(context, _event.data, guardMeta);
670
- };
671
-
672
652
  StateNode.prototype.getActions = function (transition, currentContext, _event, prevState) {
673
653
  var e_4, _a, e_5, _b;
674
654
 
@@ -729,18 +709,20 @@ function () {
729
709
  }
730
710
 
731
711
  var parent = sn.parent;
712
+
713
+ if (!parent.parent) {
714
+ return events;
715
+ }
716
+
732
717
  events.push(done(sn.id, sn.data), // TODO: deprecate - final states should not emit done events for their own state.
733
718
  done(parent.id, sn.data ? mapContext(sn.data, currentContext, _event) : undefined));
719
+ var grandparent = parent.parent;
734
720
 
735
- if (parent.parent) {
736
- var grandparent = parent.parent;
737
-
738
- if (grandparent.type === 'parallel') {
739
- if (getChildren(grandparent).every(function (parentNode) {
740
- return isInFinalState(transition.configuration, parentNode);
741
- })) {
742
- events.push(done(grandparent.id, grandparent.data));
743
- }
721
+ if (grandparent.type === 'parallel') {
722
+ if (getChildren(grandparent).every(function (parentNode) {
723
+ return isInFinalState(transition.configuration, parentNode);
724
+ })) {
725
+ events.push(done(grandparent.id, grandparent.data));
744
726
  }
745
727
  }
746
728
 
@@ -837,8 +819,6 @@ function () {
837
819
  StateNode.prototype.resolveTransition = function (stateTransition, currentState, _event, context) {
838
820
  var e_6, _a;
839
821
 
840
- var _this = this;
841
-
842
822
  if (_event === void 0) {
843
823
  _event = initEvent;
844
824
  }
@@ -880,42 +860,12 @@ function () {
880
860
  }
881
861
  }
882
862
 
883
- var _b = __read(partition(actions, function (action) {
884
- return action.type === assign;
885
- }), 2),
886
- assignActions = _b[0],
887
- otherActions = _b[1];
888
-
889
- var updatedContext = assignActions.length ? updateContext(currentContext, _event, assignActions, currentState) : currentContext;
890
- var resolvedActions = flatten(otherActions.map(function (actionObject) {
891
- switch (actionObject.type) {
892
- case raise$1:
893
- return resolveRaise(actionObject);
894
-
895
- case send:
896
- var sendAction = resolveSend(actionObject, updatedContext, _event, _this.machine.options.delays); // TODO: fix ActionTypes.Init
897
-
898
- if (!IS_PRODUCTION) {
899
- // warn after resolving as we can create better contextual message here
900
- warn(!isString(actionObject.delay) || typeof sendAction.delay === 'number', // tslint:disable-next-line:max-line-length
901
- "No delay reference for delay expression '" + actionObject.delay + "' was found on machine '" + _this.machine.id + "'");
902
- }
903
-
904
- return sendAction;
905
-
906
- case log:
907
- return resolveLog(actionObject, updatedContext, _event);
908
-
909
- case pure:
910
- return actionObject.get(updatedContext, _event.data) || [];
911
-
912
- default:
913
- return toActionObject(actionObject, _this.options.actions);
914
- }
915
- }));
863
+ var _b = __read(resolveActions(this, currentState, currentContext, _event, actions), 2),
864
+ resolvedActions = _b[0],
865
+ updatedContext = _b[1];
916
866
 
917
867
  var _c = __read(partition(resolvedActions, function (action) {
918
- return action.type === raise$1 || action.type === send && action.to === SpecialTargets.Internal;
868
+ return action.type === raise$1 || action.type === send$1 && action.to === SpecialTargets.Internal;
919
869
  }), 2),
920
870
  raisedEvents = _c[0],
921
871
  nonRaisedActions = _c[1];
@@ -953,7 +903,8 @@ function () {
953
903
  children: children,
954
904
  done: isDone
955
905
  });
956
- nextState.changed = _event.name === update || !!assignActions.length; // Dispose of penultimate histories to prevent memory leaks
906
+ var didUpdateContext = currentContext !== updatedContext;
907
+ nextState.changed = _event.name === update || didUpdateContext; // Dispose of penultimate histories to prevent memory leaks
957
908
 
958
909
  var history = nextState.history;
959
910
 
@@ -985,7 +936,7 @@ function () {
985
936
  } // Detect if state changed
986
937
 
987
938
 
988
- var changed = maybeNextState.changed || (history ? !!maybeNextState.actions.length || !!assignActions.length || typeof history.value !== typeof maybeNextState.value || !stateValuesEqual(maybeNextState.value, history.value) : undefined);
939
+ var changed = maybeNextState.changed || (history ? !!maybeNextState.actions.length || didUpdateContext || typeof history.value !== typeof maybeNextState.value || !stateValuesEqual(maybeNextState.value, history.value) : undefined);
989
940
  maybeNextState.changed = changed; // Preserve original history after raised events
990
941
 
991
942
  maybeNextState.historyValue = nextState.historyValue;
@@ -1475,7 +1426,8 @@ function () {
1475
1426
  }) : true;
1476
1427
  var guards = this.machine.options.guards;
1477
1428
  var target = this.resolveTarget(normalizedTarget);
1478
- return __assign(__assign({}, transitionConfig), {
1429
+
1430
+ var transition = __assign(__assign({}, transitionConfig), {
1479
1431
  actions: toActionObjects(toArray(transitionConfig.actions)),
1480
1432
  cond: toGuard(transitionConfig.cond, guards),
1481
1433
  target: target,
@@ -1483,6 +1435,18 @@ function () {
1483
1435
  internal: internal,
1484
1436
  eventType: transitionConfig.event
1485
1437
  });
1438
+
1439
+ Object.defineProperty(transition, 'toJSON', {
1440
+ value: function () {
1441
+ return __assign(__assign({}, transition), {
1442
+ target: transition.target ? transition.target.map(function (t) {
1443
+ return "#" + t.id;
1444
+ }) : undefined,
1445
+ source: "#{this.id}"
1446
+ });
1447
+ }
1448
+ });
1449
+ return transition;
1486
1450
  };
1487
1451
 
1488
1452
  StateNode.prototype.formatTransitions = function () {
@@ -15,5 +15,6 @@ export declare const errorExecution = ActionTypes.ErrorExecution;
15
15
  export declare const errorPlatform = ActionTypes.ErrorPlatform;
16
16
  export declare const error = ActionTypes.ErrorCustom;
17
17
  export declare const update = ActionTypes.Update;
18
+ export declare const choose = ActionTypes.Choose;
18
19
  export declare const pure = ActionTypes.Pure;
19
20
  //# sourceMappingURL=actionTypes.d.ts.map
package/es/actionTypes.js CHANGED
@@ -16,5 +16,6 @@ var errorExecution = ActionTypes.ErrorExecution;
16
16
  var errorPlatform = ActionTypes.ErrorPlatform;
17
17
  var error = ActionTypes.ErrorCustom;
18
18
  var update = ActionTypes.Update;
19
+ var choose = ActionTypes.Choose;
19
20
  var pure = ActionTypes.Pure;
20
- export { after, assign, cancel, doneState, error, errorExecution, errorPlatform, init, invoke, log, nullEvent, pure, raise, send, start, stop, update };
21
+ export { after, assign, cancel, choose, doneState, error, errorExecution, errorPlatform, init, invoke, log, nullEvent, pure, raise, send, start, stop, update };
package/es/actions.d.ts CHANGED
@@ -1,12 +1,14 @@
1
- import { Action, Event, EventObject, SingleOrArray, SendAction, SendActionOptions, CancelAction, ActionObject, ActionType, Assigner, PropertyAssigner, AssignAction, ActionFunction, ActionFunctionMap, ActivityActionObject, ActionTypes, ActivityDefinition, RaiseAction, RaiseActionObject, DoneEvent, ErrorPlatformEvent, DoneEventObject, SendExpr, SendActionObject, PureAction, LogExpr, LogAction, LogActionObject, DelayFunctionMap, SCXML, ExprWithMeta } from './types';
1
+ import { Action, Event, EventObject, SingleOrArray, SendAction, SendActionOptions, CancelAction, ActionObject, ActionType, Assigner, PropertyAssigner, AssignAction, ActionFunction, ActionFunctionMap, ActivityActionObject, ActionTypes, ActivityDefinition, RaiseAction, RaiseActionObject, DoneEvent, ErrorPlatformEvent, DoneEventObject, SendExpr, SendActionObject, PureAction, LogExpr, LogAction, LogActionObject, DelayFunctionMap, SCXML, ExprWithMeta, ChooseConditon, ChooseAction } from './types';
2
2
  import * as actionTypes from './actionTypes';
3
+ import { State } from './State';
4
+ import { StateNode } from './StateNode';
3
5
  export { actionTypes };
4
6
  export declare const initEvent: SCXML.Event<{
5
- type: ActionTypes.Init;
7
+ type: ActionTypes;
6
8
  }>;
7
9
  export declare function getActionFunction<TContext, TEvent extends EventObject>(actionType: ActionType, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | undefined;
8
10
  export declare function toActionObject<TContext, TEvent extends EventObject>(action: Action<TContext, TEvent>, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): ActionObject<TContext, TEvent>;
9
- export declare const toActionObjects: <TContext, TEvent extends EventObject>(action?: string | RaiseAction<import("./types").AnyEventObject> | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | AssignAction<Required<TContext>, TEvent> | SendAction<TContext, TEvent> | Action<TContext, TEvent>[] | undefined, actionFunctionMap?: Record<string, ActionFunction<TContext, TEvent> | ActionObject<TContext, TEvent>> | undefined) => ActionObject<TContext, TEvent>[];
11
+ export declare const toActionObjects: <TContext, TEvent extends EventObject>(action?: string | RaiseAction<import("./types").AnyEventObject> | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | AssignAction<Required<TContext>, TEvent> | SendAction<TContext, import("./types").AnyEventObject> | ChooseAction<TContext, TEvent> | Action<TContext, TEvent>[] | undefined, actionFunctionMap?: Record<string, ActionFunction<TContext, TEvent> | ActionObject<TContext, TEvent>> | undefined) => ActionObject<TContext, TEvent>[];
10
12
  export declare function toActivityDefinition<TContext, TEvent extends EventObject>(action: string | ActivityDefinition<TContext, TEvent>): ActivityDefinition<TContext, TEvent>;
11
13
  /**
12
14
  * Raises an event. This places the event in the internal event queue, so that
@@ -126,4 +128,6 @@ export declare function forwardTo<TContext, TEvent extends EventObject>(target:
126
128
  * @param options Options to pass into the send action creator.
127
129
  */
128
130
  export declare function escalate<TContext, TEvent extends EventObject, TErrorData = any>(errorData: TErrorData | ExprWithMeta<TContext, TEvent, TErrorData>, options?: SendActionOptions<TContext, TEvent>): SendAction<TContext, TEvent>;
131
+ export declare function choose<TContext, TEvent extends EventObject>(conds: Array<ChooseConditon<TContext, TEvent>>): ChooseAction<TContext, TEvent>;
132
+ export declare function resolveActions<TContext, TEvent extends EventObject>(machine: StateNode<TContext, any, TEvent>, currentState: State<TContext, TEvent> | undefined, currentContext: TContext, _event: SCXML.Event<TEvent>, actions: Array<ActionObject<TContext, TEvent>>): [Array<ActionObject<TContext, TEvent>>, TContext];
129
133
  //# sourceMappingURL=actions.d.ts.map
package/es/actions.js CHANGED
@@ -1,10 +1,9 @@
1
- import { __assign, __rest } from './_virtual/_tslib.js';
2
- import { toSCXMLEvent, isFunction, toEventObject, getEventType, isString, isArray } from './utils.js';
1
+ import { __assign, __read, __rest } from './_virtual/_tslib.js';
2
+ import { IS_PRODUCTION } from './environment.js';
3
+ import { toSCXMLEvent, isFunction, toEventObject, getEventType, isString, partition, updateContext, flatten, toArray, toGuard, evaluateGuard, warn, isArray } from './utils.js';
3
4
  import { SpecialTargets, ActionTypes } from './types.js';
4
- import { send as send$1, update, assign as assign$1, raise as raise$1, init, log as log$1, cancel as cancel$1, error as error$1 } from './actionTypes.js';
5
- var initEvent =
6
- /*#__PURE__*/
7
- toSCXMLEvent({
5
+ import { send as send$1, update, assign as assign$1, init, raise as raise$1, log as log$1, cancel as cancel$1, error as error$1, pure as pure$1, choose as choose$1 } from './actionTypes.js';
6
+ var initEvent = /*#__PURE__*/toSCXMLEvent({
8
7
  type: init
9
8
  });
10
9
 
@@ -361,6 +360,13 @@ function error(id, data) {
361
360
 
362
361
  return eventObject;
363
362
  }
363
+
364
+ function pure(getActions) {
365
+ return {
366
+ type: ActionTypes.Pure,
367
+ get: getActions
368
+ };
369
+ }
364
370
  /**
365
371
  * Forwards (sends) an event to a specified service.
366
372
  *
@@ -396,4 +402,77 @@ function escalate(errorData, options) {
396
402
  }));
397
403
  }
398
404
 
399
- export { after, assign, cancel, done, doneInvoke, error, escalate, forwardTo, getActionFunction, initEvent, log, raise, resolveLog, resolveRaise, resolveSend, respond, send, sendParent, sendUpdate, start, stop, toActionObject, toActionObjects, toActivityDefinition };
405
+ function choose(conds) {
406
+ return {
407
+ type: ActionTypes.Choose,
408
+ conds: conds
409
+ };
410
+ }
411
+
412
+ function resolveActions(machine, currentState, currentContext, _event, actions) {
413
+ var _a = __read(partition(actions, function (action) {
414
+ return action.type === assign$1;
415
+ }), 2),
416
+ assignActions = _a[0],
417
+ otherActions = _a[1];
418
+
419
+ var updatedContext = assignActions.length ? updateContext(currentContext, _event, assignActions, currentState) : currentContext;
420
+ var resolvedActions = flatten(otherActions.map(function (actionObject) {
421
+ var _a;
422
+
423
+ switch (actionObject.type) {
424
+ case raise$1:
425
+ return resolveRaise(actionObject);
426
+
427
+ case send$1:
428
+ var sendAction = resolveSend(actionObject, updatedContext, _event, machine.options.delays); // TODO: fix ActionTypes.Init
429
+
430
+ if (!IS_PRODUCTION) {
431
+ // warn after resolving as we can create better contextual message here
432
+ warn(!isString(actionObject.delay) || typeof sendAction.delay === 'number', // tslint:disable-next-line:max-line-length
433
+ "No delay reference for delay expression '" + actionObject.delay + "' was found on machine '" + machine.id + "'");
434
+ }
435
+
436
+ return sendAction;
437
+
438
+ case log$1:
439
+ return resolveLog(actionObject, updatedContext, _event);
440
+
441
+ case choose$1:
442
+ {
443
+ var chooseAction = actionObject;
444
+ var matchedActions = (_a = chooseAction.conds.find(function (condition) {
445
+ var guard = toGuard(condition.cond, machine.options.guards);
446
+ return !guard || evaluateGuard(machine, guard, updatedContext, _event, currentState);
447
+ })) === null || _a === void 0 ? void 0 : _a.actions;
448
+
449
+ if (!matchedActions) {
450
+ return [];
451
+ }
452
+
453
+ var resolved = resolveActions(machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions)));
454
+ updatedContext = resolved[1];
455
+ return resolved[0];
456
+ }
457
+
458
+ case pure$1:
459
+ {
460
+ var matchedActions = actionObject.get(updatedContext, _event.data);
461
+
462
+ if (!matchedActions) {
463
+ return [];
464
+ }
465
+
466
+ var resolved = resolveActions(machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions)));
467
+ updatedContext = resolved[1];
468
+ return resolved[0];
469
+ }
470
+
471
+ default:
472
+ return toActionObject(actionObject, machine.options.actions);
473
+ }
474
+ }));
475
+ return [resolvedActions, updatedContext];
476
+ }
477
+
478
+ export { after, assign, cancel, choose, done, doneInvoke, error, escalate, forwardTo, getActionFunction, initEvent, log, pure, raise, resolveActions, resolveLog, resolveRaise, resolveSend, respond, send, sendParent, sendUpdate, start, stop, toActionObject, toActionObjects, toActivityDefinition };
package/es/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { StateNode } from './StateNode';
4
4
  import { State } from './State';
5
5
  import { Machine, createMachine } from './Machine';
6
6
  import { Actor } from './Actor';
7
- import { raise, send, sendParent, sendUpdate, log, start, stop, assign, after, done, respond, doneInvoke, forwardTo, escalate } from './actions';
7
+ import { raise, send, sendParent, sendUpdate, log, start, stop, assign, after, done, respond, doneInvoke, forwardTo, escalate, choose, pure } from './actions';
8
8
  import { interpret, Interpreter, spawn } from './interpreter';
9
9
  import { matchState } from './match';
10
10
  declare const actions: {
@@ -22,6 +22,8 @@ declare const actions: {
22
22
  respond: typeof respond;
23
23
  forwardTo: typeof forwardTo;
24
24
  escalate: typeof escalate;
25
+ choose: typeof choose;
26
+ pure: typeof pure;
25
27
  };
26
28
  export { Actor, Machine, StateNode, State, matchesState, mapState, actions, assign, send, sendParent, sendUpdate, forwardTo, interpret, Interpreter, matchState, spawn, doneInvoke, createMachine };
27
29
  export * from './types';