Comparing version 4.0.0-7 to 4.0.0-8
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.xstateGraph={})}(this,function(t){"use strict";var e=function(){return(e=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function n(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&(n[r[i]]=t[r[i]])}return n}var r=".",i={},a=function(){function t(t,e,n,r,a,o,s,u){void 0===a&&(a=[]),void 0===o&&(o=i),void 0===s&&(s={}),void 0===u&&(u=[]),this.value=t,this.context=e,this.historyValue=n,this.history=r,this.actions=a,this.activities=o,this.data=s,this.events=u}return t.from=function(e,n){return e instanceof t?e.context!==n?new t(e.value,n,e.historyValue,e.history,[],e.activities,{},[]):e:new t(e,n,void 0,void 0,[],void 0,void 0,[])},t.inert=function(e,n){return e instanceof t?e.actions.length?new t(e.value,n,e.historyValue,e.history,[],e.activities,void 0,[]):e:t.from(e,n)},t.prototype.toStrings=function(t){var e=this;if(void 0===t&&(t=this.value),"string"==typeof t)return[t];var n=Object.keys(t);return n.concat.apply(n,n.map(function(n){return e.toStrings(t[n]).map(function(t){return n+"."+t})}))},t.prototype.matches=function(t){return b(t,this.value)},Object.defineProperty(t.prototype,"changed",{get:function(){return!!this.history&&(!!this.actions.length||typeof this.history.value!==this.value||("string"==typeof this.value?this.value!==this.history.value:function t(e,n){if(e===n)return!0;var r=Object.keys(e);var i=Object.keys(n);return r.length===i.length&&r.every(function(r){return t(e[r],n[r])})}(this.value,this.history.value)))},enumerable:!0,configurable:!0}),t}();function o(t){try{return"string"==typeof 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 s(t){try{return"string"==typeof t||"number"==typeof t?""+t:"function"==typeof t?t.name:t.type}catch(t){throw new Error("Actions must be strings or objects with a string action.type property.")}}function u(t,e){try{return Array.isArray(t)?t:t.toString().split(e)}catch(e){throw new Error("'"+t+"' is not a valid state path.")}}function c(t,e){return t instanceof a?t.value:"object"!=typeof t||t instanceof a?f(u(t,e)):t}function f(t){if(1===t.length)return t[0];for(var e={},n=e,r=0;r<t.length-1;r++)r===t.length-2?n[t[r]]=t[r+1]:(n[t[r]]={},n=n[t[r]]);return e}function h(t,e){var n={};return Object.keys(t).forEach(function(r,i){n[r]=e(t[r],r,t,i)}),n}function p(t,e,n){var r={};return Object.keys(t).forEach(function(i){var a=t[i];n(a)&&(r[i]=e(a,i,t))}),r}var y=function(t){return function(e){for(var n=e,r=0,i=t;r<i.length;r++){n=n[i[r]]}return n}};function v(t,e){return function(n){for(var r=n,i=0,a=t;i<a.length;i++){var o=a[i];r=r[e][o]}return r}}var l,d=function(t){return"string"==typeof t?[[t]]:m(Object.keys(t).map(function(e){return d(t[e]).map(function(t){return[e].concat(t)})}))},g=function(t){var e={};if(t&&1===t.length&&1===t[0].length)return t[0][0];for(var n=0,r=t;n<r.length;n++)for(var i=r[n],a=e,o=0;o<i.length;o++){var s=i[o];if(o===i.length-2){a[s]=i[o+1];break}a[s]=a[s]||{},a=a[s]}return e};function m(t){var e;return(e=[]).concat.apply(e,t)}function S(t){return Array.isArray(t)?t:void 0===t?[]:[t]}function b(t,e,n){void 0===n&&(n=r);var i=c(t,n),a=c(e,n);return"string"==typeof a?"string"==typeof i&&a===i:"string"==typeof i?i in a:Object.keys(i).every(function(t){return t in a&&b(i[t],a[t])})}!function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.Null="xstate.null",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.Log="xstate.log"}(l||(l={}));l.Start,l.Stop;var x=l.Raise,O=l.Send,j=l.Cancel,E=l.Null,w=l.Assign,N=(l.After,l.DoneState,l.Log,function(t,e){if("string"==typeof t||"number"==typeof t){var n={type:t};return void 0!==e&&(n.id=e),n}return t});function k(t,e){if(e){var n=e[t];if(n)return"function"==typeof n?n:n.exec}}var A=function(t,n){var r;if("string"==typeof t||"number"==typeof t)r={type:t,exec:k(t,n)};else{if("function"!=typeof t){var i=k(t.type,n);return i?e({},t,{exec:i}):t}r={type:t.name,exec:t}}return Object.defineProperty(r,"toString",{value:function(){return r.type},enumerable:!1}),r};function P(t){var n=A(t);return e({},n,{type:n.type,start:n.start?A(n.start):n.exec?A(n.exec):void 0,stop:n.stop?A(n.stop):void 0})}var V=function(t,e){return t?(Array.isArray(t)?t:[t]).map(function(t){return A(t,e)}):[]},_=function(t){return{type:x,event:t}};function J(t){var e=P(t);return{type:l.Start,activity:e,exec:e.start?e.start.exec:void 0}}function R(t,e){var n=e?"#"+e:"";return l.After+"("+t+")"+n}function T(t){return l.DoneState+"."+t}var M=".",C="",I={},F=[],B=function(t){return"#"===t[0]},H=function(){return{guards:I}},L=(function(){function t(n,r,i){void 0===r&&(r=H());var a=this;this._config=n,this.options=r,this.context=i,this.__cache={events:void 0,relativeValue:new Map,initialState:void 0},this.idMap={},this.key=n.key||n.id||"(machine)",this.type=n.type||(n.parallel?"parallel":n.states&&Object.keys(n.states).length?"compound":n.history?"history":"atomic"),this.parent=n.parent,this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=n.delimiter||(this.parent?this.parent.delimiter:M),this.id=n.id||(this.machine?[this.machine.key].concat(this.path).join(this.delimiter):this.key),this.initial=n.initial,this.order=n.order||-1,this.states=n.states?h(n.states,function(n,r,i,o){var s,u=new t(e({},n,{key:r,order:void 0===n.order?n.order:o,parent:a}));return Object.assign(a.idMap,e(((s={})[u.id]=u,s),u.idMap)),u}):I,this.history=!0===n.history?"shallow":n.history||!1,this.transient=!(!n.on||!n.on[C]),this.strict=!!n.strict,this.onEntry=S(n.onEntry),this.onExit=S(n.onExit),this.data=n.data,this.activities=S(n.activities).map(function(t){return a.resolveActivity(t)})}Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,type:this.type,initial:this.initial,history:this.history,states:h(this.states,function(t){return t.definition}),on:this.on,onEntry:this.onEntry,onExit:this.onExit,after:this.after,activities:this.activities||F,data:this.data,order:this.order||-1}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"config",{get:function(){var t=this._config;t.parent;return n(t,["parent"])},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"on",{get:function(){return this.formatTransitions()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){var t=this,n=this.config.after;if(!n)return F;if(Array.isArray(n))return n.map(function(n){return e({event:R(n.delay,t.id)},n,{actions:S(n.actions)})});var r=m(Object.keys(n).map(function(r){var i=n[r],a=+r,o=R(a,t.id);return"string"==typeof i?[{target:i,delay:a,event:o,actions:[]}]:S(i).map(function(t){return e({event:o,delay:a},t,{actions:S(t.actions)})})}));return r.sort(function(t,e){return t.delay-e.delay}),r},enumerable:!0,configurable:!0}),t.prototype.getStateNodes=function(t){var e,n=this;if(!t)return[];var r=t instanceof a?t.value:c(t,this.delimiter);if("string"==typeof r){var i=this.getStateNode(r).initial;return i?this.getStateNodes(((e={})[r]=i,e)):[this.states[r]]}var o=Object.keys(r);return o.map(function(t){return n.getStateNode(t)}).concat(o.reduce(function(t,e){var i=n.getStateNode(e).getStateNodes(r[e]);return t.concat(i)},[]))},t.prototype.handles=function(t){var e=o(t);return-1!==this.events.indexOf(e)},t.prototype.transitionLeafNode=function(t,e,n,r){var i=this.getStateNode(t),a=i.next(e,n,r);if(!a.value){var o=this.next(e,n,r),s=o.value,u=o.entryExitStates,c=o.actions,f=o.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set([i].concat(u?Array.from(u.exit):[]))},actions:c,paths:f}}return a},t.prototype.transitionNestedNode=function(t,e,n,r){var i=Object.keys(t),a=this.getStateNode(i[0]),o=a._transition(t[i[0]],e,n,r);if(!o.value){var s=this.next(e,n,r),u=s.value,c=s.entryExitStates,f=s.actions,h=s.paths;return{value:u,source:e,entryExitStates:{entry:c?c.entry:new Set,exit:new Set((o.entryExitStates?Array.from(o.entryExitStates.exit):[]).concat([a],c?Array.from(c.exit):[]))},actions:f,paths:h}}return o},t.prototype.transitionParallelNode=function(t,e,n,r){var i=this,a={};if(Object.keys(t).forEach(function(o){var s=t[o];if(s){var u=i.getStateNode(o)._transition(s,e,n,r);u.value,a[o]=u}}),!Object.keys(a).some(function(t){return void 0!==a[t].value})){var o=this.next(e,n,r),s=o.value,u=o.entryExitStates,c=o.actions,h=o.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set(Object.keys(this.states).map(function(t){return i.states[t]}).concat(u?Array.from(u.exit):[]))},actions:c,paths:h}}var p=m(Object.keys(a).map(function(t){return a[t].paths}));if(1===p.length&&!b(f(this.path),f(p[0])))return{value:this.machine.resolve(g(p)),source:e,entryExitStates:Object.keys(a).map(function(t){return a[t].entryExitStates}).reduce(function(t,e){var n=e,r=n.entry,i=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(r))),exit:new Set(Array.from(t.exit).concat(Array.from(i)))}},{entry:new Set,exit:new Set}),actions:m(Object.keys(a).map(function(t){return a[t].actions})),paths:p};var v=m(Object.keys(a).map(function(t){var n=a[t].value||e.value;return d(y(i.path)(n)[t]).map(function(e){return i.path.concat(t,e)})})),l=this.machine.resolve(g(v));return{value:l,source:e,entryExitStates:Object.keys(a).reduce(function(t,e){var n=a[e],r=n.value,i=n.entryExitStates;if(!r||!i)return t;var o=i.entry,s=i.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(o))),exit:new Set(Array.from(t.exit).concat(Array.from(s)))}},{entry:new Set,exit:new Set}),actions:m(Object.keys(a).map(function(t){return a[t].actions})),paths:d(l)}},t.prototype._transition=function(t,e,n,r){return"string"==typeof t?this.transitionLeafNode(t,e,n,r):1===Object.keys(t).length?this.transitionNestedNode(t,e,n,r):this.transitionParallelNode(t,e,n,r)},t.prototype.next=function(t,e,n){var r=this,i=e.type,a=this.on[i],o=this.transient?[{type:E}]:[];if(!a||!a.length)return{value:void 0,source:t,entryExitStates:void 0,actions:o,paths:[]};for(var s,u=[],f=0,h=a;f<h.length;f++){var p=h[f],v=p,l=v.cond,d=v.in,x=n||I,O=!d||b(c(d,this.delimiter),y(this.path.slice(0,-2))(t.value));if((!l||this.evaluateCond(l,x,e,t.value))&&O){u=S(p.target),o.push.apply(o,S(p.actions)),s=p;break}}if(s&&0===u.length)return{value:t.value,source:t,entryExitStates:void 0,actions:o,paths:[]};if(!s&&0===u.length)return{value:void 0,source:t,entryExitStates:void 0,actions:o,paths:[]};var j=m(u.map(function(e){return r.getRelativeStateNodes(e,t.historyValue)})),w=j.map(function(t){return t.path}),N=j.reduce(function(t,e){var n=r.getEntryExitStates(e,!!s.internal),i=n.entry,a=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(i))),exit:new Set(Array.from(t.exit).concat(Array.from(a)))}},{entry:new Set,exit:new Set});return{value:this.machine.resolve(g(m(u.map(function(e){return r.getRelativeStateNodes(e,t.historyValue).map(function(t){return t.path})})))),source:t,entryExitStates:N,actions:o,paths:w}},t.prototype.getStateNodeValueTree=function(t){var e,n=this;return"string"==typeof t?{stateNode:this,value:(e={},e[t]={stateNode:this.getStateNode(t),value:void 0},e)}:{stateNode:this,value:h(t,function(t,e){return n.getStateNode(e).getStateNodeValueTree(t)})}},t.prototype.getEntryExitStates=function(t,e){for(var n={entry:[],exit:[]},r=this.path,i=t.path,a=this.machine,o=0;o<Math.min(r.length,i.length);o++){var s=r[o];if(s!==i[o])break;a=a.getStateNode(s)}for(var u=a.path,c=a,f=0,h=r.slice(u.length);f<h.length;f++){var p=h[f];c=c.getStateNode(p),n.exit.unshift(c)}a===this&&(e||(n.exit.push(this),n.entry.push(this))),c=a;for(var y=0,v=i.slice(u.length);y<v.length;y++){p=v[y];c=c.getStateNode(p),n.entry.push(c)}return{entry:new Set(n.entry),exit:new Set(n.exit)}},t.prototype.evaluateCond=function(t,e,n,r){var i,a=this.machine.options.guards;if("string"==typeof t){if(!a||!a[t])throw new Error("Condition '"+t+"' is not implemented on machine '"+this.machine.id+"'.");i=a[t]}else i=t;return i(e,n,r)},Object.defineProperty(t.prototype,"delays",{get:function(){var t=this;return Array.from(new Set(this.after.map(function(t){return t.delay}))).map(function(e){return{id:t.id,delay:e}})},enumerable:!0,configurable:!0}),t.prototype.getActions=function(t){var e=this,n=new Set,r={entry:t.entryExitStates?m(Array.from(t.entryExitStates.entry).map(function(r){if("final"===r.type){var i=e.getStateNodeValueTree(t.value);n.add(T(r.id));var a=r.parent?r.parent.parent:void 0;if(a){var s=v(a.path,"value")(i);Object.keys(s.value).every(function(t){return Object.keys(s.value[t].value).every(function(e){return"final"===s.value[t].value[e].stateNode.type})})&&n.add(T(s.stateNode.id))}}return r.onEntry.concat(r.activities.map(function(t){return J(t)}),r.delays.map(function(t){var e,n,r=t.delay,i=t.id;return e=R(r,i),n={delay:r},{type:O,event:N(e),delay:n?n.delay:void 0,id:n&&void 0!==n.id?n.id:o(e)}}))})).concat(Array.from(n).map(_)):[],exit:t.entryExitStates?m(Array.from(t.entryExitStates.exit).map(function(t){return t.onExit.concat(t.activities.map(function(t){return function(t){var e=P(t);return{type:l.Stop,activity:e,exec:e.stop?e.stop.exec:void 0}}(t)}),t.delays.map(function(t){var e,n=t.delay,r=t.id;return e=R(n,r),{type:j,sendId:e}}))})):[]};return r.exit.concat(t.actions).concat(r.entry).map(function(t){return"string"==typeof t?e.resolveAction(t):t})},t.prototype.resolveAction=function(t){var e=this.machine.options.actions;return(e?e[t]:t)||t},t.prototype.resolveActivity=function(t){var n=this.machine.options.activities;return"string"==typeof t?P(n?e({type:t},n[t]):t):t},t.prototype.getActivities=function(t,n){if(!t)return I;var r=e({},n);return Array.from(t.exit).forEach(function(t){t.activities&&t.activities.forEach(function(t){r[t.type]=!1})}),Array.from(t.entry).forEach(function(t){t.activities&&t.activities.forEach(function(t){r[t.type]=!0})}),r},t.prototype.transition=function(t,e,n){var r="string"==typeof t?this.resolve(f(this.getResolvedPath(t))):t instanceof a?t:this.resolve(t),i=n||(t instanceof a?t.context:void 0),o=N(e),s=o.type;if(this.strict&&-1===this.events.indexOf(s))throw new Error("Machine '"+this.id+"' does not accept event '"+s+"'");var u=a.from(r,i),c=this._transition(u.value,u,o,i);return this.resolveTransition(c,u,o)},t.prototype.resolveTransition=function(e,n,r){var i,o=n.historyValue?n.historyValue:e.source?this.machine.historyValue(n.value):void 0;try{this.ensureValidPaths(e.paths)}catch(t){throw new Error("Event '"+(r?r.type:"none")+"' leads to an invalid configuration: "+t.message)}var s=this.getActions(e),u=this.getActivities(e.entryExitStates,n.activities),c=s.filter(function(t){return"object"==typeof t&&(t.type===x||t.type===E)}),f=s.filter(function(t){return"object"!=typeof t||t.type!==x&&t.type!==E&&t.type!==w}),h=s.filter(function(t){return"object"==typeof t&&t.type===w}),p=n.context?h.reduce(function(t,e){var n=e.assignment,i={};return"function"==typeof n?i=n(t,r||{type:"xstate.init"}):Object.keys(n).forEach(function(e){var a=n[e];i[e]="function"==typeof a?a(t,r):a}),Object.assign({},t,i)},n.context):n.context,y=e.value?this.getStateNodes(e.value):[];y.some(function(t){return t.transient})&&c.push({type:E});var v=[this].concat(y).reduce(function(t,e){return void 0!==e.data&&(t[e.id]=e.data),t},{}),l=e.value?new a(e.value,p,o?t.updateHistoryValue(o,e.value):void 0,e.source?n:void 0,V(f,this.options.actions),u,v,c):void 0;if(!l)return a.inert(n,p);delete n.history;for(var d=l;c.length;){var g=d.actions,m=c.shift();(i=(d=this.transition(d,m.type===E?C:m.event,d.context)).actions).unshift.apply(i,g)}return d},t.prototype.ensureValidPaths=function(t){var e=this,n=new Map;t:for(var r=0,i=m(t.map(function(t){return e.getRelativeStateNodes(t)}));r<i.length;r++)for(var a=i[r],o=a;o.parent;){if(n.has(o.parent)){if("parallel"===o.parent.type)continue t;throw new Error("State node '"+a.id+"' shares parent '"+o.parent.id+"' with state node '"+n.get(o.parent).map(function(t){return t.id})+"'")}n.get(o.parent)?n.get(o.parent).push(a):n.set(o.parent,[a]),o=o.parent}},t.prototype.getStateNode=function(t){if(B(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.");var e=this.states[t];if(!e)throw new Error("Child state '"+t+"' does not exist on '"+this.id+"'");return e},t.prototype.getStateNodeById=function(t){var e=B(t)?t.slice("#".length):t;if(e===this.id)return this;var n=this.machine.idMap[e];if(!n)throw new Error("Substate '#"+e+"' does not exist on '"+this.id+"'");return n},t.prototype.getStateNodeByPath=function(t){for(var e=u(t,this.delimiter),n=this;e.length;){var r=e.shift();n=n.getStateNode(r)}return n},t.prototype.resolve=function(t){var e,n=this;if("string"==typeof t){var r=this.getStateNode(t);return r.initial?((e={})[t]=r.initialStateValue,e):t}return"parallel"===this.type?h(this.initialStateValue,function(e,r){return e?n.getStateNode(r).resolve(t[r]||e):I}):h(t,function(t,e){return t?n.getStateNode(e).resolve(t):I})},Object.defineProperty(t.prototype,"resolvedStateValue",{get:function(){var t,e,n=this.key;return"parallel"===this.type?((t={})[n]=p(this.states,function(t){return t.resolvedStateValue[t.key]},function(t){return!t.history}),t):this.initial?((e={})[n]=this.states[this.initial].resolvedStateValue,e):n},enumerable:!0,configurable:!0}),t.prototype.getResolvedPath=function(t){if(B(t)){var e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error("Unable to find state node '"+t+"'");return e.path}return u(t,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){if(this.__cache.initialState)return this.__cache.initialState;var t="parallel"===this.type?p(this.states,function(t){return t.initialStateValue||I},function(t){return!t.history}):"string"==typeof this.resolvedStateValue?void 0:this.resolvedStateValue[this.key];return this.__cache.initialState=t,this.__cache.initialState},enumerable:!0,configurable:!0}),t.prototype.getState=function(t,e){var n=this;void 0===e&&(e=this.machine.context);var r={},i=[];this.getStateNodes(t).forEach(function(t){t.onEntry&&i.push.apply(i,t.onEntry),t.activities&&t.activities.forEach(function(t){r[o(t)]=!0,i.push(J(t))})});var s=i.filter(function(t){return"object"==typeof t&&(t.type===x||t.type===E)}),u=i.filter(function(t){return"object"==typeof t&&t.type===w}),c=e?u.reduce(function(t,e){var n=e.assignment,r={};return"function"==typeof n?r=n(t,{type:"init"}):Object.keys(n).forEach(function(e){var i=n[e];r[e]="function"==typeof i?i(t,{type:"init"}):i}),Object.assign({},t,r)},e):e,f=new a(t,c,void 0,void 0,V(i,this.options.actions),r,void 0,[]);return s.reduce(function(t,e){var r,i=t.actions;return(r=(t=n.transition(t,e.type===E?C:e.event,t.context)).actions).unshift.apply(r,i),t},f)},Object.defineProperty(t.prototype,"initialState",{get:function(){var t=this.initialStateValue;if(!t)throw new Error("Cannot retrieve initial state from simple state '"+this.id+"'.");var e=this.getState(t);return this.resolveTransition({value:e.value,source:void 0,entryExitStates:{entry:new Set(this.getStateNodes(e.value)),exit:new Set},actions:[],paths:[]},e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var t;if(this.history){var e=this.config;t=e.target&&"string"==typeof e.target&&B(e.target)?f(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t},enumerable:!0,configurable:!0}),t.prototype.getStates=function(t){var e=this;if("string"==typeof t)return[this.states[t]];var n=[];return Object.keys(t).forEach(function(r){n.push.apply(n,e.states[r].getStates(t[r]))}),n},t.prototype.getRelativeStateNodes=function(t,e,n){if(void 0===n&&(n=!0),"string"==typeof t&&B(t)){var r=this.getStateNodeById(t);return n?r.history?r.resolveHistory(e):r.initialStateNodes:[r]}var i=u(t,this.delimiter),a=(this.parent||this).getFromRelativePath(i,e);return n?m(a.map(function(t){return t.initialStateNodes})):a},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var t=this;if("atomic"===this.type||"final"===this.type)return[this];var e=this.initialStateValue;return m(d(e).map(function(e){return t.getFromRelativePath(e)}))},enumerable:!0,configurable:!0}),t.prototype.getFromRelativePath=function(t,e){if(!t.length)return[this];var n=t[0],r=t.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '"+n+"' from node with no states");var i=this.getStateNode(n);if(i.history)return i.resolveHistory(e);if(!this.states[n])throw new Error("Child state '"+n+"' does not exist on '"+this.id+"'");return this.states[n].getFromRelativePath(r,e)},t.updateHistoryValue=function(t,e){return{current:e,states:function t(e,n){return h(e.states,function(e,r){if(e){var i=("string"==typeof n?void 0:n[r])||(e?e.current:void 0);if(i)return{current:i,states:t(e,i)}}})}(t,e)}},t.prototype.historyValue=function(t){if(Object.keys(this.states).length)return{current:t||this.initialStateValue,states:p(this.states,function(e,n){if(!t)return e.historyValue();var r="string"==typeof t?void 0:t[n];return e.historyValue(r||e.initialStateValue)},function(t){return!t.history})}},t.prototype.resolveHistory=function(t){var e=this;if(!this.history)return[this];var n=this.parent;if(!t)return this.target?m(d(this.target).map(function(t){return n.getFromRelativePath(t)})):this.parent.initialStateNodes;var r=v(n.path,"states")(t).current;return"string"==typeof r?[n.getStateNode(r)]:m(d(r).map(function(t){return"deep"===e.history?n.getFromRelativePath(t):[n.states[t[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var t=this,e=m(Object.keys(this.states).map(function(e){return t.states[e].stateIds}));return[this.id].concat(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){if(this.__cache.events)return this.__cache.events;var t=this.states,e=new Set(Object.keys(this.on));return t&&Object.keys(t).forEach(function(n){var r=t[n];if(r.states)for(var i=0,a=r.events;i<a.length;i++){var o=a[i];e.add(""+o)}}),this.__cache.events=Array.from(e)},enumerable:!0,configurable:!0}),t.prototype.formatTransition=function(t,n,r){var i=this,a=!!n&&n.internal;if(void 0===t||""===t)return e({},n,{actions:n?S(n.actions):[],target:void 0,internal:!n||(void 0===n.internal||n.internal),event:r});var o=S(t).map(function(t){var e="string"==typeof t&&t[0]===i.delimiter;return a=a||e,e&&!i.parent?t.slice(1):e?i.key+t:t});return e({},n,{actions:n?S(n.actions):[],target:o,internal:a,event:r})},t.prototype.formatTransitions=function(){var t=this,e=this.config.on||I,n=this.after,r=h(e,function(e,n){return void 0===e?[{target:void 0,event:n,actions:[]}]:Array.isArray(e)?e.map(function(e){return t.formatTransition(e.target,e,n)}):"string"==typeof e?[t.formatTransition([e],void 0,n)]:[t.formatTransition(e.target,e,n)]});return n.forEach(function(t){r[t.event]=r[t.event]||[],r[t.event].push(t)}),r}}(),{});function D(t,e){return m(t.definition.on[e].map(function(n){var r=n.target?[].concat(n.target):void 0;return r?r.map(function(r){try{var i=r?t.getRelativeStateNodes(r,void 0,!1)[0]:t;return{source:t,target:i,event:e,actions:n.actions?n.actions.map(s):[],cond:n.cond,transition:n}}catch(e){return void console.warn("Target '"+r+"' not found on '"+t.id+"'")}}).filter(function(t){return void 0!==t}):[{source:t,target:t,event:e,actions:n.actions?n.actions.map(s):[],cond:n.cond,transition:n}]}))}function U(t,e){var n={},r=t.events;return function i(a){var o=JSON.stringify(a);if(!n[o]){n[o]={};for(var s=0,u=r;s<u.length;s++){var c=u[s],f=t.transition(a,c,e);n[o][c]={state:f.value},i(f.value)}}}(t.initialState.value),n}function z(t){if("string"==typeof t||"number"==typeof t)return""+t;var e=t.type,r=n(t,["type"]);return e+" | "+JSON.stringify(r)}function G(t){var e=t.value,n=t.context;return JSON.stringify(e)+" | "+JSON.stringify(n)}function q(t,e){var n=e.events,r=e.filter,i={},a=m(t.events.map(function(t){return n[t]||[t]}));return function e(n){var o=G(n);if(!i[o]){i[o]={};for(var s=0,u=a;s<u.length;s++){var c=u[s],f=t.transition(n,c);r&&!r(f)||(i[o][z(c)]={value:f.value,context:f.context},e(f))}}}(t.initialState),i}function K(t,e){var n;if(!t.states)return L;var r=U(t,e),i=((n={})[JSON.stringify(t.initialState.value)]=[],n),a=new Set;return function e(n){var o=JSON.stringify(n);a.add(o);for(var s=r[o],u=0,f=Object.keys(s);u<f.length;u++){var h=f[u];if(l=s[h].state){var p=JSON.stringify(c(l,t.delimiter));(!i[p]||i[p].length>i[o].length+1)&&(i[p]=(i[o]||[]).concat([{state:n,event:h}]))}}for(var y=0,v=Object.keys(s);y<v.length;y++){var l;(l=s[v[y]].state)&&(p=JSON.stringify(l),a.has(p)||e(l))}return i}(t.initialState.value),i}function Q(t,e){if(!t.states)return L;var n=U(t,e),r=new Set,i=[],a={};var o=JSON.stringify(t.initialState.value);return Object.keys(n).forEach(function(t){!function t(e,o){if(r.add(e),e===o)a[o]=a[o]||[],a[o].push(i.slice());else for(var s=0,u=Object.keys(n[e]);s<u.length;s++){var c=u[s],f=n[e][c].state;if(f){var h=JSON.stringify(f);r.has(h)||(i.push({state:JSON.parse(e),event:c}),t(h,o))}}i.pop(),r.delete(e)}(o,t)}),a}t.getNodes=function t(e){var n=e.states;return Object.keys(n).reduce(function(e,r){var i=n[r],a=t(n[r]);return e.push.apply(e,[i].concat(a)),e},[])},t.getEventEdges=D,t.getEdges=function t(e,n){var r=(n||{}).depth,i=void 0===r?null:r,a=[];return e.states&&null===i?Object.keys(e.states).forEach(function(n){a.push.apply(a,t(e.states[n]))}):i&&i>0&&Object.keys(e.states).forEach(function(n){a.push.apply(a,t(e.states[n],{depth:i-1}))}),Object.keys(e.on).forEach(function(t){a.push.apply(a,D(e,t))}),a},t.getAdjacencyMap=U,t.deserializeStateString=function(t){var e=t.split(" | "),n=e[0],r=e[1];return{value:JSON.parse(n),context:JSON.parse(r)}},t.getValueAdjacencyMap=q,t.getShortestValuePaths=function(t,e){if(!t.states)return L;var n=q(t,e),r={},i=new Set;return function t(e){var o=G(e);i.add(o);for(var s=n[o],u=0,c=Object.keys(s);u<c.length;u++){var f=c[u],h=s[f],p=h.value,y=h.context;if(p){var v=G(S=a.from(p,y));(!r[v]||r[v].length>r[o].length+1)&&(r[v]=(r[o]||[]).concat([{state:p,event:f}]))}}for(var l=0,d=Object.keys(s);l<d.length;l++){var g=s[d[l]],m=(p=g.value,g.context);if(p){var S=a.from(p,m);v=G(a.from(p,m)),i.has(v)||t(S)}}return r}(t.initialState),r},t.getShortestPaths=K,t.getShortestPathsAsArray=function(t,e){var n=K(t,e);return Object.keys(n).map(function(t){return{state:JSON.parse(t),path:n[t]}})},t.getSimplePaths=Q,t.getSimplePathsAsArray=function(t,e){var n=Q(t,e);return Object.keys(n).map(function(t){return{state:JSON.parse(t),paths:n[t]}})},Object.defineProperty(t,"__esModule",{value:!0})}); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.xstateGraph={})}(this,function(t){"use strict";var e=function(){return(e=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function n(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&(n[r[i]]=t[r[i]])}return n}var r=".",i={},a=function(){function t(t,e,n,r,a,o,s,u){void 0===a&&(a=[]),void 0===o&&(o=i),void 0===s&&(s={}),void 0===u&&(u=[]),this.value=t,this.context=e,this.historyValue=n,this.history=r,this.actions=a,this.activities=o,this.data=s,this.events=u}return t.from=function(e,n){return e instanceof t?e.context!==n?new t(e.value,n,e.historyValue,e.history,[],e.activities,{},[]):e:new t(e,n,void 0,void 0,[],void 0,void 0,[])},t.inert=function(e,n){return e instanceof t?e.actions.length?new t(e.value,n,e.historyValue,e.history,[],e.activities,void 0,[]):e:t.from(e,n)},t.prototype.toStrings=function(t){var e=this;if(void 0===t&&(t=this.value),"string"==typeof t)return[t];var n=Object.keys(t);return n.concat.apply(n,n.map(function(n){return e.toStrings(t[n]).map(function(t){return n+"."+t})}))},t.prototype.matches=function(t){return b(t,this.value)},Object.defineProperty(t.prototype,"changed",{get:function(){if(this.history)return!!this.actions.length||typeof this.history.value!=typeof this.value||("string"==typeof this.value?this.value!==this.history.value:function t(e,n){if(e===n)return!0;var r=Object.keys(e);var i=Object.keys(n);return r.length===i.length&&r.every(function(r){return t(e[r],n[r])})}(this.value,this.history.value))},enumerable:!0,configurable:!0}),t}();function o(t){try{return"string"==typeof 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 s(t){try{return"string"==typeof t||"number"==typeof t?""+t:"function"==typeof t?t.name:t.type}catch(t){throw new Error("Actions must be strings or objects with a string action.type property.")}}function u(t,e){try{return Array.isArray(t)?t:t.toString().split(e)}catch(e){throw new Error("'"+t+"' is not a valid state path.")}}function c(t,e){return t instanceof a?t.value:"object"!=typeof t||t instanceof a?f(u(t,e)):t}function f(t){if(1===t.length)return t[0];for(var e={},n=e,r=0;r<t.length-1;r++)r===t.length-2?n[t[r]]=t[r+1]:(n[t[r]]={},n=n[t[r]]);return e}function h(t,e){var n={};return Object.keys(t).forEach(function(r,i){n[r]=e(t[r],r,t,i)}),n}function p(t,e,n){var r={};return Object.keys(t).forEach(function(i){var a=t[i];n(a)&&(r[i]=e(a,i,t))}),r}var y=function(t){return function(e){for(var n=e,r=0,i=t;r<i.length;r++){n=n[i[r]]}return n}};function v(t,e){return function(n){for(var r=n,i=0,a=t;i<a.length;i++){var o=a[i];r=r[e][o]}return r}}var l,d=function(t){return"string"==typeof t?[[t]]:m(Object.keys(t).map(function(e){return d(t[e]).map(function(t){return[e].concat(t)})}))},g=function(t){var e={};if(t&&1===t.length&&1===t[0].length)return t[0][0];for(var n=0,r=t;n<r.length;n++)for(var i=r[n],a=e,o=0;o<i.length;o++){var s=i[o];if(o===i.length-2){a[s]=i[o+1];break}a[s]=a[s]||{},a=a[s]}return e};function m(t){var e;return(e=[]).concat.apply(e,t)}function S(t){return Array.isArray(t)?t:void 0===t?[]:[t]}function b(t,e,n){void 0===n&&(n=r);var i=c(t,n),a=c(e,n);return"string"==typeof a?"string"==typeof i&&a===i:"string"==typeof i?i in a:Object.keys(i).every(function(t){return t in a&&b(i[t],a[t])})}!function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.Null="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.Log="xstate.log",t.Init="xstate.init"}(l||(l={}));l.Start,l.Stop;var x=l.Raise,O=l.Send,j=l.Cancel,E=l.Null,w=l.Assign;l.After,l.DoneState,l.Log,l.Init;function N(t){return"string"==typeof t||"number"==typeof t?{type:t}:t}function k(t,e){if(e){var n=e[t];if(n)return"function"==typeof n?n:n.exec}}var A=function(t,n){var r;if("string"==typeof t||"number"==typeof t)r={type:t,exec:k(t,n)};else{if("function"!=typeof t){var i=k(t.type,n);return i?e({},t,{exec:i}):t}r={type:t.name,exec:t}}return Object.defineProperty(r,"toString",{value:function(){return r.type},enumerable:!1}),r};function P(t){var n=A(t);return e({},n,{type:n.type,start:n.start?A(n.start):n.exec?A(n.exec):void 0,stop:n.stop?A(n.stop):void 0})}var V=function(t,e){return t?(Array.isArray(t)?t:[t]).map(function(t){return A(t,e)}):[]};function _(t){return{type:x,event:t}}function J(t){var e=P(t);return{type:l.Start,activity:e,exec:e.start?e.start.exec:void 0}}function R(t,e){var n=e?"#"+e:"";return l.After+"("+t+")"+n}function T(t){return l.DoneState+"."+t}var M=".",I="",C={},F=[],B=function(t){return"#"===t[0]},H=function(){return{guards:C}},L=(function(){function t(n,r,i){void 0===r&&(r=H());var a=this;this._config=n,this.options=r,this.context=i,this.__cache={events:void 0,relativeValue:new Map,initialState:void 0},this.idMap={},this.key=n.key||n.id||"(machine)",this.type=n.type||(n.parallel?"parallel":n.states&&Object.keys(n.states).length?"compound":n.history?"history":"atomic"),this.parent=n.parent,this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=n.delimiter||(this.parent?this.parent.delimiter:M),this.id=n.id||(this.machine?[this.machine.key].concat(this.path).join(this.delimiter):this.key),this.initial=n.initial,this.order=n.order||-1,this.states=n.states?h(n.states,function(n,r,i,o){var s,u=new t(e({},n,{key:r,order:void 0===n.order?n.order:o,parent:a}));return Object.assign(a.idMap,e(((s={})[u.id]=u,s),u.idMap)),u}):C,this.history=!0===n.history?"shallow":n.history||!1,this.transient=!(!n.on||!n.on[I]),this.strict=!!n.strict,this.onEntry=S(n.onEntry),this.onExit=S(n.onExit),this.data=n.data,this.activities=S(n.activities).map(function(t){return a.resolveActivity(t)})}Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,type:this.type,initial:this.initial,history:this.history,states:h(this.states,function(t){return t.definition}),on:this.on,onEntry:this.onEntry,onExit:this.onExit,after:this.after,activities:this.activities||F,data:this.data,order:this.order||-1}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"config",{get:function(){var t=this._config;t.parent;return n(t,["parent"])},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"on",{get:function(){return this.formatTransitions()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){var t=this,n=this.config.after;if(!n)return F;if(Array.isArray(n))return n.map(function(n){return e({event:R(n.delay,t.id)},n,{actions:S(n.actions)})});var r=m(Object.keys(n).map(function(r){var i=n[r],a=+r,o=R(a,t.id);return"string"==typeof i?[{target:i,delay:a,event:o,actions:[]}]:S(i).map(function(t){return e({event:o,delay:a},t,{actions:S(t.actions)})})}));return r.sort(function(t,e){return t.delay-e.delay}),r},enumerable:!0,configurable:!0}),t.prototype.getStateNodes=function(t){var e,n=this;if(!t)return[];var r=t instanceof a?t.value:c(t,this.delimiter);if("string"==typeof r){var i=this.getStateNode(r).initial;return i?this.getStateNodes(((e={})[r]=i,e)):[this.states[r]]}var o=Object.keys(r);return o.map(function(t){return n.getStateNode(t)}).concat(o.reduce(function(t,e){var i=n.getStateNode(e).getStateNodes(r[e]);return t.concat(i)},[]))},t.prototype.handles=function(t){var e=o(t);return-1!==this.events.indexOf(e)},t.prototype.transitionLeafNode=function(t,e,n,r){var i=this.getStateNode(t),a=i.next(e,n,r);if(!a.value){var o=this.next(e,n,r),s=o.value,u=o.entryExitStates,c=o.actions,f=o.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set([i].concat(u?Array.from(u.exit):[]))},actions:c,paths:f}}return a},t.prototype.transitionNestedNode=function(t,e,n,r){var i=Object.keys(t),a=this.getStateNode(i[0]),o=a._transition(t[i[0]],e,n,r);if(!o.value){var s=this.next(e,n,r),u=s.value,c=s.entryExitStates,f=s.actions,h=s.paths;return{value:u,source:e,entryExitStates:{entry:c?c.entry:new Set,exit:new Set((o.entryExitStates?Array.from(o.entryExitStates.exit):[]).concat([a],c?Array.from(c.exit):[]))},actions:f,paths:h}}return o},t.prototype.transitionParallelNode=function(t,e,n,r){var i=this,a={};if(Object.keys(t).forEach(function(o){var s=t[o];if(s){var u=i.getStateNode(o)._transition(s,e,n,r);u.value,a[o]=u}}),!Object.keys(a).some(function(t){return void 0!==a[t].value})){var o=this.next(e,n,r),s=o.value,u=o.entryExitStates,c=o.actions,h=o.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set(Object.keys(this.states).map(function(t){return i.states[t]}).concat(u?Array.from(u.exit):[]))},actions:c,paths:h}}var p=m(Object.keys(a).map(function(t){return a[t].paths}));if(1===p.length&&!b(f(this.path),f(p[0])))return{value:this.machine.resolve(g(p)),source:e,entryExitStates:Object.keys(a).map(function(t){return a[t].entryExitStates}).reduce(function(t,e){var n=e,r=n.entry,i=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(r))),exit:new Set(Array.from(t.exit).concat(Array.from(i)))}},{entry:new Set,exit:new Set}),actions:m(Object.keys(a).map(function(t){return a[t].actions})),paths:p};var v=m(Object.keys(a).map(function(t){var n=a[t].value||e.value;return d(y(i.path)(n)[t]).map(function(e){return i.path.concat(t,e)})})),l=this.machine.resolve(g(v));return{value:l,source:e,entryExitStates:Object.keys(a).reduce(function(t,e){var n=a[e],r=n.value,i=n.entryExitStates;if(!r||!i)return t;var o=i.entry,s=i.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(o))),exit:new Set(Array.from(t.exit).concat(Array.from(s)))}},{entry:new Set,exit:new Set}),actions:m(Object.keys(a).map(function(t){return a[t].actions})),paths:d(l)}},t.prototype._transition=function(t,e,n,r){return"string"==typeof t?this.transitionLeafNode(t,e,n,r):1===Object.keys(t).length?this.transitionNestedNode(t,e,n,r):this.transitionParallelNode(t,e,n,r)},t.prototype.next=function(t,e,n){var r=this,i=e.type,a=this.on[i],o=this.transient?[{type:E}]:[];if(!a||!a.length)return{value:void 0,source:t,entryExitStates:void 0,actions:o,paths:[]};for(var s,u=[],f=0,h=a;f<h.length;f++){var p=h[f],v=p,l=v.cond,d=v.in,x=n||C,O=!d||b(c(d,this.delimiter),y(this.path.slice(0,-2))(t.value));if((!l||this.evaluateCond(l,x,e,t.value))&&O){u=S(p.target),o.push.apply(o,S(p.actions)),s=p;break}}if(s&&0===u.length)return{value:t.value,source:t,entryExitStates:void 0,actions:o,paths:[]};if(!s&&0===u.length)return{value:void 0,source:t,entryExitStates:void 0,actions:o,paths:[]};var j=m(u.map(function(e){return r.getRelativeStateNodes(e,t.historyValue)})),w=j.map(function(t){return t.path}),N=j.reduce(function(t,e){var n=r.getEntryExitStates(e,!!s.internal),i=n.entry,a=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(i))),exit:new Set(Array.from(t.exit).concat(Array.from(a)))}},{entry:new Set,exit:new Set});return{value:this.machine.resolve(g(m(u.map(function(e){return r.getRelativeStateNodes(e,t.historyValue).map(function(t){return t.path})})))),source:t,entryExitStates:N,actions:o,paths:w}},t.prototype.getStateNodeValueTree=function(t){var e,n=this;return"string"==typeof t?{stateNode:this,value:(e={},e[t]={stateNode:this.getStateNode(t),value:void 0},e)}:{stateNode:this,value:h(t,function(t,e){return n.getStateNode(e).getStateNodeValueTree(t)})}},t.prototype.getEntryExitStates=function(t,e){for(var n={entry:[],exit:[]},r=this.path,i=t.path,a=this.machine,o=0;o<Math.min(r.length,i.length);o++){var s=r[o];if(s!==i[o])break;a=a.getStateNode(s)}for(var u=a.path,c=a,f=0,h=r.slice(u.length);f<h.length;f++){var p=h[f];c=c.getStateNode(p),n.exit.unshift(c)}a===this&&(e||(n.exit.push(this),n.entry.push(this))),c=a;for(var y=0,v=i.slice(u.length);y<v.length;y++){p=v[y];c=c.getStateNode(p),n.entry.push(c)}return{entry:new Set(n.entry),exit:new Set(n.exit)}},t.prototype.evaluateCond=function(t,e,n,r){var i,a=this.machine.options.guards;if("string"==typeof t){if(!a||!a[t])throw new Error("Condition '"+t+"' is not implemented on machine '"+this.machine.id+"'.");i=a[t]}else i=t;return i(e,n,r)},Object.defineProperty(t.prototype,"delays",{get:function(){var t=this;return Array.from(new Set(this.after.map(function(t){return t.delay}))).map(function(e){return{id:t.id,delay:e}})},enumerable:!0,configurable:!0}),t.prototype.getActions=function(t){var e=this,n=new Set,r={entry:t.entryExitStates?m(Array.from(t.entryExitStates.entry).map(function(r){if("final"===r.type){var i=e.getStateNodeValueTree(t.value);n.add(T(r.id));var a=r.parent?r.parent.parent:void 0;if(a){var s=v(a.path,"value")(i);Object.keys(s.value).every(function(t){return Object.keys(s.value[t].value).every(function(e){return"final"===s.value[t].value[e].stateNode.type})})&&n.add(T(s.stateNode.id))}}return r.onEntry.concat(r.activities.map(function(t){return J(t)}),r.delays.map(function(t){var e,n,r=t.delay,i=t.id;return e=R(r,i),n={delay:r},{type:O,event:N(e),delay:n?n.delay:void 0,id:n&&void 0!==n.id?n.id:o(e)}}))})).concat(Array.from(n).map(_)):[],exit:t.entryExitStates?m(Array.from(t.entryExitStates.exit).map(function(t){return t.onExit.concat(t.activities.map(function(t){return function(t){var e=P(t);return{type:l.Stop,activity:e,exec:e.stop?e.stop.exec:void 0}}(t)}),t.delays.map(function(t){var e,n=t.delay,r=t.id;return e=R(n,r),{type:j,sendId:e}}))})):[]};return r.exit.concat(t.actions).concat(r.entry).map(function(t){return"string"==typeof t?e.resolveAction(t):t})},t.prototype.resolveAction=function(t){var e=this.machine.options.actions;return(e?e[t]:t)||t},t.prototype.resolveActivity=function(t){var n=this.machine.options.activities;return"string"==typeof t?P(n?e({type:t},n[t]):t):t},t.prototype.getActivities=function(t,n){if(!t)return C;var r=e({},n);return Array.from(t.exit).forEach(function(t){t.activities&&t.activities.forEach(function(t){r[t.type]=!1})}),Array.from(t.entry).forEach(function(t){t.activities&&t.activities.forEach(function(t){r[t.type]=!0})}),r},t.prototype.transition=function(t,e,n){var r="string"==typeof t?this.resolve(f(this.getResolvedPath(t))):t instanceof a?t:this.resolve(t),i=n||(t instanceof a?t.context:void 0),o=N(e),s=o.type;if(this.strict&&-1===this.events.indexOf(s))throw new Error("Machine '"+this.id+"' does not accept event '"+s+"'");var u=a.from(r,i),c=this._transition(u.value,u,o,i);return this.resolveTransition(c,u,o)},t.prototype.resolveTransition=function(e,n,r){var i,o=n.historyValue?n.historyValue:e.source?this.machine.historyValue(n.value):void 0,s=this.getActions(e),u=this.getActivities(e.entryExitStates,n.activities),c=s.filter(function(t){return"object"==typeof t&&(t.type===x||t.type===E)}),f=s.filter(function(t){return"object"!=typeof t||t.type!==x&&t.type!==E&&t.type!==w}),h=s.filter(function(t){return"object"==typeof t&&t.type===w}),p=n.context?h.reduce(function(t,e){var n=e.assignment,i={};return"function"==typeof n?i=n(t,r||{type:l.Init}):Object.keys(n).forEach(function(e){var a=n[e];i[e]="function"==typeof a?a(t,r):a}),Object.assign({},t,i)},n.context):n.context,y=e.value?this.getStateNodes(e.value):[];y.some(function(t){return t.transient})&&c.push({type:E});var v=[this].concat(y).reduce(function(t,e){return void 0!==e.data&&(t[e.id]=e.data),t},{}),d=e.value?new a(e.value,p,o?t.updateHistoryValue(o,e.value):void 0,e.source?n:void 0,V(f,this.options.actions),u,v,c):void 0;if(!d)return a.inert(n,p);n.history&&delete n.history.history;for(var g=d;c.length;){var m=g.actions,S=c.shift();(i=(g=this.transition(g,S.type===E?I:S.event,g.context)).actions).unshift.apply(i,m)}return g},t.prototype.ensureValidPaths=function(t){var e=this,n=new Map;t:for(var r=0,i=m(t.map(function(t){return e.getRelativeStateNodes(t)}));r<i.length;r++)for(var a=i[r],o=a;o.parent;){if(n.has(o.parent)){if("parallel"===o.parent.type)continue t;throw new Error("State node '"+a.id+"' shares parent '"+o.parent.id+"' with state node '"+n.get(o.parent).map(function(t){return t.id})+"'")}n.get(o.parent)?n.get(o.parent).push(a):n.set(o.parent,[a]),o=o.parent}},t.prototype.getStateNode=function(t){if(B(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.");var e=this.states[t];if(!e)throw new Error("Child state '"+t+"' does not exist on '"+this.id+"'");return e},t.prototype.getStateNodeById=function(t){var e=B(t)?t.slice("#".length):t;if(e===this.id)return this;var n=this.machine.idMap[e];if(!n)throw new Error("Substate '#"+e+"' does not exist on '"+this.id+"'");return n},t.prototype.getStateNodeByPath=function(t){for(var e=u(t,this.delimiter),n=this;e.length;){var r=e.shift();n=n.getStateNode(r)}return n},t.prototype.resolve=function(t){var e,n=this;if("string"==typeof t){var r=this.getStateNode(t);return r.initial?((e={})[t]=r.initialStateValue,e):t}return"parallel"===this.type?h(this.initialStateValue,function(e,r){return e?n.getStateNode(r).resolve(t[r]||e):C}):h(t,function(t,e){return t?n.getStateNode(e).resolve(t):C})},Object.defineProperty(t.prototype,"resolvedStateValue",{get:function(){var t,e,n=this.key;return"parallel"===this.type?((t={})[n]=p(this.states,function(t){return t.resolvedStateValue[t.key]},function(t){return!t.history}),t):this.initial?((e={})[n]=this.states[this.initial].resolvedStateValue,e):n},enumerable:!0,configurable:!0}),t.prototype.getResolvedPath=function(t){if(B(t)){var e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error("Unable to find state node '"+t+"'");return e.path}return u(t,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){if(this.__cache.initialState)return this.__cache.initialState;var t="parallel"===this.type?p(this.states,function(t){return t.initialStateValue||C},function(t){return!t.history}):"string"==typeof this.resolvedStateValue?void 0:this.resolvedStateValue[this.key];return this.__cache.initialState=t,this.__cache.initialState},enumerable:!0,configurable:!0}),t.prototype.getState=function(t,e){var n=this;void 0===e&&(e=this.machine.context);var r={},i=[];this.getStateNodes(t).forEach(function(t){t.onEntry&&i.push.apply(i,t.onEntry),t.activities&&t.activities.forEach(function(t){r[o(t)]=!0,i.push(J(t))})});var s=i.filter(function(t){return"object"==typeof t&&(t.type===x||t.type===E)}),u=i.filter(function(t){return"object"==typeof t&&t.type===w}),c=e?u.reduce(function(t,e){var n=e.assignment,r={};return"function"==typeof n?r=n(t,{type:"init"}):Object.keys(n).forEach(function(e){var i=n[e];r[e]="function"==typeof i?i(t,{type:"init"}):i}),Object.assign({},t,r)},e):e,f=new a(t,c,void 0,void 0,V(i,this.options.actions),r,void 0,[]);return s.reduce(function(t,e){var r,i=t.actions;return(r=(t=n.transition(t,e.type===E?I:e.event,t.context)).actions).unshift.apply(r,i),t},f)},Object.defineProperty(t.prototype,"initialState",{get:function(){var t=this.initialStateValue;if(!t)throw new Error("Cannot retrieve initial state from simple state '"+this.id+"'.");var e=this.getState(t);return this.resolveTransition({value:e.value,source:void 0,entryExitStates:{entry:new Set(this.getStateNodes(e.value)),exit:new Set},actions:[],paths:[]},e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var t;if(this.history){var e=this.config;t=e.target&&"string"==typeof e.target&&B(e.target)?f(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t},enumerable:!0,configurable:!0}),t.prototype.getStates=function(t){var e=this;if("string"==typeof t)return[this.states[t]];var n=[];return Object.keys(t).forEach(function(r){n.push.apply(n,e.states[r].getStates(t[r]))}),n},t.prototype.getRelativeStateNodes=function(t,e,n){if(void 0===n&&(n=!0),"string"==typeof t&&B(t)){var r=this.getStateNodeById(t);return n?r.history?r.resolveHistory(e):r.initialStateNodes:[r]}var i=u(t,this.delimiter),a=(this.parent||this).getFromRelativePath(i,e);return n?m(a.map(function(t){return t.initialStateNodes})):a},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var t=this;if("atomic"===this.type||"final"===this.type)return[this];var e=this.initialStateValue;return m(d(e).map(function(e){return t.getFromRelativePath(e)}))},enumerable:!0,configurable:!0}),t.prototype.getFromRelativePath=function(t,e){if(!t.length)return[this];var n=t[0],r=t.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '"+n+"' from node with no states");var i=this.getStateNode(n);if(i.history)return i.resolveHistory(e);if(!this.states[n])throw new Error("Child state '"+n+"' does not exist on '"+this.id+"'");return this.states[n].getFromRelativePath(r,e)},t.updateHistoryValue=function(t,e){return{current:e,states:function t(e,n){return h(e.states,function(e,r){if(e){var i=("string"==typeof n?void 0:n[r])||(e?e.current:void 0);if(i)return{current:i,states:t(e,i)}}})}(t,e)}},t.prototype.historyValue=function(t){if(Object.keys(this.states).length)return{current:t||this.initialStateValue,states:p(this.states,function(e,n){if(!t)return e.historyValue();var r="string"==typeof t?void 0:t[n];return e.historyValue(r||e.initialStateValue)},function(t){return!t.history})}},t.prototype.resolveHistory=function(t){var e=this;if(!this.history)return[this];var n=this.parent;if(!t)return this.target?m(d(this.target).map(function(t){return n.getFromRelativePath(t)})):this.parent.initialStateNodes;var r=v(n.path,"states")(t).current;return"string"==typeof r?[n.getStateNode(r)]:m(d(r).map(function(t){return"deep"===e.history?n.getFromRelativePath(t):[n.states[t[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var t=this,e=m(Object.keys(this.states).map(function(e){return t.states[e].stateIds}));return[this.id].concat(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){if(this.__cache.events)return this.__cache.events;var t=this.states,e=new Set(Object.keys(this.on));return t&&Object.keys(t).forEach(function(n){var r=t[n];if(r.states)for(var i=0,a=r.events;i<a.length;i++){var o=a[i];e.add(""+o)}}),this.__cache.events=Array.from(e)},enumerable:!0,configurable:!0}),t.prototype.formatTransition=function(t,n,r){var i=this,a=!!n&&n.internal;if(void 0===t||""===t)return e({},n,{actions:n?S(n.actions):[],target:void 0,internal:!n||(void 0===n.internal||n.internal),event:r});var o=S(t).map(function(t){var e="string"==typeof t&&t[0]===i.delimiter;return a=a||e,e&&!i.parent?t.slice(1):e?i.key+t:t});return e({},n,{actions:n?S(n.actions):[],target:o,internal:a,event:r})},t.prototype.formatTransitions=function(){var t=this,e=this.config.on||C,n=this.after,r=h(e,function(e,n){return void 0===e?[{target:void 0,event:n,actions:[]}]:Array.isArray(e)?e.map(function(e){return t.formatTransition(e.target,e,n)}):"string"==typeof e?[t.formatTransition([e],void 0,n)]:[t.formatTransition(e.target,e,n)]});return n.forEach(function(t){r[t.event]=r[t.event]||[],r[t.event].push(t)}),r}}(),{});function D(t,e){return m(t.definition.on[e].map(function(n){var r=n.target?[].concat(n.target):void 0;return r?r.map(function(r){try{var i=r?t.getRelativeStateNodes(r,void 0,!1)[0]:t;return{source:t,target:i,event:e,actions:n.actions?n.actions.map(s):[],cond:n.cond,transition:n}}catch(e){return void console.warn("Target '"+r+"' not found on '"+t.id+"'")}}).filter(function(t){return void 0!==t}):[{source:t,target:t,event:e,actions:n.actions?n.actions.map(s):[],cond:n.cond,transition:n}]}))}function U(t,e){var n={},r=t.events;return function i(a){var o=JSON.stringify(a);if(!n[o]){n[o]={};for(var s=0,u=r;s<u.length;s++){var c=u[s],f=t.transition(a,c,e);n[o][c]={state:f.value},i(f.value)}}}(t.initialState.value),n}function z(t){if("string"==typeof t||"number"==typeof t)return""+t;var e=t.type,r=n(t,["type"]);return e+" | "+JSON.stringify(r)}function G(t){var e=t.value,n=t.context;return JSON.stringify(e)+" | "+JSON.stringify(n)}function q(t,e){var n=e.events,r=e.filter,i={},a=m(t.events.map(function(t){return n[t]||[t]}));return function e(n){var o=G(n);if(!i[o]){i[o]={};for(var s=0,u=a;s<u.length;s++){var c=u[s],f=t.transition(n,c);r&&!r(f)||(i[o][z(c)]={value:f.value,context:f.context},e(f))}}}(t.initialState),i}function K(t,e){var n;if(!t.states)return L;var r=U(t,e),i=((n={})[JSON.stringify(t.initialState.value)]=[],n),a=new Set;return function e(n){var o=JSON.stringify(n);a.add(o);for(var s=r[o],u=0,f=Object.keys(s);u<f.length;u++){var h=f[u];if(l=s[h].state){var p=JSON.stringify(c(l,t.delimiter));(!i[p]||i[p].length>i[o].length+1)&&(i[p]=(i[o]||[]).concat([{state:n,event:h}]))}}for(var y=0,v=Object.keys(s);y<v.length;y++){var l;(l=s[v[y]].state)&&(p=JSON.stringify(l),a.has(p)||e(l))}return i}(t.initialState.value),i}function Q(t,e){if(!t.states)return L;var n=U(t,e),r=new Set,i=[],a={};var o=JSON.stringify(t.initialState.value);return Object.keys(n).forEach(function(t){!function t(e,o){if(r.add(e),e===o)a[o]=a[o]||[],a[o].push(i.slice());else for(var s=0,u=Object.keys(n[e]);s<u.length;s++){var c=u[s],f=n[e][c].state;if(f){var h=JSON.stringify(f);r.has(h)||(i.push({state:JSON.parse(e),event:c}),t(h,o))}}i.pop(),r.delete(e)}(o,t)}),a}t.getNodes=function t(e){var n=e.states;return Object.keys(n).reduce(function(e,r){var i=n[r],a=t(n[r]);return e.push.apply(e,[i].concat(a)),e},[])},t.getEventEdges=D,t.getEdges=function t(e,n){var r=(n||{}).depth,i=void 0===r?null:r,a=[];return e.states&&null===i?Object.keys(e.states).forEach(function(n){a.push.apply(a,t(e.states[n]))}):i&&i>0&&Object.keys(e.states).forEach(function(n){a.push.apply(a,t(e.states[n],{depth:i-1}))}),Object.keys(e.on).forEach(function(t){a.push.apply(a,D(e,t))}),a},t.getAdjacencyMap=U,t.deserializeStateString=function(t){var e=t.split(" | "),n=e[0],r=e[1];return{value:JSON.parse(n),context:JSON.parse(r)}},t.getValueAdjacencyMap=q,t.getShortestValuePaths=function(t,e){if(!t.states)return L;var n=q(t,e),r={},i=new Set;return function t(e){var o=G(e);i.add(o);for(var s=n[o],u=0,c=Object.keys(s);u<c.length;u++){var f=c[u],h=s[f],p=h.value,y=h.context;if(p){var v=G(S=a.from(p,y));(!r[v]||r[v].length>r[o].length+1)&&(r[v]=(r[o]||[]).concat([{state:p,event:f}]))}}for(var l=0,d=Object.keys(s);l<d.length;l++){var g=s[d[l]],m=(p=g.value,g.context);if(p){var S=a.from(p,m);v=G(a.from(p,m)),i.has(v)||t(S)}}return r}(t.initialState),r},t.getShortestPaths=K,t.getShortestPathsAsArray=function(t,e){var n=K(t,e);return Object.keys(n).map(function(t){return{state:JSON.parse(t),path:n[t]}})},t.getSimplePaths=Q,t.getSimplePathsAsArray=function(t,e){var n=Q(t,e);return Object.keys(n).map(function(t){return{state:JSON.parse(t),paths:n[t]}})},Object.defineProperty(t,"__esModule",{value:!0})}); |
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.xstateInterpreter={})}(this,function(t){"use strict";var e,n=function(){return(n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};!function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.Null="xstate.null",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.Log="xstate.log"}(e||(e={}));e.Start,e.Stop;var r=e.Raise,i=e.Send,o=e.Cancel,a=e.Null,s=e.Assign,u=(e.After,e.DoneState,e.Log),c=".",h={};function f(t,e,n){void 0===n&&(n=c);var r=b(t,n),i=b(e,n);return"string"==typeof i?"string"==typeof r&&i===r:"string"==typeof r?r in i:Object.keys(r).every(function(t){return t in i&&f(r[t],i[t])})}var p=".",l="",y={},v=[],d=function(t){return"#"===t[0]},g=function(){return{guards:y}},m=(function(){function t(e,r,i){void 0===r&&(r=g());var o=this;this._config=e,this.options=r,this.context=i,this.__cache={events:void 0,relativeValue:new Map,initialState:void 0},this.idMap={},this.key=e.key||e.id||"(machine)",this.type=e.type||(e.parallel?"parallel":e.states&&Object.keys(e.states).length?"compound":e.history?"history":"atomic"),this.parent=e.parent,this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=e.delimiter||(this.parent?this.parent.delimiter:p),this.id=e.id||(this.machine?[this.machine.key].concat(this.path).join(this.delimiter):this.key),this.initial=e.initial,this.order=e.order||-1,this.states=e.states?E(e.states,function(e,r,i,a){var s,u=new t(n({},e,{key:r,order:void 0===e.order?e.order:a,parent:o}));return Object.assign(o.idMap,n(((s={})[u.id]=u,s),u.idMap)),u}):y,this.history=!0===e.history?"shallow":e.history||!1,this.transient=!(!e.on||!e.on[l]),this.strict=!!e.strict,this.onEntry=V(e.onEntry),this.onExit=V(e.onExit),this.data=e.data,this.activities=V(e.activities).map(function(t){return o.resolveActivity(t)})}Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,type:this.type,initial:this.initial,history:this.history,states:E(this.states,function(t){return t.definition}),on:this.on,onEntry:this.onEntry,onExit:this.onExit,after:this.after,activities:this.activities||v,data:this.data,order:this.order||-1}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"config",{get:function(){var t=this._config;t.parent;return function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&(n[r[i]]=t[r[i]])}return n}(t,["parent"])},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"on",{get:function(){return this.formatTransitions()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){var t=this,e=this.config.after;if(!e)return v;if(Array.isArray(e))return e.map(function(e){return n({event:B(e.delay,t.id)},e,{actions:V(e.actions)})});var r=P(Object.keys(e).map(function(r){var i=e[r],o=+r,a=B(o,t.id);return"string"==typeof i?[{target:i,delay:o,event:a,actions:[]}]:V(i).map(function(t){return n({event:a,delay:o},t,{actions:V(t.actions)})})}));return r.sort(function(t,e){return t.delay-e.delay}),r},enumerable:!0,configurable:!0}),t.prototype.getStateNodes=function(t){var e,n=this;if(!t)return[];var r=t instanceof m?t.value:b(t,this.delimiter);if("string"==typeof r){var i=this.getStateNode(r).initial;return i?this.getStateNodes(((e={})[r]=i,e)):[this.states[r]]}var o=Object.keys(r);return o.map(function(t){return n.getStateNode(t)}).concat(o.reduce(function(t,e){var i=n.getStateNode(e).getStateNodes(r[e]);return t.concat(i)},[]))},t.prototype.handles=function(t){var e=S(t);return-1!==this.events.indexOf(e)},t.prototype.transitionLeafNode=function(t,e,n,r){var i=this.getStateNode(t),o=i.next(e,n,r);if(!o.value){var a=this.next(e,n,r),s=a.value,u=a.entryExitStates,c=a.actions,h=a.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set([i].concat(u?Array.from(u.exit):[]))},actions:c,paths:h}}return o},t.prototype.transitionNestedNode=function(t,e,n,r){var i=Object.keys(t),o=this.getStateNode(i[0]),a=o._transition(t[i[0]],e,n,r);if(!a.value){var s=this.next(e,n,r),u=s.value,c=s.entryExitStates,h=s.actions,f=s.paths;return{value:u,source:e,entryExitStates:{entry:c?c.entry:new Set,exit:new Set((a.entryExitStates?Array.from(a.entryExitStates.exit):[]).concat([o],c?Array.from(c.exit):[]))},actions:h,paths:f}}return a},t.prototype.transitionParallelNode=function(t,e,n,r){var i=this,o={};if(Object.keys(t).forEach(function(a){var s=t[a];if(s){var u=i.getStateNode(a)._transition(s,e,n,r);u.value,o[a]=u}}),!Object.keys(o).some(function(t){return void 0!==o[t].value})){var a=this.next(e,n,r),s=a.value,u=a.entryExitStates,c=a.actions,h=a.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set(Object.keys(this.states).map(function(t){return i.states[t]}).concat(u?Array.from(u.exit):[]))},actions:c,paths:h}}var p=P(Object.keys(o).map(function(t){return o[t].paths}));if(1===p.length&&!f(w(this.path),w(p[0])))return{value:this.machine.resolve(A(p)),source:e,entryExitStates:Object.keys(o).map(function(t){return o[t].entryExitStates}).reduce(function(t,e){var n=e,r=n.entry,i=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(r))),exit:new Set(Array.from(t.exit).concat(Array.from(i)))}},{entry:new Set,exit:new Set}),actions:P(Object.keys(o).map(function(t){return o[t].actions})),paths:p};var l=P(Object.keys(o).map(function(t){var n=o[t].value||e.value;return k(j(i.path)(n)[t]).map(function(e){return i.path.concat(t,e)})})),y=this.machine.resolve(A(l));return{value:y,source:e,entryExitStates:Object.keys(o).reduce(function(t,e){var n=o[e],r=n.value,i=n.entryExitStates;if(!r||!i)return t;var a=i.entry,s=i.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(a))),exit:new Set(Array.from(t.exit).concat(Array.from(s)))}},{entry:new Set,exit:new Set}),actions:P(Object.keys(o).map(function(t){return o[t].actions})),paths:k(y)}},t.prototype._transition=function(t,e,n,r){return"string"==typeof t?this.transitionLeafNode(t,e,n,r):1===Object.keys(t).length?this.transitionNestedNode(t,e,n,r):this.transitionParallelNode(t,e,n,r)},t.prototype.next=function(t,e,n){var r=this,i=e.type,o=this.on[i],s=this.transient?[{type:a}]:[];if(!o||!o.length)return{value:void 0,source:t,entryExitStates:void 0,actions:s,paths:[]};for(var u,c=[],h=0,p=o;h<p.length;h++){var l=p[h],v=l,d=v.cond,g=v.in,m=n||y,S=!g||f(b(g,this.delimiter),j(this.path.slice(0,-2))(t.value));if((!d||this.evaluateCond(d,m,e,t.value))&&S){c=V(l.target),s.push.apply(s,V(l.actions)),u=l;break}}if(u&&0===c.length)return{value:t.value,source:t,entryExitStates:void 0,actions:s,paths:[]};if(!u&&0===c.length)return{value:void 0,source:t,entryExitStates:void 0,actions:s,paths:[]};var x=P(c.map(function(e){return r.getRelativeStateNodes(e,t.historyValue)})),w=x.map(function(t){return t.path}),E=x.reduce(function(t,e){var n=r.getEntryExitStates(e,!!u.internal),i=n.entry,o=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(i))),exit:new Set(Array.from(t.exit).concat(Array.from(o)))}},{entry:new Set,exit:new Set});return{value:this.machine.resolve(A(P(c.map(function(e){return r.getRelativeStateNodes(e,t.historyValue).map(function(t){return t.path})})))),source:t,entryExitStates:E,actions:s,paths:w}},t.prototype.getStateNodeValueTree=function(t){var e,n=this;return"string"==typeof t?{stateNode:this,value:(e={},e[t]={stateNode:this.getStateNode(t),value:void 0},e)}:{stateNode:this,value:E(t,function(t,e){return n.getStateNode(e).getStateNodeValueTree(t)})}},t.prototype.getEntryExitStates=function(t,e){for(var n={entry:[],exit:[]},r=this.path,i=t.path,o=this.machine,a=0;a<Math.min(r.length,i.length);a++){var s=r[a];if(s!==i[a])break;o=o.getStateNode(s)}for(var u=o.path,c=o,h=0,f=r.slice(u.length);h<f.length;h++){var p=f[h];c=c.getStateNode(p),n.exit.unshift(c)}o===this&&(e||(n.exit.push(this),n.entry.push(this))),c=o;for(var l=0,y=i.slice(u.length);l<y.length;l++){p=y[l];c=c.getStateNode(p),n.entry.push(c)}return{entry:new Set(n.entry),exit:new Set(n.exit)}},t.prototype.evaluateCond=function(t,e,n,r){var i,o=this.machine.options.guards;if("string"==typeof t){if(!o||!o[t])throw new Error("Condition '"+t+"' is not implemented on machine '"+this.machine.id+"'.");i=o[t]}else i=t;return i(e,n,r)},Object.defineProperty(t.prototype,"delays",{get:function(){var t=this;return Array.from(new Set(this.after.map(function(t){return t.delay}))).map(function(e){return{id:t.id,delay:e}})},enumerable:!0,configurable:!0}),t.prototype.getActions=function(t){var n=this,r=new Set,i={entry:t.entryExitStates?P(Array.from(t.entryExitStates.entry).map(function(e){if("final"===e.type){var i=n.getStateNodeValueTree(t.value);r.add(H(e.id));var o=e.parent?e.parent.parent:void 0;if(o){var a=N(o.path,"value")(i);Object.keys(a.value).every(function(t){return Object.keys(a.value[t].value).every(function(e){return"final"===a.value[t].value[e].stateNode.type})})&&r.add(H(a.stateNode.id))}}return e.onEntry.concat(e.activities.map(function(t){return Q(t)}),e.delays.map(function(t){var e=t.delay,n=t.id;return L(B(e,n),{delay:e})}))})).concat(Array.from(r).map(C)):[],exit:t.entryExitStates?P(Array.from(t.entryExitStates.exit).map(function(t){return t.onExit.concat(t.activities.map(function(t){return function(t){var n=R(t);return{type:e.Stop,activity:n,exec:n.stop?n.stop.exec:void 0}}(t)}),t.delays.map(function(t){var e=t.delay,n=t.id;return F(B(e,n))}))})):[]};return i.exit.concat(t.actions).concat(i.entry).map(function(t){return"string"==typeof t?n.resolveAction(t):t})},t.prototype.resolveAction=function(t){var e=this.machine.options.actions;return(e?e[t]:t)||t},t.prototype.resolveActivity=function(t){var e=this.machine.options.activities;return"string"==typeof t?R(e?n({type:t},e[t]):t):t},t.prototype.getActivities=function(t,e){if(!t)return y;var r=n({},e);return Array.from(t.exit).forEach(function(t){t.activities&&t.activities.forEach(function(t){r[t.type]=!1})}),Array.from(t.entry).forEach(function(t){t.activities&&t.activities.forEach(function(t){r[t.type]=!0})}),r},t.prototype.transition=function(t,e,n){var r="string"==typeof t?this.resolve(w(this.getResolvedPath(t))):t instanceof m?t:this.resolve(t),i=n||(t instanceof m?t.context:void 0),o=_(e),a=o.type;if(this.strict&&-1===this.events.indexOf(a))throw new Error("Machine '"+this.id+"' does not accept event '"+a+"'");var s=m.from(r,i),u=this._transition(s.value,s,o,i);return this.resolveTransition(u,s,o)},t.prototype.resolveTransition=function(e,n,i){var o,u=n.historyValue?n.historyValue:e.source?this.machine.historyValue(n.value):void 0;try{this.ensureValidPaths(e.paths)}catch(t){throw new Error("Event '"+(i?i.type:"none")+"' leads to an invalid configuration: "+t.message)}var c=this.getActions(e),h=this.getActivities(e.entryExitStates,n.activities),f=c.filter(function(t){return"object"==typeof t&&(t.type===r||t.type===a)}),p=c.filter(function(t){return"object"!=typeof t||t.type!==r&&t.type!==a&&t.type!==s}),y=c.filter(function(t){return"object"==typeof t&&t.type===s}),v=n.context?y.reduce(function(t,e){var n=e.assignment,r={};return"function"==typeof n?r=n(t,i||{type:"xstate.init"}):Object.keys(n).forEach(function(e){var o=n[e];r[e]="function"==typeof o?o(t,i):o}),Object.assign({},t,r)},n.context):n.context,d=e.value?this.getStateNodes(e.value):[];d.some(function(t){return t.transient})&&f.push({type:a});var g=[this].concat(d).reduce(function(t,e){return void 0!==e.data&&(t[e.id]=e.data),t},{}),S=e.value?new m(e.value,v,u?t.updateHistoryValue(u,e.value):void 0,e.source?n:void 0,I(p,this.options.actions),h,g,f):void 0;if(!S)return m.inert(n,v);delete n.history;for(var x=S;f.length;){var b=x.actions,w=f.shift();(o=(x=this.transition(x,w.type===a?l:w.event,x.context)).actions).unshift.apply(o,b)}return x},t.prototype.ensureValidPaths=function(t){var e=this,n=new Map;t:for(var r=0,i=P(t.map(function(t){return e.getRelativeStateNodes(t)}));r<i.length;r++)for(var o=i[r],a=o;a.parent;){if(n.has(a.parent)){if("parallel"===a.parent.type)continue t;throw new Error("State node '"+o.id+"' shares parent '"+a.parent.id+"' with state node '"+n.get(a.parent).map(function(t){return t.id})+"'")}n.get(a.parent)?n.get(a.parent).push(o):n.set(a.parent,[o]),a=a.parent}},t.prototype.getStateNode=function(t){if(d(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.");var e=this.states[t];if(!e)throw new Error("Child state '"+t+"' does not exist on '"+this.id+"'");return e},t.prototype.getStateNodeById=function(t){var e=d(t)?t.slice("#".length):t;if(e===this.id)return this;var n=this.machine.idMap[e];if(!n)throw new Error("Substate '#"+e+"' does not exist on '"+this.id+"'");return n},t.prototype.getStateNodeByPath=function(t){for(var e=x(t,this.delimiter),n=this;e.length;){var r=e.shift();n=n.getStateNode(r)}return n},t.prototype.resolve=function(t){var e,n=this;if("string"==typeof t){var r=this.getStateNode(t);return r.initial?((e={})[t]=r.initialStateValue,e):t}return"parallel"===this.type?E(this.initialStateValue,function(e,r){return e?n.getStateNode(r).resolve(t[r]||e):y}):E(t,function(t,e){return t?n.getStateNode(e).resolve(t):y})},Object.defineProperty(t.prototype,"resolvedStateValue",{get:function(){var t,e,n=this.key;return"parallel"===this.type?((t={})[n]=O(this.states,function(t){return t.resolvedStateValue[t.key]},function(t){return!t.history}),t):this.initial?((e={})[n]=this.states[this.initial].resolvedStateValue,e):n},enumerable:!0,configurable:!0}),t.prototype.getResolvedPath=function(t){if(d(t)){var e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error("Unable to find state node '"+t+"'");return e.path}return x(t,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){if(this.__cache.initialState)return this.__cache.initialState;var t="parallel"===this.type?O(this.states,function(t){return t.initialStateValue||y},function(t){return!t.history}):"string"==typeof this.resolvedStateValue?void 0:this.resolvedStateValue[this.key];return this.__cache.initialState=t,this.__cache.initialState},enumerable:!0,configurable:!0}),t.prototype.getState=function(t,e){var n=this;void 0===e&&(e=this.machine.context);var i={},o=[];this.getStateNodes(t).forEach(function(t){t.onEntry&&o.push.apply(o,t.onEntry),t.activities&&t.activities.forEach(function(t){i[S(t)]=!0,o.push(Q(t))})});var u=o.filter(function(t){return"object"==typeof t&&(t.type===r||t.type===a)}),c=o.filter(function(t){return"object"==typeof t&&t.type===s}),h=e?c.reduce(function(t,e){var n=e.assignment,r={};return"function"==typeof n?r=n(t,{type:"init"}):Object.keys(n).forEach(function(e){var i=n[e];r[e]="function"==typeof i?i(t,{type:"init"}):i}),Object.assign({},t,r)},e):e,f=new m(t,h,void 0,void 0,I(o,this.options.actions),i,void 0,[]);return u.reduce(function(t,e){var r,i=t.actions;return(r=(t=n.transition(t,e.type===a?l:e.event,t.context)).actions).unshift.apply(r,i),t},f)},Object.defineProperty(t.prototype,"initialState",{get:function(){var t=this.initialStateValue;if(!t)throw new Error("Cannot retrieve initial state from simple state '"+this.id+"'.");var e=this.getState(t);return this.resolveTransition({value:e.value,source:void 0,entryExitStates:{entry:new Set(this.getStateNodes(e.value)),exit:new Set},actions:[],paths:[]},e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var t;if(this.history){var e=this.config;t=e.target&&"string"==typeof e.target&&d(e.target)?w(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t},enumerable:!0,configurable:!0}),t.prototype.getStates=function(t){var e=this;if("string"==typeof t)return[this.states[t]];var n=[];return Object.keys(t).forEach(function(r){n.push.apply(n,e.states[r].getStates(t[r]))}),n},t.prototype.getRelativeStateNodes=function(t,e,n){if(void 0===n&&(n=!0),"string"==typeof t&&d(t)){var r=this.getStateNodeById(t);return n?r.history?r.resolveHistory(e):r.initialStateNodes:[r]}var i=x(t,this.delimiter),o=(this.parent||this).getFromRelativePath(i,e);return n?P(o.map(function(t){return t.initialStateNodes})):o},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var t=this;if("atomic"===this.type||"final"===this.type)return[this];var e=this.initialStateValue;return P(k(e).map(function(e){return t.getFromRelativePath(e)}))},enumerable:!0,configurable:!0}),t.prototype.getFromRelativePath=function(t,e){if(!t.length)return[this];var n=t[0],r=t.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '"+n+"' from node with no states");var i=this.getStateNode(n);if(i.history)return i.resolveHistory(e);if(!this.states[n])throw new Error("Child state '"+n+"' does not exist on '"+this.id+"'");return this.states[n].getFromRelativePath(r,e)},t.updateHistoryValue=function(t,e){return{current:e,states:function t(e,n){return E(e.states,function(e,r){if(e){var i=("string"==typeof n?void 0:n[r])||(e?e.current:void 0);if(i)return{current:i,states:t(e,i)}}})}(t,e)}},t.prototype.historyValue=function(t){if(Object.keys(this.states).length)return{current:t||this.initialStateValue,states:O(this.states,function(e,n){if(!t)return e.historyValue();var r="string"==typeof t?void 0:t[n];return e.historyValue(r||e.initialStateValue)},function(t){return!t.history})}},t.prototype.resolveHistory=function(t){var e=this;if(!this.history)return[this];var n=this.parent;if(!t)return this.target?P(k(this.target).map(function(t){return n.getFromRelativePath(t)})):this.parent.initialStateNodes;var r=N(n.path,"states")(t).current;return"string"==typeof r?[n.getStateNode(r)]:P(k(r).map(function(t){return"deep"===e.history?n.getFromRelativePath(t):[n.states[t[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var t=this,e=P(Object.keys(this.states).map(function(e){return t.states[e].stateIds}));return[this.id].concat(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){if(this.__cache.events)return this.__cache.events;var t=this.states,e=new Set(Object.keys(this.on));return t&&Object.keys(t).forEach(function(n){var r=t[n];if(r.states)for(var i=0,o=r.events;i<o.length;i++){var a=o[i];e.add(""+a)}}),this.__cache.events=Array.from(e)},enumerable:!0,configurable:!0}),t.prototype.formatTransition=function(t,e,r){var i=this,o=!!e&&e.internal;if(void 0===t||""===t)return n({},e,{actions:e?V(e.actions):[],target:void 0,internal:!e||(void 0===e.internal||e.internal),event:r});var a=V(t).map(function(t){var e="string"==typeof t&&t[0]===i.delimiter;return o=o||e,e&&!i.parent?t.slice(1):e?i.key+t:t});return n({},e,{actions:e?V(e.actions):[],target:a,internal:o,event:r})},t.prototype.formatTransitions=function(){var t=this,e=this.config.on||y,n=this.after,r=E(e,function(e,n){return void 0===e?[{target:void 0,event:n,actions:[]}]:Array.isArray(e)?e.map(function(e){return t.formatTransition(e.target,e,n)}):"string"==typeof e?[t.formatTransition([e],void 0,n)]:[t.formatTransition(e.target,e,n)]});return n.forEach(function(t){r[t.event]=r[t.event]||[],r[t.event].push(t)}),r}}(),function(){function t(t,e,n,r,i,o,a,s){void 0===i&&(i=[]),void 0===o&&(o=h),void 0===a&&(a={}),void 0===s&&(s=[]),this.value=t,this.context=e,this.historyValue=n,this.history=r,this.actions=i,this.activities=o,this.data=a,this.events=s}return t.from=function(e,n){return e instanceof t?e.context!==n?new t(e.value,n,e.historyValue,e.history,[],e.activities,{},[]):e:new t(e,n,void 0,void 0,[],void 0,void 0,[])},t.inert=function(e,n){return e instanceof t?e.actions.length?new t(e.value,n,e.historyValue,e.history,[],e.activities,void 0,[]):e:t.from(e,n)},t.prototype.toStrings=function(t){var e=this;if(void 0===t&&(t=this.value),"string"==typeof t)return[t];var n=Object.keys(t);return n.concat.apply(n,n.map(function(n){return e.toStrings(t[n]).map(function(t){return n+"."+t})}))},t.prototype.matches=function(t){return f(t,this.value)},Object.defineProperty(t.prototype,"changed",{get:function(){return!!this.history&&(!!this.actions.length||typeof this.history.value!==this.value||("string"==typeof this.value?this.value!==this.history.value:function t(e,n){if(e===n)return!0;var r=Object.keys(e);var i=Object.keys(n);return r.length===i.length&&r.every(function(r){return t(e[r],n[r])})}(this.value,this.history.value)))},enumerable:!0,configurable:!0}),t}());function S(t){try{return"string"==typeof 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 x(t,e){try{return Array.isArray(t)?t:t.toString().split(e)}catch(e){throw new Error("'"+t+"' is not a valid state path.")}}function b(t,e){return t instanceof m?t.value:"object"!=typeof t||t instanceof m?w(x(t,e)):t}function w(t){if(1===t.length)return t[0];for(var e={},n=e,r=0;r<t.length-1;r++)r===t.length-2?n[t[r]]=t[r+1]:(n[t[r]]={},n=n[t[r]]);return e}function E(t,e){var n={};return Object.keys(t).forEach(function(r,i){n[r]=e(t[r],r,t,i)}),n}function O(t,e,n){var r={};return Object.keys(t).forEach(function(i){var o=t[i];n(o)&&(r[i]=e(o,i,t))}),r}var j=function(t){return function(e){for(var n=e,r=0,i=t;r<i.length;r++){n=n[i[r]]}return n}};function N(t,e){return function(n){for(var r=n,i=0,o=t;i<o.length;i++){var a=o[i];r=r[e][a]}return r}}var k=function(t){return"string"==typeof t?[[t]]:P(Object.keys(t).map(function(e){return k(t[e]).map(function(t){return[e].concat(t)})}))},A=function(t){var e={};if(t&&1===t.length&&1===t[0].length)return t[0][0];for(var n=0,r=t;n<r.length;n++)for(var i=r[n],o=e,a=0;a<i.length;a++){var s=i[a];if(a===i.length-2){o[s]=i[a+1];break}o[s]=o[s]||{},o=o[s]}return e};function P(t){var e;return(e=[]).concat.apply(e,t)}function V(t){return Array.isArray(t)?t:void 0===t?[]:[t]}var _=function(t,e){if("string"==typeof t||"number"==typeof t){var n={type:t};return void 0!==e&&(n.id=e),n}return t};function T(t,e){if(e){var n=e[t];if(n)return"function"==typeof n?n:n.exec}}var M=function(t,e){var r;if("string"==typeof t||"number"==typeof t)r={type:t,exec:T(t,e)};else{if("function"!=typeof t){var i=T(t.type,e);return i?n({},t,{exec:i}):t}r={type:t.name,exec:t}}return Object.defineProperty(r,"toString",{value:function(){return r.type},enumerable:!1}),r};function R(t){var e=M(t);return n({},e,{type:e.type,start:e.start?M(e.start):e.exec?M(e.exec):void 0,stop:e.stop?M(e.stop):void 0})}var I=function(t,e){return t?(Array.isArray(t)?t:[t]).map(function(t){return M(t,e)}):[]},C=function(t){return{type:r,event:t}},L=function(t,e){return{type:i,event:_(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:S(t)}},F=function(t){return{type:o,sendId:t}};function Q(t){var n=R(t);return{type:e.Start,activity:n,exec:n.start?n.start.exec:void 0}}function B(t,n){var r=n?"#"+n:"";return e.After+"("+t+")"+r}function H(t){return e.DoneState+"."+t}var z=function(){function t(){this.timeouts=new Map,this._now=0,this._id=0}return t.prototype.now=function(){return this._now},t.prototype.getId=function(){return this._id++},t.prototype.setTimeout=function(t,e){var n=this.getId();return this.timeouts.set(n,{start:this.now(),timeout:e,fn:t}),n},t.prototype.clearTimeout=function(t){this.timeouts.delete(t)},t.prototype.set=function(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()},t.prototype.flushTimeouts=function(){var t=this;this.timeouts.forEach(function(e,n){t.now()-e.start>=e.timeout&&(e.fn.call(null),t.timeouts.delete(n))})},t.prototype.increment=function(t){this._now+=t,this.flushTimeouts()},t}(),U=function(){function t(e,r,i){void 0===i&&(i=t.defaultOptions);var o=this;this.machine=e,this.eventQueue=[],this.delayedEventsMap={},this.listeners=new Set,this.stopListeners=new Set,this.initialized=!1,this.init=this.start,this.send=function(t){var e=_(t);if(!o.initialized)throw new Error('Unable to send event "'+e.type+'" to an uninitialized interpreter.');var n=o.machine.transition(o.state,e,o.extState);return o.update(n,t),o.flushEventQueue(),n},r&&this.onTransition(r);var a=n({},t.defaultOptions,i);this.clock=a.clock,this.logger=a.logger}return t.prototype.update=function(t,e){var n=this;this.state=t;var r=this.state.context;this.state.actions.forEach(function(t){n.exec(t,r,e?_(e):void 0)},r),this.listeners.forEach(function(e){return e(t)})},t.prototype.onTransition=function(t){return this.listeners.add(t),this},t.prototype.onStop=function(t){return this.stopListeners.add(t),this},t.prototype.off=function(t){return this.listeners.delete(t),this},t.prototype.start=function(t){return void 0===t&&(t=this.machine.initialState),this.update(t),this.initialized=!0,this},t.prototype.stop=function(){var t=this;return this.listeners.forEach(function(e){return t.off(e)}),this.stopListeners.forEach(function(e){e(),t.stopListeners.delete(e)}),this},t.prototype.defer=function(t){var e=this;return this.clock.setTimeout(function(){return e.send(t.event)},t.delay||0)},t.prototype.cancel=function(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]},t.prototype.exec=function(t,e,n){if(t.exec)return t.exec(e,n);switch(t.type){case i:var r=t;r.delay?this.delayedEventsMap[r.id]=this.defer(r):this.eventQueue.push(r.event);break;case o:this.cancel(t.sendId);break;case u:var a=t.expr?t.expr(e,n):void 0;t.label?this.logger(t.label,a):this.logger(a);break;default:console.warn("No implementation found for action type '"+t.type+"'")}},t.prototype.flushEventQueue=function(){this.eventQueue.length&&this.send(this.eventQueue.unshift())},t.defaultOptions={clock:{setTimeout:setTimeout,clearTimeout:clearTimeout},logger:global.console.log.bind(console)},t.interpret=D,t}();function D(t,e,n){return new U(t,e,n)}t.SimulatedClock=z,t.Interpreter=U,t.interpret=D,Object.defineProperty(t,"__esModule",{value:!0})}); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.xstateInterpreter={})}(this,function(t){"use strict";var e,n=function(){return(n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};!function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.Null="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.Log="xstate.log",t.Init="xstate.init"}(e||(e={}));e.Start,e.Stop;var r=e.Raise,i=e.Send,o=e.Cancel,a=e.Null,s=e.Assign,u=(e.After,e.DoneState,e.Log),c=(e.Init,"."),h={};function f(t,e,n){void 0===n&&(n=c);var r=b(t,n),i=b(e,n);return"string"==typeof i?"string"==typeof r&&i===r:"string"==typeof r?r in i:Object.keys(r).every(function(t){return t in i&&f(r[t],i[t])})}var p=".",y="",l={},v=[],d=function(t){return"#"===t[0]},g=function(){return{guards:l}},m=(function(){function t(e,r,i){void 0===r&&(r=g());var o=this;this._config=e,this.options=r,this.context=i,this.__cache={events:void 0,relativeValue:new Map,initialState:void 0},this.idMap={},this.key=e.key||e.id||"(machine)",this.type=e.type||(e.parallel?"parallel":e.states&&Object.keys(e.states).length?"compound":e.history?"history":"atomic"),this.parent=e.parent,this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=e.delimiter||(this.parent?this.parent.delimiter:p),this.id=e.id||(this.machine?[this.machine.key].concat(this.path).join(this.delimiter):this.key),this.initial=e.initial,this.order=e.order||-1,this.states=e.states?E(e.states,function(e,r,i,a){var s,u=new t(n({},e,{key:r,order:void 0===e.order?e.order:a,parent:o}));return Object.assign(o.idMap,n(((s={})[u.id]=u,s),u.idMap)),u}):l,this.history=!0===e.history?"shallow":e.history||!1,this.transient=!(!e.on||!e.on[y]),this.strict=!!e.strict,this.onEntry=V(e.onEntry),this.onExit=V(e.onExit),this.data=e.data,this.activities=V(e.activities).map(function(t){return o.resolveActivity(t)})}Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,type:this.type,initial:this.initial,history:this.history,states:E(this.states,function(t){return t.definition}),on:this.on,onEntry:this.onEntry,onExit:this.onExit,after:this.after,activities:this.activities||v,data:this.data,order:this.order||-1}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"config",{get:function(){var t=this._config;t.parent;return function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&(n[r[i]]=t[r[i]])}return n}(t,["parent"])},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"on",{get:function(){return this.formatTransitions()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){var t=this,e=this.config.after;if(!e)return v;if(Array.isArray(e))return e.map(function(e){return n({event:B(e.delay,t.id)},e,{actions:V(e.actions)})});var r=P(Object.keys(e).map(function(r){var i=e[r],o=+r,a=B(o,t.id);return"string"==typeof i?[{target:i,delay:o,event:a,actions:[]}]:V(i).map(function(t){return n({event:a,delay:o},t,{actions:V(t.actions)})})}));return r.sort(function(t,e){return t.delay-e.delay}),r},enumerable:!0,configurable:!0}),t.prototype.getStateNodes=function(t){var e,n=this;if(!t)return[];var r=t instanceof m?t.value:b(t,this.delimiter);if("string"==typeof r){var i=this.getStateNode(r).initial;return i?this.getStateNodes(((e={})[r]=i,e)):[this.states[r]]}var o=Object.keys(r);return o.map(function(t){return n.getStateNode(t)}).concat(o.reduce(function(t,e){var i=n.getStateNode(e).getStateNodes(r[e]);return t.concat(i)},[]))},t.prototype.handles=function(t){var e=S(t);return-1!==this.events.indexOf(e)},t.prototype.transitionLeafNode=function(t,e,n,r){var i=this.getStateNode(t),o=i.next(e,n,r);if(!o.value){var a=this.next(e,n,r),s=a.value,u=a.entryExitStates,c=a.actions,h=a.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set([i].concat(u?Array.from(u.exit):[]))},actions:c,paths:h}}return o},t.prototype.transitionNestedNode=function(t,e,n,r){var i=Object.keys(t),o=this.getStateNode(i[0]),a=o._transition(t[i[0]],e,n,r);if(!a.value){var s=this.next(e,n,r),u=s.value,c=s.entryExitStates,h=s.actions,f=s.paths;return{value:u,source:e,entryExitStates:{entry:c?c.entry:new Set,exit:new Set((a.entryExitStates?Array.from(a.entryExitStates.exit):[]).concat([o],c?Array.from(c.exit):[]))},actions:h,paths:f}}return a},t.prototype.transitionParallelNode=function(t,e,n,r){var i=this,o={};if(Object.keys(t).forEach(function(a){var s=t[a];if(s){var u=i.getStateNode(a)._transition(s,e,n,r);u.value,o[a]=u}}),!Object.keys(o).some(function(t){return void 0!==o[t].value})){var a=this.next(e,n,r),s=a.value,u=a.entryExitStates,c=a.actions,h=a.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set(Object.keys(this.states).map(function(t){return i.states[t]}).concat(u?Array.from(u.exit):[]))},actions:c,paths:h}}var p=P(Object.keys(o).map(function(t){return o[t].paths}));if(1===p.length&&!f(w(this.path),w(p[0])))return{value:this.machine.resolve(A(p)),source:e,entryExitStates:Object.keys(o).map(function(t){return o[t].entryExitStates}).reduce(function(t,e){var n=e,r=n.entry,i=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(r))),exit:new Set(Array.from(t.exit).concat(Array.from(i)))}},{entry:new Set,exit:new Set}),actions:P(Object.keys(o).map(function(t){return o[t].actions})),paths:p};var y=P(Object.keys(o).map(function(t){var n=o[t].value||e.value;return k(j(i.path)(n)[t]).map(function(e){return i.path.concat(t,e)})})),l=this.machine.resolve(A(y));return{value:l,source:e,entryExitStates:Object.keys(o).reduce(function(t,e){var n=o[e],r=n.value,i=n.entryExitStates;if(!r||!i)return t;var a=i.entry,s=i.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(a))),exit:new Set(Array.from(t.exit).concat(Array.from(s)))}},{entry:new Set,exit:new Set}),actions:P(Object.keys(o).map(function(t){return o[t].actions})),paths:k(l)}},t.prototype._transition=function(t,e,n,r){return"string"==typeof t?this.transitionLeafNode(t,e,n,r):1===Object.keys(t).length?this.transitionNestedNode(t,e,n,r):this.transitionParallelNode(t,e,n,r)},t.prototype.next=function(t,e,n){var r=this,i=e.type,o=this.on[i],s=this.transient?[{type:a}]:[];if(!o||!o.length)return{value:void 0,source:t,entryExitStates:void 0,actions:s,paths:[]};for(var u,c=[],h=0,p=o;h<p.length;h++){var y=p[h],v=y,d=v.cond,g=v.in,m=n||l,S=!g||f(b(g,this.delimiter),j(this.path.slice(0,-2))(t.value));if((!d||this.evaluateCond(d,m,e,t.value))&&S){c=V(y.target),s.push.apply(s,V(y.actions)),u=y;break}}if(u&&0===c.length)return{value:t.value,source:t,entryExitStates:void 0,actions:s,paths:[]};if(!u&&0===c.length)return{value:void 0,source:t,entryExitStates:void 0,actions:s,paths:[]};var x=P(c.map(function(e){return r.getRelativeStateNodes(e,t.historyValue)})),w=x.map(function(t){return t.path}),E=x.reduce(function(t,e){var n=r.getEntryExitStates(e,!!u.internal),i=n.entry,o=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(i))),exit:new Set(Array.from(t.exit).concat(Array.from(o)))}},{entry:new Set,exit:new Set});return{value:this.machine.resolve(A(P(c.map(function(e){return r.getRelativeStateNodes(e,t.historyValue).map(function(t){return t.path})})))),source:t,entryExitStates:E,actions:s,paths:w}},t.prototype.getStateNodeValueTree=function(t){var e,n=this;return"string"==typeof t?{stateNode:this,value:(e={},e[t]={stateNode:this.getStateNode(t),value:void 0},e)}:{stateNode:this,value:E(t,function(t,e){return n.getStateNode(e).getStateNodeValueTree(t)})}},t.prototype.getEntryExitStates=function(t,e){for(var n={entry:[],exit:[]},r=this.path,i=t.path,o=this.machine,a=0;a<Math.min(r.length,i.length);a++){var s=r[a];if(s!==i[a])break;o=o.getStateNode(s)}for(var u=o.path,c=o,h=0,f=r.slice(u.length);h<f.length;h++){var p=f[h];c=c.getStateNode(p),n.exit.unshift(c)}o===this&&(e||(n.exit.push(this),n.entry.push(this))),c=o;for(var y=0,l=i.slice(u.length);y<l.length;y++){p=l[y];c=c.getStateNode(p),n.entry.push(c)}return{entry:new Set(n.entry),exit:new Set(n.exit)}},t.prototype.evaluateCond=function(t,e,n,r){var i,o=this.machine.options.guards;if("string"==typeof t){if(!o||!o[t])throw new Error("Condition '"+t+"' is not implemented on machine '"+this.machine.id+"'.");i=o[t]}else i=t;return i(e,n,r)},Object.defineProperty(t.prototype,"delays",{get:function(){var t=this;return Array.from(new Set(this.after.map(function(t){return t.delay}))).map(function(e){return{id:t.id,delay:e}})},enumerable:!0,configurable:!0}),t.prototype.getActions=function(t){var n=this,r=new Set,o={entry:t.entryExitStates?P(Array.from(t.entryExitStates.entry).map(function(e){if("final"===e.type){var o=n.getStateNodeValueTree(t.value);r.add(H(e.id));var a=e.parent?e.parent.parent:void 0;if(a){var s=N(a.path,"value")(o);Object.keys(s.value).every(function(t){return Object.keys(s.value[t].value).every(function(e){return"final"===s.value[t].value[e].stateNode.type})})&&r.add(H(s.stateNode.id))}}return e.onEntry.concat(e.activities.map(function(t){return F(t)}),e.delays.map(function(t){var e,n,r=t.delay,o=t.id;return e=B(r,o),n={delay:r},{type:i,event:_(e),delay:n?n.delay:void 0,id:n&&void 0!==n.id?n.id:S(e)}}))})).concat(Array.from(r).map(C)):[],exit:t.entryExitStates?P(Array.from(t.entryExitStates.exit).map(function(t){return t.onExit.concat(t.activities.map(function(t){return function(t){var n=M(t);return{type:e.Stop,activity:n,exec:n.stop?n.stop.exec:void 0}}(t)}),t.delays.map(function(t){var e=t.delay,n=t.id;return L(B(e,n))}))})):[]};return o.exit.concat(t.actions).concat(o.entry).map(function(t){return"string"==typeof t?n.resolveAction(t):t})},t.prototype.resolveAction=function(t){var e=this.machine.options.actions;return(e?e[t]:t)||t},t.prototype.resolveActivity=function(t){var e=this.machine.options.activities;return"string"==typeof t?M(e?n({type:t},e[t]):t):t},t.prototype.getActivities=function(t,e){if(!t)return l;var r=n({},e);return Array.from(t.exit).forEach(function(t){t.activities&&t.activities.forEach(function(t){r[t.type]=!1})}),Array.from(t.entry).forEach(function(t){t.activities&&t.activities.forEach(function(t){r[t.type]=!0})}),r},t.prototype.transition=function(t,e,n){var r="string"==typeof t?this.resolve(w(this.getResolvedPath(t))):t instanceof m?t:this.resolve(t),i=n||(t instanceof m?t.context:void 0),o=_(e),a=o.type;if(this.strict&&-1===this.events.indexOf(a))throw new Error("Machine '"+this.id+"' does not accept event '"+a+"'");var s=m.from(r,i),u=this._transition(s.value,s,o,i);return this.resolveTransition(u,s,o)},t.prototype.resolveTransition=function(n,i,o){var u,c=i.historyValue?i.historyValue:n.source?this.machine.historyValue(i.value):void 0,h=this.getActions(n),f=this.getActivities(n.entryExitStates,i.activities),p=h.filter(function(t){return"object"==typeof t&&(t.type===r||t.type===a)}),l=h.filter(function(t){return"object"!=typeof t||t.type!==r&&t.type!==a&&t.type!==s}),v=h.filter(function(t){return"object"==typeof t&&t.type===s}),d=i.context?v.reduce(function(t,n){var r=n.assignment,i={};return"function"==typeof r?i=r(t,o||{type:e.Init}):Object.keys(r).forEach(function(e){var n=r[e];i[e]="function"==typeof n?n(t,o):n}),Object.assign({},t,i)},i.context):i.context,g=n.value?this.getStateNodes(n.value):[];g.some(function(t){return t.transient})&&p.push({type:a});var S=[this].concat(g).reduce(function(t,e){return void 0!==e.data&&(t[e.id]=e.data),t},{}),x=n.value?new m(n.value,d,c?t.updateHistoryValue(c,n.value):void 0,n.source?i:void 0,R(l,this.options.actions),f,S,p):void 0;if(!x)return m.inert(i,d);i.history&&delete i.history.history;for(var b=x;p.length;){var w=b.actions,E=p.shift();(u=(b=this.transition(b,E.type===a?y:E.event,b.context)).actions).unshift.apply(u,w)}return b},t.prototype.ensureValidPaths=function(t){var e=this,n=new Map;t:for(var r=0,i=P(t.map(function(t){return e.getRelativeStateNodes(t)}));r<i.length;r++)for(var o=i[r],a=o;a.parent;){if(n.has(a.parent)){if("parallel"===a.parent.type)continue t;throw new Error("State node '"+o.id+"' shares parent '"+a.parent.id+"' with state node '"+n.get(a.parent).map(function(t){return t.id})+"'")}n.get(a.parent)?n.get(a.parent).push(o):n.set(a.parent,[o]),a=a.parent}},t.prototype.getStateNode=function(t){if(d(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.");var e=this.states[t];if(!e)throw new Error("Child state '"+t+"' does not exist on '"+this.id+"'");return e},t.prototype.getStateNodeById=function(t){var e=d(t)?t.slice("#".length):t;if(e===this.id)return this;var n=this.machine.idMap[e];if(!n)throw new Error("Substate '#"+e+"' does not exist on '"+this.id+"'");return n},t.prototype.getStateNodeByPath=function(t){for(var e=x(t,this.delimiter),n=this;e.length;){var r=e.shift();n=n.getStateNode(r)}return n},t.prototype.resolve=function(t){var e,n=this;if("string"==typeof t){var r=this.getStateNode(t);return r.initial?((e={})[t]=r.initialStateValue,e):t}return"parallel"===this.type?E(this.initialStateValue,function(e,r){return e?n.getStateNode(r).resolve(t[r]||e):l}):E(t,function(t,e){return t?n.getStateNode(e).resolve(t):l})},Object.defineProperty(t.prototype,"resolvedStateValue",{get:function(){var t,e,n=this.key;return"parallel"===this.type?((t={})[n]=O(this.states,function(t){return t.resolvedStateValue[t.key]},function(t){return!t.history}),t):this.initial?((e={})[n]=this.states[this.initial].resolvedStateValue,e):n},enumerable:!0,configurable:!0}),t.prototype.getResolvedPath=function(t){if(d(t)){var e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error("Unable to find state node '"+t+"'");return e.path}return x(t,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){if(this.__cache.initialState)return this.__cache.initialState;var t="parallel"===this.type?O(this.states,function(t){return t.initialStateValue||l},function(t){return!t.history}):"string"==typeof this.resolvedStateValue?void 0:this.resolvedStateValue[this.key];return this.__cache.initialState=t,this.__cache.initialState},enumerable:!0,configurable:!0}),t.prototype.getState=function(t,e){var n=this;void 0===e&&(e=this.machine.context);var i={},o=[];this.getStateNodes(t).forEach(function(t){t.onEntry&&o.push.apply(o,t.onEntry),t.activities&&t.activities.forEach(function(t){i[S(t)]=!0,o.push(F(t))})});var u=o.filter(function(t){return"object"==typeof t&&(t.type===r||t.type===a)}),c=o.filter(function(t){return"object"==typeof t&&t.type===s}),h=e?c.reduce(function(t,e){var n=e.assignment,r={};return"function"==typeof n?r=n(t,{type:"init"}):Object.keys(n).forEach(function(e){var i=n[e];r[e]="function"==typeof i?i(t,{type:"init"}):i}),Object.assign({},t,r)},e):e,f=new m(t,h,void 0,void 0,R(o,this.options.actions),i,void 0,[]);return u.reduce(function(t,e){var r,i=t.actions;return(r=(t=n.transition(t,e.type===a?y:e.event,t.context)).actions).unshift.apply(r,i),t},f)},Object.defineProperty(t.prototype,"initialState",{get:function(){var t=this.initialStateValue;if(!t)throw new Error("Cannot retrieve initial state from simple state '"+this.id+"'.");var e=this.getState(t);return this.resolveTransition({value:e.value,source:void 0,entryExitStates:{entry:new Set(this.getStateNodes(e.value)),exit:new Set},actions:[],paths:[]},e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var t;if(this.history){var e=this.config;t=e.target&&"string"==typeof e.target&&d(e.target)?w(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t},enumerable:!0,configurable:!0}),t.prototype.getStates=function(t){var e=this;if("string"==typeof t)return[this.states[t]];var n=[];return Object.keys(t).forEach(function(r){n.push.apply(n,e.states[r].getStates(t[r]))}),n},t.prototype.getRelativeStateNodes=function(t,e,n){if(void 0===n&&(n=!0),"string"==typeof t&&d(t)){var r=this.getStateNodeById(t);return n?r.history?r.resolveHistory(e):r.initialStateNodes:[r]}var i=x(t,this.delimiter),o=(this.parent||this).getFromRelativePath(i,e);return n?P(o.map(function(t){return t.initialStateNodes})):o},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var t=this;if("atomic"===this.type||"final"===this.type)return[this];var e=this.initialStateValue;return P(k(e).map(function(e){return t.getFromRelativePath(e)}))},enumerable:!0,configurable:!0}),t.prototype.getFromRelativePath=function(t,e){if(!t.length)return[this];var n=t[0],r=t.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '"+n+"' from node with no states");var i=this.getStateNode(n);if(i.history)return i.resolveHistory(e);if(!this.states[n])throw new Error("Child state '"+n+"' does not exist on '"+this.id+"'");return this.states[n].getFromRelativePath(r,e)},t.updateHistoryValue=function(t,e){return{current:e,states:function t(e,n){return E(e.states,function(e,r){if(e){var i=("string"==typeof n?void 0:n[r])||(e?e.current:void 0);if(i)return{current:i,states:t(e,i)}}})}(t,e)}},t.prototype.historyValue=function(t){if(Object.keys(this.states).length)return{current:t||this.initialStateValue,states:O(this.states,function(e,n){if(!t)return e.historyValue();var r="string"==typeof t?void 0:t[n];return e.historyValue(r||e.initialStateValue)},function(t){return!t.history})}},t.prototype.resolveHistory=function(t){var e=this;if(!this.history)return[this];var n=this.parent;if(!t)return this.target?P(k(this.target).map(function(t){return n.getFromRelativePath(t)})):this.parent.initialStateNodes;var r=N(n.path,"states")(t).current;return"string"==typeof r?[n.getStateNode(r)]:P(k(r).map(function(t){return"deep"===e.history?n.getFromRelativePath(t):[n.states[t[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var t=this,e=P(Object.keys(this.states).map(function(e){return t.states[e].stateIds}));return[this.id].concat(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){if(this.__cache.events)return this.__cache.events;var t=this.states,e=new Set(Object.keys(this.on));return t&&Object.keys(t).forEach(function(n){var r=t[n];if(r.states)for(var i=0,o=r.events;i<o.length;i++){var a=o[i];e.add(""+a)}}),this.__cache.events=Array.from(e)},enumerable:!0,configurable:!0}),t.prototype.formatTransition=function(t,e,r){var i=this,o=!!e&&e.internal;if(void 0===t||""===t)return n({},e,{actions:e?V(e.actions):[],target:void 0,internal:!e||(void 0===e.internal||e.internal),event:r});var a=V(t).map(function(t){var e="string"==typeof t&&t[0]===i.delimiter;return o=o||e,e&&!i.parent?t.slice(1):e?i.key+t:t});return n({},e,{actions:e?V(e.actions):[],target:a,internal:o,event:r})},t.prototype.formatTransitions=function(){var t=this,e=this.config.on||l,n=this.after,r=E(e,function(e,n){return void 0===e?[{target:void 0,event:n,actions:[]}]:Array.isArray(e)?e.map(function(e){return t.formatTransition(e.target,e,n)}):"string"==typeof e?[t.formatTransition([e],void 0,n)]:[t.formatTransition(e.target,e,n)]});return n.forEach(function(t){r[t.event]=r[t.event]||[],r[t.event].push(t)}),r}}(),function(){function t(t,e,n,r,i,o,a,s){void 0===i&&(i=[]),void 0===o&&(o=h),void 0===a&&(a={}),void 0===s&&(s=[]),this.value=t,this.context=e,this.historyValue=n,this.history=r,this.actions=i,this.activities=o,this.data=a,this.events=s}return t.from=function(e,n){return e instanceof t?e.context!==n?new t(e.value,n,e.historyValue,e.history,[],e.activities,{},[]):e:new t(e,n,void 0,void 0,[],void 0,void 0,[])},t.inert=function(e,n){return e instanceof t?e.actions.length?new t(e.value,n,e.historyValue,e.history,[],e.activities,void 0,[]):e:t.from(e,n)},t.prototype.toStrings=function(t){var e=this;if(void 0===t&&(t=this.value),"string"==typeof t)return[t];var n=Object.keys(t);return n.concat.apply(n,n.map(function(n){return e.toStrings(t[n]).map(function(t){return n+"."+t})}))},t.prototype.matches=function(t){return f(t,this.value)},Object.defineProperty(t.prototype,"changed",{get:function(){if(this.history)return!!this.actions.length||typeof this.history.value!=typeof this.value||("string"==typeof this.value?this.value!==this.history.value:function t(e,n){if(e===n)return!0;var r=Object.keys(e);var i=Object.keys(n);return r.length===i.length&&r.every(function(r){return t(e[r],n[r])})}(this.value,this.history.value))},enumerable:!0,configurable:!0}),t}());function S(t){try{return"string"==typeof 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 x(t,e){try{return Array.isArray(t)?t:t.toString().split(e)}catch(e){throw new Error("'"+t+"' is not a valid state path.")}}function b(t,e){return t instanceof m?t.value:"object"!=typeof t||t instanceof m?w(x(t,e)):t}function w(t){if(1===t.length)return t[0];for(var e={},n=e,r=0;r<t.length-1;r++)r===t.length-2?n[t[r]]=t[r+1]:(n[t[r]]={},n=n[t[r]]);return e}function E(t,e){var n={};return Object.keys(t).forEach(function(r,i){n[r]=e(t[r],r,t,i)}),n}function O(t,e,n){var r={};return Object.keys(t).forEach(function(i){var o=t[i];n(o)&&(r[i]=e(o,i,t))}),r}var j=function(t){return function(e){for(var n=e,r=0,i=t;r<i.length;r++){n=n[i[r]]}return n}};function N(t,e){return function(n){for(var r=n,i=0,o=t;i<o.length;i++){var a=o[i];r=r[e][a]}return r}}var k=function(t){return"string"==typeof t?[[t]]:P(Object.keys(t).map(function(e){return k(t[e]).map(function(t){return[e].concat(t)})}))},A=function(t){var e={};if(t&&1===t.length&&1===t[0].length)return t[0][0];for(var n=0,r=t;n<r.length;n++)for(var i=r[n],o=e,a=0;a<i.length;a++){var s=i[a];if(a===i.length-2){o[s]=i[a+1];break}o[s]=o[s]||{},o=o[s]}return e};function P(t){var e;return(e=[]).concat.apply(e,t)}function V(t){return Array.isArray(t)?t:void 0===t?[]:[t]}function _(t){return"string"==typeof t||"number"==typeof t?{type:t}:t}function T(t,e){if(e){var n=e[t];if(n)return"function"==typeof n?n:n.exec}}var I=function(t,e){var r;if("string"==typeof t||"number"==typeof t)r={type:t,exec:T(t,e)};else{if("function"!=typeof t){var i=T(t.type,e);return i?n({},t,{exec:i}):t}r={type:t.name,exec:t}}return Object.defineProperty(r,"toString",{value:function(){return r.type},enumerable:!1}),r};function M(t){var e=I(t);return n({},e,{type:e.type,start:e.start?I(e.start):e.exec?I(e.exec):void 0,stop:e.stop?I(e.stop):void 0})}var R=function(t,e){return t?(Array.isArray(t)?t:[t]).map(function(t){return I(t,e)}):[]};function C(t){return{type:r,event:t}}var L=function(t){return{type:o,sendId:t}};function F(t){var n=M(t);return{type:e.Start,activity:n,exec:n.start?n.start.exec:void 0}}function B(t,n){var r=n?"#"+n:"";return e.After+"("+t+")"+r}function H(t){return e.DoneState+"."+t}var Q=function(){function t(){this.timeouts=new Map,this._now=0,this._id=0}return t.prototype.now=function(){return this._now},t.prototype.getId=function(){return this._id++},t.prototype.setTimeout=function(t,e){var n=this.getId();return this.timeouts.set(n,{start:this.now(),timeout:e,fn:t}),n},t.prototype.clearTimeout=function(t){this.timeouts.delete(t)},t.prototype.set=function(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()},t.prototype.flushTimeouts=function(){var t=this;this.timeouts.forEach(function(e,n){t.now()-e.start>=e.timeout&&(e.fn.call(null),t.timeouts.delete(n))})},t.prototype.increment=function(t){this._now+=t,this.flushTimeouts()},t}(),z=function(){function t(e,r,i){void 0===i&&(i=t.defaultOptions);var o=this;this.machine=e,this.eventQueue=[],this.delayedEventsMap={},this.listeners=new Set,this.stopListeners=new Set,this.initialized=!1,this.init=this.start,this.send=function(t){var e=_(t);if(!o.initialized)throw new Error('Unable to send event "'+e.type+'" to an uninitialized interpreter.');var n=o.machine.transition(o.state,e,o.extState);return o.update(n,t),o.flushEventQueue(),n},r&&this.onTransition(r);var a=n({},t.defaultOptions,i);this.clock=a.clock,this.logger=a.logger}return t.prototype.update=function(t,e){var n=this;this.state=t;var r=this.state.context;this.state.actions.forEach(function(t){n.exec(t,r,e?_(e):void 0)},r),this.listeners.forEach(function(e){return e(t)})},t.prototype.onTransition=function(t){return this.listeners.add(t),this},t.prototype.onStop=function(t){return this.stopListeners.add(t),this},t.prototype.off=function(t){return this.listeners.delete(t),this},t.prototype.start=function(t){return void 0===t&&(t=this.machine.initialState),this.update(t),this.initialized=!0,this},t.prototype.stop=function(){var t=this;return this.listeners.forEach(function(e){return t.off(e)}),this.stopListeners.forEach(function(e){e(),t.stopListeners.delete(e)}),this},t.prototype.defer=function(t){var e=this;return this.clock.setTimeout(function(){return e.send(t.event)},t.delay||0)},t.prototype.cancel=function(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]},t.prototype.exec=function(t,e,n){if(t.exec)return t.exec(e,n);switch(t.type){case i:var r=t;r.delay?this.delayedEventsMap[r.id]=this.defer(r):this.eventQueue.push(r.event);break;case o:this.cancel(t.sendId);break;case u:var a=t.expr?t.expr(e,n):void 0;t.label?this.logger(t.label,a):this.logger(a);break;default:console.warn("No implementation found for action type '"+t.type+"'")}},t.prototype.flushEventQueue=function(){var t=this.eventQueue.shift();t&&this.send(t)},t.defaultOptions={clock:{setTimeout:setTimeout,clearTimeout:clearTimeout},logger:global.console.log.bind(console)},t.interpret=U,t}();function U(t,e,n){return new z(t,e,n)}t.SimulatedClock=Q,t.Interpreter=z,t.interpret=U,Object.defineProperty(t,"__esModule",{value:!0})}); |
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.xstate={})}(this,function(t){"use strict";var e=".",n={},r=function(){function t(t,e,r,i,a,o,s,u){void 0===a&&(a=[]),void 0===o&&(o=n),void 0===s&&(s={}),void 0===u&&(u=[]),this.value=t,this.context=e,this.historyValue=r,this.history=i,this.actions=a,this.activities=o,this.data=s,this.events=u}return t.from=function(e,n){return e instanceof t?e.context!==n?new t(e.value,n,e.historyValue,e.history,[],e.activities,{},[]):e:new t(e,n,void 0,void 0,[],void 0,void 0,[])},t.inert=function(e,n){return e instanceof t?e.actions.length?new t(e.value,n,e.historyValue,e.history,[],e.activities,void 0,[]):e:t.from(e,n)},t.prototype.toStrings=function(t){var e=this;if(void 0===t&&(t=this.value),"string"==typeof t)return[t];var n=Object.keys(t);return n.concat.apply(n,n.map(function(n){return e.toStrings(t[n]).map(function(t){return n+"."+t})}))},t.prototype.matches=function(t){return d(t,this.value)},Object.defineProperty(t.prototype,"changed",{get:function(){return!!this.history&&(!!this.actions.length||typeof this.history.value!==this.value||("string"==typeof this.value?this.value!==this.history.value:function t(e,n){if(e===n)return!0;var r=Object.keys(e);var i=Object.keys(n);return r.length===i.length&&r.every(function(r){return t(e[r],n[r])})}(this.value,this.history.value)))},enumerable:!0,configurable:!0}),t}();function i(t){try{return"string"==typeof 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 Array.isArray(t)?t:t.toString().split(e)}catch(e){throw new Error("'"+t+"' is not a valid state path.")}}function o(t,e){return t instanceof r?t.value:"object"!=typeof t||t instanceof r?s(a(t,e)):t}function s(t){if(1===t.length)return t[0];for(var e={},n=e,r=0;r<t.length-1;r++)r===t.length-2?n[t[r]]=t[r+1]:(n[t[r]]={},n=n[t[r]]);return e}function u(t,e){var n={};return Object.keys(t).forEach(function(r,i){n[r]=e(t[r],r,t,i)}),n}function c(t,e,n){var r={};return Object.keys(t).forEach(function(i){var a=t[i];n(a)&&(r[i]=e(a,i,t))}),r}var f=function(t){return function(e){for(var n=e,r=0,i=t;r<i.length;r++){n=n[i[r]]}return n}};function h(t,e){return function(n){for(var r=n,i=0,a=t;i<a.length;i++){var o=a[i];r=r[e][o]}return r}}var p=function(t){return"string"==typeof t?[[t]]:v(Object.keys(t).map(function(e){return p(t[e]).map(function(t){return[e].concat(t)})}))},y=function(t){var e={};if(t&&1===t.length&&1===t[0].length)return t[0][0];for(var n=0,r=t;n<r.length;n++)for(var i=r[n],a=e,o=0;o<i.length;o++){var s=i[o];if(o===i.length-2){a[s]=i[o+1];break}a[s]=a[s]||{},a=a[s]}return e};function v(t){var e;return(e=[]).concat.apply(e,t)}function l(t){return Array.isArray(t)?t:void 0===t?[]:[t]}function d(t,n,r){void 0===r&&(r=e);var i=o(t,r),a=o(n,r);return"string"==typeof a?"string"==typeof i&&a===i:"string"==typeof i?i in a:Object.keys(i).every(function(t){return t in a&&d(i[t],a[t])})}var g,m=function(){return(m=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};(g=t.ActionTypes||(t.ActionTypes={})).Start="xstate.start",g.Stop="xstate.stop",g.Raise="xstate.raise",g.Send="xstate.send",g.Cancel="xstate.cancel",g.Null="xstate.null",g.Assign="xstate.assign",g.After="xstate.after",g.DoneState="done.state",g.Log="xstate.log";var S=t.ActionTypes.Start,b=t.ActionTypes.Stop,x=t.ActionTypes.Raise,j=t.ActionTypes.Send,E=t.ActionTypes.Cancel,w=t.ActionTypes.Null,O=t.ActionTypes.Assign,A=t.ActionTypes.After,N=t.ActionTypes.DoneState,k=t.ActionTypes.Log,P=Object.freeze({start:S,stop:b,raise:x,send:j,cancel:E,_null:w,null:w,assign:O,after:A,doneState:N,log:k}),V=function(t,e){if("string"==typeof t||"number"==typeof t){var n={type:t};return void 0!==e&&(n.id=e),n}return t};function T(t,e){if(e){var n=e[t];if(n)return"function"==typeof n?n:n.exec}}var _=function(t,e){var n;if("string"==typeof t||"number"==typeof t)n={type:t,exec:T(t,e)};else{if("function"!=typeof t){var r=T(t.type,e);return r?m({},t,{exec:r}):t}n={type:t.name,exec:t}}return Object.defineProperty(n,"toString",{value:function(){return n.type},enumerable:!1}),n};function R(t){var e=_(t);return m({},e,{type:e.type,start:e.start?_(e.start):e.exec?_(e.exec):void 0,stop:e.stop?_(e.stop):void 0})}var M=function(t,e){return t?(Array.isArray(t)?t:[t]).map(function(t){return _(t,e)}):[]},C=function(t){return{type:x,event:t}},I=function(t,e){return{type:j,event:V(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:i(t)}};var F=function(t){return{type:E,sendId:t}};function B(e){var n=R(e);return{type:t.ActionTypes.Start,activity:n,exec:n.start?n.start.exec:void 0}}function H(e){var n=R(e);return{type:t.ActionTypes.Stop,activity:n,exec:n.stop?n.stop.exec:void 0}}function D(e,n){var r=n?"#"+n:"";return t.ActionTypes.After+"("+e+")"+r}function L(e){return t.ActionTypes.DoneState+"."+e}var z=Object.freeze({actionTypes:P,toEventObject:V,toActionObject:_,toActivityDefinition:R,toActionObjects:M,raise:C,send:I,log:function(t,e){return{type:k,label:e,expr:t}},cancel:F,start:B,stop:H,assign:function(t){return{type:O,assignment:t}},isActionObject:function(t){return"object"==typeof t&&"type"in t},after:D,done:L}),U=".",q="",G={},J=[],K=function(t){return"#"===t[0]},Q=function(){return{guards:G}},W=function(){function t(e,n,r){void 0===n&&(n=Q());var i=this;this._config=e,this.options=n,this.context=r,this.__cache={events:void 0,relativeValue:new Map,initialState:void 0},this.idMap={},this.key=e.key||e.id||"(machine)",this.type=e.type||(e.parallel?"parallel":e.states&&Object.keys(e.states).length?"compound":e.history?"history":"atomic"),this.parent=e.parent,this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=e.delimiter||(this.parent?this.parent.delimiter:U),this.id=e.id||(this.machine?[this.machine.key].concat(this.path).join(this.delimiter):this.key),this.initial=e.initial,this.order=e.order||-1,this.states=e.states?u(e.states,function(e,n,r,a){var o,s=new t(m({},e,{key:n,order:void 0===e.order?e.order:a,parent:i}));return Object.assign(i.idMap,m(((o={})[s.id]=s,o),s.idMap)),s}):G,this.history=!0===e.history?"shallow":e.history||!1,this.transient=!(!e.on||!e.on[q]),this.strict=!!e.strict,this.onEntry=l(e.onEntry),this.onExit=l(e.onExit),this.data=e.data,this.activities=l(e.activities).map(function(t){return i.resolveActivity(t)})}return Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,type:this.type,initial:this.initial,history:this.history,states:u(this.states,function(t){return t.definition}),on:this.on,onEntry:this.onEntry,onExit:this.onExit,after:this.after,activities:this.activities||J,data:this.data,order:this.order||-1}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"config",{get:function(){var t=this._config;t.parent;return function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&(n[r[i]]=t[r[i]])}return n}(t,["parent"])},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"on",{get:function(){return this.formatTransitions()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){var t=this,e=this.config.after;if(!e)return J;if(Array.isArray(e))return e.map(function(e){return m({event:D(e.delay,t.id)},e,{actions:l(e.actions)})});var n=v(Object.keys(e).map(function(n){var r=e[n],i=+n,a=D(i,t.id);return"string"==typeof r?[{target:r,delay:i,event:a,actions:[]}]:l(r).map(function(t){return m({event:a,delay:i},t,{actions:l(t.actions)})})}));return n.sort(function(t,e){return t.delay-e.delay}),n},enumerable:!0,configurable:!0}),t.prototype.getStateNodes=function(t){var e,n=this;if(!t)return[];var i=t instanceof r?t.value:o(t,this.delimiter);if("string"==typeof i){var a=this.getStateNode(i).initial;return a?this.getStateNodes(((e={})[i]=a,e)):[this.states[i]]}var s=Object.keys(i);return s.map(function(t){return n.getStateNode(t)}).concat(s.reduce(function(t,e){var r=n.getStateNode(e).getStateNodes(i[e]);return t.concat(r)},[]))},t.prototype.handles=function(t){var e=i(t);return-1!==this.events.indexOf(e)},t.prototype.transitionLeafNode=function(t,e,n,r){var i=this.getStateNode(t),a=i.next(e,n,r);if(!a.value){var o=this.next(e,n,r),s=o.value,u=o.entryExitStates,c=o.actions,f=o.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set([i].concat(u?Array.from(u.exit):[]))},actions:c,paths:f}}return a},t.prototype.transitionNestedNode=function(t,e,n,r){var i=Object.keys(t),a=this.getStateNode(i[0]),o=a._transition(t[i[0]],e,n,r);if(!o.value){var s=this.next(e,n,r),u=s.value,c=s.entryExitStates,f=s.actions,h=s.paths;return{value:u,source:e,entryExitStates:{entry:c?c.entry:new Set,exit:new Set((o.entryExitStates?Array.from(o.entryExitStates.exit):[]).concat([a],c?Array.from(c.exit):[]))},actions:f,paths:h}}return o},t.prototype.transitionParallelNode=function(t,e,n,r){var i=this,a={};if(Object.keys(t).forEach(function(o){var s=t[o];if(s){var u=i.getStateNode(o)._transition(s,e,n,r);u.value,a[o]=u}}),!Object.keys(a).some(function(t){return void 0!==a[t].value})){var o=this.next(e,n,r),u=o.value,c=o.entryExitStates,h=o.actions,l=o.paths;return{value:u,source:e,entryExitStates:{entry:c?c.entry:new Set,exit:new Set(Object.keys(this.states).map(function(t){return i.states[t]}).concat(c?Array.from(c.exit):[]))},actions:h,paths:l}}var g=v(Object.keys(a).map(function(t){return a[t].paths}));if(1===g.length&&!d(s(this.path),s(g[0])))return{value:this.machine.resolve(y(g)),source:e,entryExitStates:Object.keys(a).map(function(t){return a[t].entryExitStates}).reduce(function(t,e){var n=e,r=n.entry,i=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(r))),exit:new Set(Array.from(t.exit).concat(Array.from(i)))}},{entry:new Set,exit:new Set}),actions:v(Object.keys(a).map(function(t){return a[t].actions})),paths:g};var m=v(Object.keys(a).map(function(t){var n=a[t].value||e.value;return p(f(i.path)(n)[t]).map(function(e){return i.path.concat(t,e)})})),S=this.machine.resolve(y(m));return{value:S,source:e,entryExitStates:Object.keys(a).reduce(function(t,e){var n=a[e],r=n.value,i=n.entryExitStates;if(!r||!i)return t;var o=i.entry,s=i.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(o))),exit:new Set(Array.from(t.exit).concat(Array.from(s)))}},{entry:new Set,exit:new Set}),actions:v(Object.keys(a).map(function(t){return a[t].actions})),paths:p(S)}},t.prototype._transition=function(t,e,n,r){return"string"==typeof t?this.transitionLeafNode(t,e,n,r):1===Object.keys(t).length?this.transitionNestedNode(t,e,n,r):this.transitionParallelNode(t,e,n,r)},t.prototype.next=function(t,e,n){var r=this,i=e.type,a=this.on[i],s=this.transient?[{type:w}]:[];if(!a||!a.length)return{value:void 0,source:t,entryExitStates:void 0,actions:s,paths:[]};for(var u,c=[],h=0,p=a;h<p.length;h++){var g=p[h],m=g,S=m.cond,b=m.in,x=n||G,j=!b||d(o(b,this.delimiter),f(this.path.slice(0,-2))(t.value));if((!S||this.evaluateCond(S,x,e,t.value))&&j){c=l(g.target),s.push.apply(s,l(g.actions)),u=g;break}}if(u&&0===c.length)return{value:t.value,source:t,entryExitStates:void 0,actions:s,paths:[]};if(!u&&0===c.length)return{value:void 0,source:t,entryExitStates:void 0,actions:s,paths:[]};var E=v(c.map(function(e){return r.getRelativeStateNodes(e,t.historyValue)})),O=E.map(function(t){return t.path}),A=E.reduce(function(t,e){var n=r.getEntryExitStates(e,!!u.internal),i=n.entry,a=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(i))),exit:new Set(Array.from(t.exit).concat(Array.from(a)))}},{entry:new Set,exit:new Set});return{value:this.machine.resolve(y(v(c.map(function(e){return r.getRelativeStateNodes(e,t.historyValue).map(function(t){return t.path})})))),source:t,entryExitStates:A,actions:s,paths:O}},t.prototype.getStateNodeValueTree=function(t){var e,n=this;return"string"==typeof t?{stateNode:this,value:(e={},e[t]={stateNode:this.getStateNode(t),value:void 0},e)}:{stateNode:this,value:u(t,function(t,e){return n.getStateNode(e).getStateNodeValueTree(t)})}},t.prototype.getEntryExitStates=function(t,e){for(var n={entry:[],exit:[]},r=this.path,i=t.path,a=this.machine,o=0;o<Math.min(r.length,i.length);o++){var s=r[o];if(s!==i[o])break;a=a.getStateNode(s)}for(var u=a.path,c=a,f=0,h=r.slice(u.length);f<h.length;f++){var p=h[f];c=c.getStateNode(p),n.exit.unshift(c)}a===this&&(e||(n.exit.push(this),n.entry.push(this))),c=a;for(var y=0,v=i.slice(u.length);y<v.length;y++){p=v[y];c=c.getStateNode(p),n.entry.push(c)}return{entry:new Set(n.entry),exit:new Set(n.exit)}},t.prototype.evaluateCond=function(t,e,n,r){var i,a=this.machine.options.guards;if("string"==typeof t){if(!a||!a[t])throw new Error("Condition '"+t+"' is not implemented on machine '"+this.machine.id+"'.");i=a[t]}else i=t;return i(e,n,r)},Object.defineProperty(t.prototype,"delays",{get:function(){var t=this;return Array.from(new Set(this.after.map(function(t){return t.delay}))).map(function(e){return{id:t.id,delay:e}})},enumerable:!0,configurable:!0}),t.prototype.getActions=function(t){var e=this,n=new Set,r={entry:t.entryExitStates?v(Array.from(t.entryExitStates.entry).map(function(r){if("final"===r.type){var i=e.getStateNodeValueTree(t.value);n.add(L(r.id));var a=r.parent?r.parent.parent:void 0;if(a){var o=h(a.path,"value")(i);Object.keys(o.value).every(function(t){return Object.keys(o.value[t].value).every(function(e){return"final"===o.value[t].value[e].stateNode.type})})&&n.add(L(o.stateNode.id))}}return r.onEntry.concat(r.activities.map(function(t){return B(t)}),r.delays.map(function(t){var e=t.delay,n=t.id;return I(D(e,n),{delay:e})}))})).concat(Array.from(n).map(C)):[],exit:t.entryExitStates?v(Array.from(t.entryExitStates.exit).map(function(t){return t.onExit.concat(t.activities.map(function(t){return H(t)}),t.delays.map(function(t){var e=t.delay,n=t.id;return F(D(e,n))}))})):[]};return r.exit.concat(t.actions).concat(r.entry).map(function(t){return"string"==typeof t?e.resolveAction(t):t})},t.prototype.resolveAction=function(t){var e=this.machine.options.actions;return(e?e[t]:t)||t},t.prototype.resolveActivity=function(t){var e=this.machine.options.activities;return"string"==typeof t?R(e?m({type:t},e[t]):t):t},t.prototype.getActivities=function(t,e){if(!t)return G;var n=m({},e);return Array.from(t.exit).forEach(function(t){t.activities&&t.activities.forEach(function(t){n[t.type]=!1})}),Array.from(t.entry).forEach(function(t){t.activities&&t.activities.forEach(function(t){n[t.type]=!0})}),n},t.prototype.transition=function(t,e,n){var i="string"==typeof t?this.resolve(s(this.getResolvedPath(t))):t instanceof r?t:this.resolve(t),a=n||(t instanceof r?t.context:void 0),o=V(e),u=o.type;if(this.strict&&-1===this.events.indexOf(u))throw new Error("Machine '"+this.id+"' does not accept event '"+u+"'");var c=r.from(i,a),f=this._transition(c.value,c,o,a);return this.resolveTransition(f,c,o)},t.prototype.resolveTransition=function(e,n,i){var a,o=n.historyValue?n.historyValue:e.source?this.machine.historyValue(n.value):void 0;try{this.ensureValidPaths(e.paths)}catch(t){throw new Error("Event '"+(i?i.type:"none")+"' leads to an invalid configuration: "+t.message)}var s=this.getActions(e),u=this.getActivities(e.entryExitStates,n.activities),c=s.filter(function(t){return"object"==typeof t&&(t.type===x||t.type===w)}),f=s.filter(function(t){return"object"!=typeof t||t.type!==x&&t.type!==w&&t.type!==O}),h=s.filter(function(t){return"object"==typeof t&&t.type===O}),p=n.context?h.reduce(function(t,e){var n=e.assignment,r={};return"function"==typeof n?r=n(t,i||{type:"xstate.init"}):Object.keys(n).forEach(function(e){var a=n[e];r[e]="function"==typeof a?a(t,i):a}),Object.assign({},t,r)},n.context):n.context,y=e.value?this.getStateNodes(e.value):[];y.some(function(t){return t.transient})&&c.push({type:w});var v=[this].concat(y).reduce(function(t,e){return void 0!==e.data&&(t[e.id]=e.data),t},{}),l=e.value?new r(e.value,p,o?t.updateHistoryValue(o,e.value):void 0,e.source?n:void 0,M(f,this.options.actions),u,v,c):void 0;if(!l)return r.inert(n,p);delete n.history;for(var d=l;c.length;){var g=d.actions,m=c.shift();(a=(d=this.transition(d,m.type===w?q:m.event,d.context)).actions).unshift.apply(a,g)}return d},t.prototype.ensureValidPaths=function(t){var e=this,n=new Map;t:for(var r=0,i=v(t.map(function(t){return e.getRelativeStateNodes(t)}));r<i.length;r++)for(var a=i[r],o=a;o.parent;){if(n.has(o.parent)){if("parallel"===o.parent.type)continue t;throw new Error("State node '"+a.id+"' shares parent '"+o.parent.id+"' with state node '"+n.get(o.parent).map(function(t){return t.id})+"'")}n.get(o.parent)?n.get(o.parent).push(a):n.set(o.parent,[a]),o=o.parent}},t.prototype.getStateNode=function(t){if(K(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.");var e=this.states[t];if(!e)throw new Error("Child state '"+t+"' does not exist on '"+this.id+"'");return e},t.prototype.getStateNodeById=function(t){var e=K(t)?t.slice("#".length):t;if(e===this.id)return this;var n=this.machine.idMap[e];if(!n)throw new Error("Substate '#"+e+"' does not exist on '"+this.id+"'");return n},t.prototype.getStateNodeByPath=function(t){for(var e=a(t,this.delimiter),n=this;e.length;){var r=e.shift();n=n.getStateNode(r)}return n},t.prototype.resolve=function(t){var e,n=this;if("string"==typeof t){var r=this.getStateNode(t);return r.initial?((e={})[t]=r.initialStateValue,e):t}return"parallel"===this.type?u(this.initialStateValue,function(e,r){return e?n.getStateNode(r).resolve(t[r]||e):G}):u(t,function(t,e){return t?n.getStateNode(e).resolve(t):G})},Object.defineProperty(t.prototype,"resolvedStateValue",{get:function(){var t,e,n=this.key;return"parallel"===this.type?((t={})[n]=c(this.states,function(t){return t.resolvedStateValue[t.key]},function(t){return!t.history}),t):this.initial?((e={})[n]=this.states[this.initial].resolvedStateValue,e):n},enumerable:!0,configurable:!0}),t.prototype.getResolvedPath=function(t){if(K(t)){var e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error("Unable to find state node '"+t+"'");return e.path}return a(t,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){if(this.__cache.initialState)return this.__cache.initialState;var t="parallel"===this.type?c(this.states,function(t){return t.initialStateValue||G},function(t){return!t.history}):"string"==typeof this.resolvedStateValue?void 0:this.resolvedStateValue[this.key];return this.__cache.initialState=t,this.__cache.initialState},enumerable:!0,configurable:!0}),t.prototype.getState=function(t,e){var n=this;void 0===e&&(e=this.machine.context);var a={},o=[];this.getStateNodes(t).forEach(function(t){t.onEntry&&o.push.apply(o,t.onEntry),t.activities&&t.activities.forEach(function(t){a[i(t)]=!0,o.push(B(t))})});var s=o.filter(function(t){return"object"==typeof t&&(t.type===x||t.type===w)}),u=o.filter(function(t){return"object"==typeof t&&t.type===O}),c=e?u.reduce(function(t,e){var n=e.assignment,r={};return"function"==typeof n?r=n(t,{type:"init"}):Object.keys(n).forEach(function(e){var i=n[e];r[e]="function"==typeof i?i(t,{type:"init"}):i}),Object.assign({},t,r)},e):e,f=new r(t,c,void 0,void 0,M(o,this.options.actions),a,void 0,[]);return s.reduce(function(t,e){var r,i=t.actions;return(r=(t=n.transition(t,e.type===w?q:e.event,t.context)).actions).unshift.apply(r,i),t},f)},Object.defineProperty(t.prototype,"initialState",{get:function(){var t=this.initialStateValue;if(!t)throw new Error("Cannot retrieve initial state from simple state '"+this.id+"'.");var e=this.getState(t);return this.resolveTransition({value:e.value,source:void 0,entryExitStates:{entry:new Set(this.getStateNodes(e.value)),exit:new Set},actions:[],paths:[]},e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var t;if(this.history){var e=this.config;t=e.target&&"string"==typeof e.target&&K(e.target)?s(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t},enumerable:!0,configurable:!0}),t.prototype.getStates=function(t){var e=this;if("string"==typeof t)return[this.states[t]];var n=[];return Object.keys(t).forEach(function(r){n.push.apply(n,e.states[r].getStates(t[r]))}),n},t.prototype.getRelativeStateNodes=function(t,e,n){if(void 0===n&&(n=!0),"string"==typeof t&&K(t)){var r=this.getStateNodeById(t);return n?r.history?r.resolveHistory(e):r.initialStateNodes:[r]}var i=a(t,this.delimiter),o=(this.parent||this).getFromRelativePath(i,e);return n?v(o.map(function(t){return t.initialStateNodes})):o},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var t=this;if("atomic"===this.type||"final"===this.type)return[this];var e=this.initialStateValue;return v(p(e).map(function(e){return t.getFromRelativePath(e)}))},enumerable:!0,configurable:!0}),t.prototype.getFromRelativePath=function(t,e){if(!t.length)return[this];var n=t[0],r=t.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '"+n+"' from node with no states");var i=this.getStateNode(n);if(i.history)return i.resolveHistory(e);if(!this.states[n])throw new Error("Child state '"+n+"' does not exist on '"+this.id+"'");return this.states[n].getFromRelativePath(r,e)},t.updateHistoryValue=function(t,e){return{current:e,states:function t(e,n){return u(e.states,function(e,r){if(e){var i=("string"==typeof n?void 0:n[r])||(e?e.current:void 0);if(i)return{current:i,states:t(e,i)}}})}(t,e)}},t.prototype.historyValue=function(t){if(Object.keys(this.states).length)return{current:t||this.initialStateValue,states:c(this.states,function(e,n){if(!t)return e.historyValue();var r="string"==typeof t?void 0:t[n];return e.historyValue(r||e.initialStateValue)},function(t){return!t.history})}},t.prototype.resolveHistory=function(t){var e=this;if(!this.history)return[this];var n=this.parent;if(!t)return this.target?v(p(this.target).map(function(t){return n.getFromRelativePath(t)})):this.parent.initialStateNodes;var r=h(n.path,"states")(t).current;return"string"==typeof r?[n.getStateNode(r)]:v(p(r).map(function(t){return"deep"===e.history?n.getFromRelativePath(t):[n.states[t[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var t=this,e=v(Object.keys(this.states).map(function(e){return t.states[e].stateIds}));return[this.id].concat(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){if(this.__cache.events)return this.__cache.events;var t=this.states,e=new Set(Object.keys(this.on));return t&&Object.keys(t).forEach(function(n){var r=t[n];if(r.states)for(var i=0,a=r.events;i<a.length;i++){var o=a[i];e.add(""+o)}}),this.__cache.events=Array.from(e)},enumerable:!0,configurable:!0}),t.prototype.formatTransition=function(t,e,n){var r=this,i=!!e&&e.internal;if(void 0===t||""===t)return m({},e,{actions:e?l(e.actions):[],target:void 0,internal:!e||(void 0===e.internal||e.internal),event:n});var a=l(t).map(function(t){var e="string"==typeof t&&t[0]===r.delimiter;return i=i||e,e&&!r.parent?t.slice(1):e?r.key+t:t});return m({},e,{actions:e?l(e.actions):[],target:a,internal:i,event:n})},t.prototype.formatTransitions=function(){var t=this,e=this.config.on||G,n=this.after,r=u(e,function(e,n){return void 0===e?[{target:void 0,event:n,actions:[]}]:Array.isArray(e)?e.map(function(e){return t.formatTransition(e.target,e,n)}):"string"==typeof e?[t.formatTransition([e],void 0,n)]:[t.formatTransition(e.target,e,n)]});return n.forEach(function(t){r[t.event]=r[t.event]||[],r[t.event].push(t)}),r},t}();t.Machine=function(t,e,n){return new W(t,e,n)},t.StateNode=W,t.State=r,t.matchesState=d,t.mapState=function(t,e){var n;return Object.keys(t).forEach(function(t){d(t,e)&&(!n||e.length>n.length)&&(n=t)}),t[n]},t.actions=z,Object.defineProperty(t,"__esModule",{value:!0})}); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.xstate={})}(this,function(t){"use strict";var e=".",n={},r=function(){function t(t,e,r,i,a,o,s,u){void 0===a&&(a=[]),void 0===o&&(o=n),void 0===s&&(s={}),void 0===u&&(u=[]),this.value=t,this.context=e,this.historyValue=r,this.history=i,this.actions=a,this.activities=o,this.data=s,this.events=u}return t.from=function(e,n){return e instanceof t?e.context!==n?new t(e.value,n,e.historyValue,e.history,[],e.activities,{},[]):e:new t(e,n,void 0,void 0,[],void 0,void 0,[])},t.inert=function(e,n){return e instanceof t?e.actions.length?new t(e.value,n,e.historyValue,e.history,[],e.activities,void 0,[]):e:t.from(e,n)},t.prototype.toStrings=function(t){var e=this;if(void 0===t&&(t=this.value),"string"==typeof t)return[t];var n=Object.keys(t);return n.concat.apply(n,n.map(function(n){return e.toStrings(t[n]).map(function(t){return n+"."+t})}))},t.prototype.matches=function(t){return d(t,this.value)},Object.defineProperty(t.prototype,"changed",{get:function(){if(this.history)return!!this.actions.length||typeof this.history.value!=typeof this.value||("string"==typeof this.value?this.value!==this.history.value:function t(e,n){if(e===n)return!0;var r=Object.keys(e);var i=Object.keys(n);return r.length===i.length&&r.every(function(r){return t(e[r],n[r])})}(this.value,this.history.value))},enumerable:!0,configurable:!0}),t}();function i(t){try{return"string"==typeof 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 Array.isArray(t)?t:t.toString().split(e)}catch(e){throw new Error("'"+t+"' is not a valid state path.")}}function o(t,e){return t instanceof r?t.value:"object"!=typeof t||t instanceof r?s(a(t,e)):t}function s(t){if(1===t.length)return t[0];for(var e={},n=e,r=0;r<t.length-1;r++)r===t.length-2?n[t[r]]=t[r+1]:(n[t[r]]={},n=n[t[r]]);return e}function u(t,e){var n={};return Object.keys(t).forEach(function(r,i){n[r]=e(t[r],r,t,i)}),n}function c(t,e,n){var r={};return Object.keys(t).forEach(function(i){var a=t[i];n(a)&&(r[i]=e(a,i,t))}),r}var f=function(t){return function(e){for(var n=e,r=0,i=t;r<i.length;r++){n=n[i[r]]}return n}};function h(t,e){return function(n){for(var r=n,i=0,a=t;i<a.length;i++){var o=a[i];r=r[e][o]}return r}}var p=function(t){return"string"==typeof t?[[t]]:v(Object.keys(t).map(function(e){return p(t[e]).map(function(t){return[e].concat(t)})}))},y=function(t){var e={};if(t&&1===t.length&&1===t[0].length)return t[0][0];for(var n=0,r=t;n<r.length;n++)for(var i=r[n],a=e,o=0;o<i.length;o++){var s=i[o];if(o===i.length-2){a[s]=i[o+1];break}a[s]=a[s]||{},a=a[s]}return e};function v(t){var e;return(e=[]).concat.apply(e,t)}function l(t){return Array.isArray(t)?t:void 0===t?[]:[t]}function d(t,n,r){void 0===r&&(r=e);var i=o(t,r),a=o(n,r);return"string"==typeof a?"string"==typeof i&&a===i:"string"==typeof i?i in a:Object.keys(i).every(function(t){return t in a&&d(i[t],a[t])})}var g,m=function(){return(m=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};(g=t.ActionTypes||(t.ActionTypes={})).Start="xstate.start",g.Stop="xstate.stop",g.Raise="xstate.raise",g.Send="xstate.send",g.Cancel="xstate.cancel",g.Null="",g.Assign="xstate.assign",g.After="xstate.after",g.DoneState="done.state",g.Log="xstate.log",g.Init="xstate.init";var S=t.ActionTypes.Start,b=t.ActionTypes.Stop,x=t.ActionTypes.Raise,j=t.ActionTypes.Send,A=t.ActionTypes.Cancel,O=t.ActionTypes.Null,E=t.ActionTypes.Assign,w=t.ActionTypes.After,N=t.ActionTypes.DoneState,k=t.ActionTypes.Log,P=t.ActionTypes.Init,T=Object.freeze({start:S,stop:b,raise:x,send:j,cancel:A,_null:O,null:O,assign:E,after:w,doneState:N,log:k,init:P});function V(t){return"string"==typeof t||"number"==typeof t?{type:t}:t}function _(t,e){if(e){var n=e[t];if(n)return"function"==typeof n?n:n.exec}}var R=function(t,e){var n;if("string"==typeof t||"number"==typeof t)n={type:t,exec:_(t,e)};else{if("function"!=typeof t){var r=_(t.type,e);return r?m({},t,{exec:r}):t}n={type:t.name,exec:t}}return Object.defineProperty(n,"toString",{value:function(){return n.type},enumerable:!1}),n};function M(t){var e=R(t);return m({},e,{type:e.type,start:e.start?R(e.start):e.exec?R(e.exec):void 0,stop:e.stop?R(e.stop):void 0})}var I=function(t,e){return t?(Array.isArray(t)?t:[t]).map(function(t){return R(t,e)}):[]};function C(t){return{type:x,event:t}}function F(t,e){return{type:j,event:V(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:i(t)}}var B=function(t){return{type:A,sendId:t}};function H(e){var n=M(e);return{type:t.ActionTypes.Start,activity:n,exec:n.start?n.start.exec:void 0}}function D(e){var n=M(e);return{type:t.ActionTypes.Stop,activity:n,exec:n.stop?n.stop.exec:void 0}}function L(e,n){var r=n?"#"+n:"";return t.ActionTypes.After+"("+e+")"+r}function z(e){return t.ActionTypes.DoneState+"."+e}var U=Object.freeze({actionTypes:T,toEventObject:V,toActionObject:R,toActivityDefinition:M,toActionObjects:I,raise:C,send:F,log:function(t,e){return{type:k,label:e,expr:t}},cancel:B,start:H,stop:D,assign:function(t){return{type:E,assignment:t}},isActionObject:function(t){return"object"==typeof t&&"type"in t},after:L,done:z}),q=".",G="",J={},K=[],Q=function(t){return"#"===t[0]},W=function(){return{guards:J}},X=function(){function e(t,n,r){void 0===n&&(n=W());var i=this;this._config=t,this.options=n,this.context=r,this.__cache={events:void 0,relativeValue:new Map,initialState:void 0},this.idMap={},this.key=t.key||t.id||"(machine)",this.type=t.type||(t.parallel?"parallel":t.states&&Object.keys(t.states).length?"compound":t.history?"history":"atomic"),this.parent=t.parent,this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=t.delimiter||(this.parent?this.parent.delimiter:q),this.id=t.id||(this.machine?[this.machine.key].concat(this.path).join(this.delimiter):this.key),this.initial=t.initial,this.order=t.order||-1,this.states=t.states?u(t.states,function(t,n,r,a){var o,s=new e(m({},t,{key:n,order:void 0===t.order?t.order:a,parent:i}));return Object.assign(i.idMap,m(((o={})[s.id]=s,o),s.idMap)),s}):J,this.history=!0===t.history?"shallow":t.history||!1,this.transient=!(!t.on||!t.on[G]),this.strict=!!t.strict,this.onEntry=l(t.onEntry),this.onExit=l(t.onExit),this.data=t.data,this.activities=l(t.activities).map(function(t){return i.resolveActivity(t)})}return Object.defineProperty(e.prototype,"definition",{get:function(){return{id:this.id,key:this.key,type:this.type,initial:this.initial,history:this.history,states:u(this.states,function(t){return t.definition}),on:this.on,onEntry:this.onEntry,onExit:this.onExit,after:this.after,activities:this.activities||K,data:this.data,order:this.order||-1}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"config",{get:function(){var t=this._config;t.parent;return function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&(n[r[i]]=t[r[i]])}return n}(t,["parent"])},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"on",{get:function(){return this.formatTransitions()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"after",{get:function(){var t=this,e=this.config.after;if(!e)return K;if(Array.isArray(e))return e.map(function(e){return m({event:L(e.delay,t.id)},e,{actions:l(e.actions)})});var n=v(Object.keys(e).map(function(n){var r=e[n],i=+n,a=L(i,t.id);return"string"==typeof r?[{target:r,delay:i,event:a,actions:[]}]:l(r).map(function(t){return m({event:a,delay:i},t,{actions:l(t.actions)})})}));return n.sort(function(t,e){return t.delay-e.delay}),n},enumerable:!0,configurable:!0}),e.prototype.getStateNodes=function(t){var e,n=this;if(!t)return[];var i=t instanceof r?t.value:o(t,this.delimiter);if("string"==typeof i){var a=this.getStateNode(i).initial;return a?this.getStateNodes(((e={})[i]=a,e)):[this.states[i]]}var s=Object.keys(i);return s.map(function(t){return n.getStateNode(t)}).concat(s.reduce(function(t,e){var r=n.getStateNode(e).getStateNodes(i[e]);return t.concat(r)},[]))},e.prototype.handles=function(t){var e=i(t);return-1!==this.events.indexOf(e)},e.prototype.transitionLeafNode=function(t,e,n,r){var i=this.getStateNode(t),a=i.next(e,n,r);if(!a.value){var o=this.next(e,n,r),s=o.value,u=o.entryExitStates,c=o.actions,f=o.paths;return{value:s,source:e,entryExitStates:{entry:u?u.entry:new Set,exit:new Set([i].concat(u?Array.from(u.exit):[]))},actions:c,paths:f}}return a},e.prototype.transitionNestedNode=function(t,e,n,r){var i=Object.keys(t),a=this.getStateNode(i[0]),o=a._transition(t[i[0]],e,n,r);if(!o.value){var s=this.next(e,n,r),u=s.value,c=s.entryExitStates,f=s.actions,h=s.paths;return{value:u,source:e,entryExitStates:{entry:c?c.entry:new Set,exit:new Set((o.entryExitStates?Array.from(o.entryExitStates.exit):[]).concat([a],c?Array.from(c.exit):[]))},actions:f,paths:h}}return o},e.prototype.transitionParallelNode=function(t,e,n,r){var i=this,a={};if(Object.keys(t).forEach(function(o){var s=t[o];if(s){var u=i.getStateNode(o)._transition(s,e,n,r);u.value,a[o]=u}}),!Object.keys(a).some(function(t){return void 0!==a[t].value})){var o=this.next(e,n,r),u=o.value,c=o.entryExitStates,h=o.actions,l=o.paths;return{value:u,source:e,entryExitStates:{entry:c?c.entry:new Set,exit:new Set(Object.keys(this.states).map(function(t){return i.states[t]}).concat(c?Array.from(c.exit):[]))},actions:h,paths:l}}var g=v(Object.keys(a).map(function(t){return a[t].paths}));if(1===g.length&&!d(s(this.path),s(g[0])))return{value:this.machine.resolve(y(g)),source:e,entryExitStates:Object.keys(a).map(function(t){return a[t].entryExitStates}).reduce(function(t,e){var n=e,r=n.entry,i=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(r))),exit:new Set(Array.from(t.exit).concat(Array.from(i)))}},{entry:new Set,exit:new Set}),actions:v(Object.keys(a).map(function(t){return a[t].actions})),paths:g};var m=v(Object.keys(a).map(function(t){var n=a[t].value||e.value;return p(f(i.path)(n)[t]).map(function(e){return i.path.concat(t,e)})})),S=this.machine.resolve(y(m));return{value:S,source:e,entryExitStates:Object.keys(a).reduce(function(t,e){var n=a[e],r=n.value,i=n.entryExitStates;if(!r||!i)return t;var o=i.entry,s=i.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(o))),exit:new Set(Array.from(t.exit).concat(Array.from(s)))}},{entry:new Set,exit:new Set}),actions:v(Object.keys(a).map(function(t){return a[t].actions})),paths:p(S)}},e.prototype._transition=function(t,e,n,r){return"string"==typeof t?this.transitionLeafNode(t,e,n,r):1===Object.keys(t).length?this.transitionNestedNode(t,e,n,r):this.transitionParallelNode(t,e,n,r)},e.prototype.next=function(t,e,n){var r=this,i=e.type,a=this.on[i],s=this.transient?[{type:O}]:[];if(!a||!a.length)return{value:void 0,source:t,entryExitStates:void 0,actions:s,paths:[]};for(var u,c=[],h=0,p=a;h<p.length;h++){var g=p[h],m=g,S=m.cond,b=m.in,x=n||J,j=!b||d(o(b,this.delimiter),f(this.path.slice(0,-2))(t.value));if((!S||this.evaluateCond(S,x,e,t.value))&&j){c=l(g.target),s.push.apply(s,l(g.actions)),u=g;break}}if(u&&0===c.length)return{value:t.value,source:t,entryExitStates:void 0,actions:s,paths:[]};if(!u&&0===c.length)return{value:void 0,source:t,entryExitStates:void 0,actions:s,paths:[]};var A=v(c.map(function(e){return r.getRelativeStateNodes(e,t.historyValue)})),E=A.map(function(t){return t.path}),w=A.reduce(function(t,e){var n=r.getEntryExitStates(e,!!u.internal),i=n.entry,a=n.exit;return{entry:new Set(Array.from(t.entry).concat(Array.from(i))),exit:new Set(Array.from(t.exit).concat(Array.from(a)))}},{entry:new Set,exit:new Set});return{value:this.machine.resolve(y(v(c.map(function(e){return r.getRelativeStateNodes(e,t.historyValue).map(function(t){return t.path})})))),source:t,entryExitStates:w,actions:s,paths:E}},e.prototype.getStateNodeValueTree=function(t){var e,n=this;return"string"==typeof t?{stateNode:this,value:(e={},e[t]={stateNode:this.getStateNode(t),value:void 0},e)}:{stateNode:this,value:u(t,function(t,e){return n.getStateNode(e).getStateNodeValueTree(t)})}},e.prototype.getEntryExitStates=function(t,e){for(var n={entry:[],exit:[]},r=this.path,i=t.path,a=this.machine,o=0;o<Math.min(r.length,i.length);o++){var s=r[o];if(s!==i[o])break;a=a.getStateNode(s)}for(var u=a.path,c=a,f=0,h=r.slice(u.length);f<h.length;f++){var p=h[f];c=c.getStateNode(p),n.exit.unshift(c)}a===this&&(e||(n.exit.push(this),n.entry.push(this))),c=a;for(var y=0,v=i.slice(u.length);y<v.length;y++){p=v[y];c=c.getStateNode(p),n.entry.push(c)}return{entry:new Set(n.entry),exit:new Set(n.exit)}},e.prototype.evaluateCond=function(t,e,n,r){var i,a=this.machine.options.guards;if("string"==typeof t){if(!a||!a[t])throw new Error("Condition '"+t+"' is not implemented on machine '"+this.machine.id+"'.");i=a[t]}else i=t;return i(e,n,r)},Object.defineProperty(e.prototype,"delays",{get:function(){var t=this;return Array.from(new Set(this.after.map(function(t){return t.delay}))).map(function(e){return{id:t.id,delay:e}})},enumerable:!0,configurable:!0}),e.prototype.getActions=function(t){var e=this,n=new Set,r={entry:t.entryExitStates?v(Array.from(t.entryExitStates.entry).map(function(r){if("final"===r.type){var i=e.getStateNodeValueTree(t.value);n.add(z(r.id));var a=r.parent?r.parent.parent:void 0;if(a){var o=h(a.path,"value")(i);Object.keys(o.value).every(function(t){return Object.keys(o.value[t].value).every(function(e){return"final"===o.value[t].value[e].stateNode.type})})&&n.add(z(o.stateNode.id))}}return r.onEntry.concat(r.activities.map(function(t){return H(t)}),r.delays.map(function(t){var e=t.delay;return F(L(e,t.id),{delay:e})}))})).concat(Array.from(n).map(C)):[],exit:t.entryExitStates?v(Array.from(t.entryExitStates.exit).map(function(t){return t.onExit.concat(t.activities.map(function(t){return D(t)}),t.delays.map(function(t){var e=t.delay,n=t.id;return B(L(e,n))}))})):[]};return r.exit.concat(t.actions).concat(r.entry).map(function(t){return"string"==typeof t?e.resolveAction(t):t})},e.prototype.resolveAction=function(t){var e=this.machine.options.actions;return(e?e[t]:t)||t},e.prototype.resolveActivity=function(t){var e=this.machine.options.activities;return"string"==typeof t?M(e?m({type:t},e[t]):t):t},e.prototype.getActivities=function(t,e){if(!t)return J;var n=m({},e);return Array.from(t.exit).forEach(function(t){t.activities&&t.activities.forEach(function(t){n[t.type]=!1})}),Array.from(t.entry).forEach(function(t){t.activities&&t.activities.forEach(function(t){n[t.type]=!0})}),n},e.prototype.transition=function(t,e,n){var i="string"==typeof t?this.resolve(s(this.getResolvedPath(t))):t instanceof r?t:this.resolve(t),a=n||(t instanceof r?t.context:void 0),o=V(e),u=o.type;if(this.strict&&-1===this.events.indexOf(u))throw new Error("Machine '"+this.id+"' does not accept event '"+u+"'");var c=r.from(i,a),f=this._transition(c.value,c,o,a);return this.resolveTransition(f,c,o)},e.prototype.resolveTransition=function(n,i,a){var o,s=i.historyValue?i.historyValue:n.source?this.machine.historyValue(i.value):void 0,u=this.getActions(n),c=this.getActivities(n.entryExitStates,i.activities),f=u.filter(function(t){return"object"==typeof t&&(t.type===x||t.type===O)}),h=u.filter(function(t){return"object"!=typeof t||t.type!==x&&t.type!==O&&t.type!==E}),p=u.filter(function(t){return"object"==typeof t&&t.type===E}),y=i.context?p.reduce(function(e,n){var r=n.assignment,i={};return"function"==typeof r?i=r(e,a||{type:t.ActionTypes.Init}):Object.keys(r).forEach(function(t){var n=r[t];i[t]="function"==typeof n?n(e,a):n}),Object.assign({},e,i)},i.context):i.context,v=n.value?this.getStateNodes(n.value):[];v.some(function(t){return t.transient})&&f.push({type:O});var l=[this].concat(v).reduce(function(t,e){return void 0!==e.data&&(t[e.id]=e.data),t},{}),d=n.value?new r(n.value,y,s?e.updateHistoryValue(s,n.value):void 0,n.source?i:void 0,I(h,this.options.actions),c,l,f):void 0;if(!d)return r.inert(i,y);i.history&&delete i.history.history;for(var g=d;f.length;){var m=g.actions,S=f.shift();(o=(g=this.transition(g,S.type===O?G:S.event,g.context)).actions).unshift.apply(o,m)}return g},e.prototype.ensureValidPaths=function(t){var e=this,n=new Map;t:for(var r=0,i=v(t.map(function(t){return e.getRelativeStateNodes(t)}));r<i.length;r++)for(var a=i[r],o=a;o.parent;){if(n.has(o.parent)){if("parallel"===o.parent.type)continue t;throw new Error("State node '"+a.id+"' shares parent '"+o.parent.id+"' with state node '"+n.get(o.parent).map(function(t){return t.id})+"'")}n.get(o.parent)?n.get(o.parent).push(a):n.set(o.parent,[a]),o=o.parent}},e.prototype.getStateNode=function(t){if(Q(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.");var e=this.states[t];if(!e)throw new Error("Child state '"+t+"' does not exist on '"+this.id+"'");return e},e.prototype.getStateNodeById=function(t){var e=Q(t)?t.slice("#".length):t;if(e===this.id)return this;var n=this.machine.idMap[e];if(!n)throw new Error("Substate '#"+e+"' does not exist on '"+this.id+"'");return n},e.prototype.getStateNodeByPath=function(t){for(var e=a(t,this.delimiter),n=this;e.length;){var r=e.shift();n=n.getStateNode(r)}return n},e.prototype.resolve=function(t){var e,n=this;if("string"==typeof t){var r=this.getStateNode(t);return r.initial?((e={})[t]=r.initialStateValue,e):t}return"parallel"===this.type?u(this.initialStateValue,function(e,r){return e?n.getStateNode(r).resolve(t[r]||e):J}):u(t,function(t,e){return t?n.getStateNode(e).resolve(t):J})},Object.defineProperty(e.prototype,"resolvedStateValue",{get:function(){var t,e,n=this.key;return"parallel"===this.type?((t={})[n]=c(this.states,function(t){return t.resolvedStateValue[t.key]},function(t){return!t.history}),t):this.initial?((e={})[n]=this.states[this.initial].resolvedStateValue,e):n},enumerable:!0,configurable:!0}),e.prototype.getResolvedPath=function(t){if(Q(t)){var e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error("Unable to find state node '"+t+"'");return e.path}return a(t,this.delimiter)},Object.defineProperty(e.prototype,"initialStateValue",{get:function(){if(this.__cache.initialState)return this.__cache.initialState;var t="parallel"===this.type?c(this.states,function(t){return t.initialStateValue||J},function(t){return!t.history}):"string"==typeof this.resolvedStateValue?void 0:this.resolvedStateValue[this.key];return this.__cache.initialState=t,this.__cache.initialState},enumerable:!0,configurable:!0}),e.prototype.getState=function(t,e){var n=this;void 0===e&&(e=this.machine.context);var a={},o=[];this.getStateNodes(t).forEach(function(t){t.onEntry&&o.push.apply(o,t.onEntry),t.activities&&t.activities.forEach(function(t){a[i(t)]=!0,o.push(H(t))})});var s=o.filter(function(t){return"object"==typeof t&&(t.type===x||t.type===O)}),u=o.filter(function(t){return"object"==typeof t&&t.type===E}),c=e?u.reduce(function(t,e){var n=e.assignment,r={};return"function"==typeof n?r=n(t,{type:"init"}):Object.keys(n).forEach(function(e){var i=n[e];r[e]="function"==typeof i?i(t,{type:"init"}):i}),Object.assign({},t,r)},e):e,f=new r(t,c,void 0,void 0,I(o,this.options.actions),a,void 0,[]);return s.reduce(function(t,e){var r,i=t.actions;return(r=(t=n.transition(t,e.type===O?G:e.event,t.context)).actions).unshift.apply(r,i),t},f)},Object.defineProperty(e.prototype,"initialState",{get:function(){var t=this.initialStateValue;if(!t)throw new Error("Cannot retrieve initial state from simple state '"+this.id+"'.");var e=this.getState(t);return this.resolveTransition({value:e.value,source:void 0,entryExitStates:{entry:new Set(this.getStateNodes(e.value)),exit:new Set},actions:[],paths:[]},e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){var t;if(this.history){var e=this.config;t=e.target&&"string"==typeof e.target&&Q(e.target)?s(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t},enumerable:!0,configurable:!0}),e.prototype.getStates=function(t){var e=this;if("string"==typeof t)return[this.states[t]];var n=[];return Object.keys(t).forEach(function(r){n.push.apply(n,e.states[r].getStates(t[r]))}),n},e.prototype.getRelativeStateNodes=function(t,e,n){if(void 0===n&&(n=!0),"string"==typeof t&&Q(t)){var r=this.getStateNodeById(t);return n?r.history?r.resolveHistory(e):r.initialStateNodes:[r]}var i=a(t,this.delimiter),o=(this.parent||this).getFromRelativePath(i,e);return n?v(o.map(function(t){return t.initialStateNodes})):o},Object.defineProperty(e.prototype,"initialStateNodes",{get:function(){var t=this;if("atomic"===this.type||"final"===this.type)return[this];var e=this.initialStateValue;return v(p(e).map(function(e){return t.getFromRelativePath(e)}))},enumerable:!0,configurable:!0}),e.prototype.getFromRelativePath=function(t,e){if(!t.length)return[this];var n=t[0],r=t.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '"+n+"' from node with no states");var i=this.getStateNode(n);if(i.history)return i.resolveHistory(e);if(!this.states[n])throw new Error("Child state '"+n+"' does not exist on '"+this.id+"'");return this.states[n].getFromRelativePath(r,e)},e.updateHistoryValue=function(t,e){return{current:e,states:function t(e,n){return u(e.states,function(e,r){if(e){var i=("string"==typeof n?void 0:n[r])||(e?e.current:void 0);if(i)return{current:i,states:t(e,i)}}})}(t,e)}},e.prototype.historyValue=function(t){if(Object.keys(this.states).length)return{current:t||this.initialStateValue,states:c(this.states,function(e,n){if(!t)return e.historyValue();var r="string"==typeof t?void 0:t[n];return e.historyValue(r||e.initialStateValue)},function(t){return!t.history})}},e.prototype.resolveHistory=function(t){var e=this;if(!this.history)return[this];var n=this.parent;if(!t)return this.target?v(p(this.target).map(function(t){return n.getFromRelativePath(t)})):this.parent.initialStateNodes;var r=h(n.path,"states")(t).current;return"string"==typeof r?[n.getStateNode(r)]:v(p(r).map(function(t){return"deep"===e.history?n.getFromRelativePath(t):[n.states[t[0]]]}))},Object.defineProperty(e.prototype,"stateIds",{get:function(){var t=this,e=v(Object.keys(this.states).map(function(e){return t.states[e].stateIds}));return[this.id].concat(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"events",{get:function(){if(this.__cache.events)return this.__cache.events;var t=this.states,e=new Set(Object.keys(this.on));return t&&Object.keys(t).forEach(function(n){var r=t[n];if(r.states)for(var i=0,a=r.events;i<a.length;i++){var o=a[i];e.add(""+o)}}),this.__cache.events=Array.from(e)},enumerable:!0,configurable:!0}),e.prototype.formatTransition=function(t,e,n){var r=this,i=!!e&&e.internal;if(void 0===t||""===t)return m({},e,{actions:e?l(e.actions):[],target:void 0,internal:!e||(void 0===e.internal||e.internal),event:n});var a=l(t).map(function(t){var e="string"==typeof t&&t[0]===r.delimiter;return i=i||e,e&&!r.parent?t.slice(1):e?r.key+t:t});return m({},e,{actions:e?l(e.actions):[],target:a,internal:i,event:n})},e.prototype.formatTransitions=function(){var t=this,e=this.config.on||J,n=this.after,r=u(e,function(e,n){return void 0===e?[{target:void 0,event:n,actions:[]}]:Array.isArray(e)?e.map(function(e){return t.formatTransition(e.target,e,n)}):"string"==typeof e?[t.formatTransition([e],void 0,n)]:[t.formatTransition(e.target,e,n)]});return n.forEach(function(t){r[t.event]=r[t.event]||[],r[t.event].push(t)}),r},e}();t.Machine=function(t,e,n){return new X(t,e,n)},t.StateNode=X,t.State=r,t.matchesState=d,t.mapState=function(t,e){var n;return Object.keys(t).forEach(function(t){d(t,e)&&(!n||e.length>n.length)&&(n=t)}),t[n]},t.actions=U,Object.defineProperty(t,"__esModule",{value:!0})}); |
import { Action, Event, EventObject, SendAction, SendActionOptions, CancelAction, ActionObject, Assigner, AssignAction, ActionFunction, ActivityActionObject, ActionTypes, ActivityDefinition } from './types'; | ||
import * as actionTypes from './actionTypes'; | ||
export { actionTypes }; | ||
export declare const toEventObject: (event: Event, id?: string | number | undefined) => EventObject; | ||
export declare function toEventObject<TEvents extends EventObject>(event: Event<TEvents>): TEvents; | ||
export declare const toActionObject: <TContext>(action: Action<TContext>, actionFunctionMap?: Record<string, ActionObject<TContext> | ActionFunction<TContext>> | undefined) => ActionObject<TContext>; | ||
export declare function toActivityDefinition<TContext>(action: string | ActionObject<TContext> | ActivityDefinition<TContext>): ActivityDefinition<TContext>; | ||
export declare const toActionObjects: <TContext>(action: Action<TContext>[] | undefined, actionFunctionMap?: Record<string, ActionObject<TContext> | ActionFunction<TContext>> | undefined) => ActionObject<TContext>[]; | ||
export declare const raise: (eventType: string | number) => EventObject; | ||
export declare const send: (event: Event, options?: SendActionOptions | undefined) => SendAction; | ||
export declare function log<TContext>(expr: (ctx: TContext, event: EventObject) => void, label?: string): { | ||
interface RaiseEvent<TContext, TEvents extends EventObject> extends ActionObject<TContext> { | ||
event: TEvents['type']; | ||
} | ||
export declare function raise<TContext, TEvents extends EventObject>(eventType: TEvents['type']): RaiseEvent<TContext, TEvents>; | ||
export declare function send<TContext, TEvents extends EventObject>(event: Event<TEvents>, options?: SendActionOptions): SendAction<TContext, TEvents>; | ||
export declare function log<TContext, TEvents extends EventObject>(expr: (ctx: TContext, event: TEvents) => void, label?: string): { | ||
type: ActionTypes; | ||
label: string | undefined; | ||
expr: (ctx: TContext, event: EventObject) => void; | ||
expr: (ctx: TContext, event: TEvents) => void; | ||
}; | ||
@@ -18,5 +21,5 @@ export declare const cancel: (sendId: string | number) => CancelAction; | ||
export declare function stop<TContext>(activity: string | ActionObject<TContext> | ActivityDefinition<TContext>): ActivityActionObject<TContext>; | ||
export declare const assign: <TContext>(assignment: Assigner<TContext> | Partial<{ [K in keyof TContext]: ((extState: TContext, event: EventObject) => TContext[K]) | TContext[K]; }>) => AssignAction<TContext>; | ||
export declare const assign: <TContext, TEvents extends EventObject = EventObject>(assignment: Assigner<TContext, TEvents> | Partial<{ [K in keyof TContext]: ((extState: TContext, event: TEvents) => TContext[K]) | TContext[K]; }>) => AssignAction<TContext, TEvents>; | ||
export declare function isActionObject<TContext>(action: Action<TContext>): action is ActionObject<TContext>; | ||
export declare function after(delay: number, id?: string): string; | ||
export declare function done(id: string): string; |
@@ -15,12 +15,14 @@ var __assign = this && this.__assign || function () { | ||
export { actionTypes }; | ||
export var toEventObject = function (event, id) { | ||
export function toEventObject(event | ||
// id?: TEvents['type'] | ||
) { | ||
if (typeof event === 'string' || typeof event === 'number') { | ||
var eventObject = { type: event }; | ||
if (id !== undefined) { | ||
eventObject.id = id; | ||
} | ||
// if (id !== undefined) { | ||
// eventObject.id = id; | ||
// } | ||
return eventObject; | ||
} | ||
return event; | ||
}; | ||
} | ||
function getActionFunction(actionType, actionFunctionMap) { | ||
@@ -76,3 +78,3 @@ if (!actionFunctionMap) { | ||
}; | ||
export var raise = function (eventType) { | ||
export function raise(eventType) { | ||
return { | ||
@@ -82,4 +84,4 @@ type: actionTypes.raise, | ||
}; | ||
}; | ||
export var send = function (event, options) { | ||
} | ||
export function send(event, options) { | ||
return { | ||
@@ -91,3 +93,3 @@ type: actionTypes.send, | ||
}; | ||
}; | ||
} | ||
export function log(expr, label) { | ||
@@ -94,0 +96,0 @@ return { |
@@ -13,1 +13,2 @@ import { ActionTypes } from './types'; | ||
export declare const log: ActionTypes; | ||
export declare const init: ActionTypes; |
@@ -13,2 +13,3 @@ import { ActionTypes } from './types'; | ||
export var doneState = ActionTypes.DoneState; | ||
export var log = ActionTypes.Log; | ||
export var log = ActionTypes.Log; | ||
export var init = ActionTypes.Init; |
import { StateNode, State } from './index'; | ||
import { StateValue, Edge, PathMap, PathItem, PathsItem, PathsMap, AdjacencyMap, DefaultContext, ValueAdjacencyMap, Event } from './types'; | ||
import { StateValue, Edge, PathMap, PathItem, PathsItem, PathsMap, AdjacencyMap, DefaultContext, ValueAdjacencyMap, Event, EventObject } from './types'; | ||
export declare function getNodes(node: StateNode): StateNode[]; | ||
export declare function getEventEdges<TContext = DefaultContext>(node: StateNode<TContext>, event: string): Array<Edge<TContext>>; | ||
export declare function getEdges<TContext = DefaultContext>(node: StateNode<TContext>, options?: { | ||
export declare function getEventEdges<TContext = DefaultContext, TEvents extends EventObject = EventObject>(node: StateNode<TContext>, event: string): Array<Edge<TContext, TEvents>>; | ||
export declare function getEdges<TContext = DefaultContext, TEvents extends EventObject = EventObject>(node: StateNode<TContext>, options?: { | ||
depth: null | number; | ||
}): Array<Edge<TContext>>; | ||
}): Array<Edge<TContext, TEvents>>; | ||
export declare function getAdjacencyMap<TContext = DefaultContext>(node: StateNode<TContext>, context?: TContext): AdjacencyMap; | ||
@@ -13,8 +13,10 @@ export declare function deserializeStateString(valueContextString: string): { | ||
}; | ||
export interface GetValueAdjacencyMapOptions<TContext> { | ||
events: Record<string, Event[]>; | ||
export interface GetValueAdjacencyMapOptions<TContext, TEvents extends EventObject> { | ||
events: { | ||
[K in TEvents['type']]: Event<TEvents>; | ||
}; | ||
filter?: (state: State<TContext>) => boolean; | ||
} | ||
export declare function getValueAdjacencyMap<TContext = DefaultContext>(node: StateNode<TContext>, options: GetValueAdjacencyMapOptions<TContext>): ValueAdjacencyMap; | ||
export declare function getShortestValuePaths<TContext = DefaultContext>(machine: StateNode<TContext>, options: GetValueAdjacencyMapOptions<TContext>): PathMap; | ||
export declare function getValueAdjacencyMap<TContext = DefaultContext, TEvents extends EventObject = EventObject>(node: StateNode<TContext, any, TEvents>, options: GetValueAdjacencyMapOptions<TContext, TEvents>): ValueAdjacencyMap; | ||
export declare function getShortestValuePaths<TContext = DefaultContext, TEvents extends EventObject = EventObject>(machine: StateNode<TContext>, options: GetValueAdjacencyMapOptions<TContext, TEvents>): PathMap; | ||
export declare function getShortestPaths<TContext = DefaultContext>(machine: StateNode<TContext>, context?: TContext): PathMap; | ||
@@ -21,0 +23,0 @@ export declare function getShortestPathsAsArray<TContext = DefaultContext>(machine: StateNode<TContext>, context?: TContext): PathItem[]; |
@@ -96,2 +96,3 @@ var __rest = this && this.__rest || function (s, e) { | ||
} | ||
// @ts-ignore - TODO: fix? | ||
var type = event.type, | ||
@@ -119,3 +120,5 @@ rest = __rest(event, ["type"]); | ||
var adjacency = {}; | ||
var potentialEvents = flatten(node.events.map(function (event) { | ||
var potentialEvents = flatten( | ||
// @ts-ignore | ||
node.events.map(function (event) { | ||
return events[event] || [event]; | ||
@@ -122,0 +125,0 @@ })); |
@@ -1,2 +0,2 @@ | ||
import { Machine, Event, EventObject, DefaultContext } from './types'; | ||
import { Machine, Event, EventObject, DefaultContext, StateSchema } from './types'; | ||
import { State } from './State'; | ||
@@ -28,8 +28,8 @@ export declare type StateListener = <TContext = DefaultContext>(state: State<TContext>) => void; | ||
} | ||
export declare class Interpreter<TContext> { | ||
machine: Machine<TContext>; | ||
export declare class Interpreter<TContext, TStateSchema extends StateSchema = any, TEvents extends EventObject = EventObject> { | ||
machine: Machine<TContext, TStateSchema, TEvents>; | ||
static defaultOptions: InterpreterOptions; | ||
state: State<TContext>; | ||
state: State<TContext, TEvents>; | ||
extState: TContext; | ||
eventQueue: EventObject[]; | ||
eventQueue: TEvents[]; | ||
delayedEventsMap: Record<string, number>; | ||
@@ -41,3 +41,3 @@ listeners: Set<StateListener>; | ||
initialized: boolean; | ||
constructor(machine: Machine<TContext>, listener?: StateListener, options?: Partial<InterpreterOptions>); | ||
constructor(machine: Machine<TContext, TStateSchema, TEvents>, listener?: StateListener, options?: Partial<InterpreterOptions>); | ||
static interpret: typeof interpret; | ||
@@ -56,6 +56,6 @@ private update; | ||
off(listener: StateListener): Interpreter<TContext>; | ||
init: (initialState?: State<TContext>) => Interpreter<TContext>; | ||
start(initialState?: State<TContext>): Interpreter<TContext>; | ||
init: (initialState?: State<TContext, TEvents>) => Interpreter<TContext, any, EventObject>; | ||
start(initialState?: State<TContext, TEvents>): Interpreter<TContext>; | ||
stop(): Interpreter<TContext>; | ||
send: (event: Event) => State<TContext>; | ||
send: (event: Event<TEvents>) => State<TContext, TEvents>; | ||
private defer; | ||
@@ -66,3 +66,3 @@ private cancel; | ||
} | ||
export declare function interpret<TContext = DefaultContext>(machine: Machine<TContext>, listener?: StateListener, options?: Partial<InterpreterOptions>): Interpreter<TContext>; | ||
export declare function interpret<TContext = DefaultContext, TStateSchema extends StateSchema = any, TEvents extends EventObject = EventObject>(machine: Machine<TContext, TStateSchema, TEvents>, listener?: StateListener, options?: Partial<InterpreterOptions>): Interpreter<TContext, TStateSchema, TEvents>; | ||
export {}; |
@@ -79,3 +79,3 @@ var __assign = this && this.__assign || function () { | ||
} | ||
var nextState = _this.machine.transition(_this.state, eventObject, _this.extState); | ||
var nextState = _this.machine.transition(_this.state, eventObject, _this.extState); // TODO: fixme | ||
_this.update(nextState, event); | ||
@@ -186,6 +186,8 @@ _this.flushEventQueue(); | ||
Interpreter.prototype.flushEventQueue = function () { | ||
if (this.eventQueue.length) { | ||
this.send(this.eventQueue.unshift()); | ||
var flushedEvent = this.eventQueue.shift(); | ||
if (flushedEvent) { | ||
this.send(flushedEvent); | ||
} | ||
}; | ||
// TODO: fixme | ||
Interpreter.defaultOptions = { | ||
@@ -192,0 +194,0 @@ clock: { setTimeout: setTimeout, clearTimeout: clearTimeout }, |
@@ -1,2 +0,2 @@ | ||
import { Machine, MachineOptions, DefaultContext, MachineConfig } from './types'; | ||
export declare function Machine<TContext = DefaultContext>(config: MachineConfig<TContext>, options?: MachineOptions<TContext>, initialContext?: TContext): Machine<TContext>; | ||
import { Machine, MachineOptions, DefaultContext, MachineConfig, StateSchema, EventObject } from './types'; | ||
export declare function Machine<TContext = DefaultContext, TStateSchema extends StateSchema = any, TEvents extends EventObject = EventObject>(config: MachineConfig<TContext, TStateSchema, TEvents>, options?: MachineOptions<TContext, TEvents>, initialContext?: TContext): Machine<TContext, TStateSchema, TEvents>; |
import { SimpleStateNodeConfig } from './types'; | ||
export declare function toggle(onState: string, offState: string, eventType: string): Record<string, SimpleStateNodeConfig<any>>; | ||
export declare function toggle<TEventType extends string = string>(onState: string, offState: string, eventType: TEventType): Record<string, SimpleStateNodeConfig<any, { | ||
type: TEventType; | ||
}>>; |
@@ -266,4 +266,3 @@ var __assign = this && this.__assign || function () { | ||
}, {}) : undefined; | ||
// console.log(dataModelEl, extState); | ||
return Machine(__assign({}, toConfig(machineElement, '(machine)', options, extState), { delimiter: options.delimiter }), undefined, extState); | ||
} |
import { StateValue, ActivityMap, EventObject, StateInterface, HistoryValue, ActionObject } from './types'; | ||
export declare class State<TContext> implements StateInterface<TContext> { | ||
export declare class State<TContext, TEvents extends EventObject = EventObject> implements StateInterface<TContext> { | ||
value: StateValue; | ||
context: TContext; | ||
historyValue?: HistoryValue | undefined; | ||
history?: State<TContext> | undefined; | ||
history?: State<TContext, EventObject> | undefined; | ||
actions: Array<ActionObject<TContext>>; | ||
@@ -13,13 +13,13 @@ activities: ActivityMap; | ||
*/ | ||
events: EventObject[]; | ||
static from<T>(stateValue: State<T> | StateValue, context: T): State<T>; | ||
static inert<T>(stateValue: State<T> | StateValue, ext: T): State<T>; | ||
constructor(value: StateValue, context: TContext, historyValue?: HistoryValue | undefined, history?: State<TContext> | undefined, actions?: Array<ActionObject<TContext>>, activities?: ActivityMap, data?: Record<string, any>, | ||
events: TEvents[]; | ||
static from<TC, TE extends EventObject = EventObject>(stateValue: State<TC, TE> | StateValue, context: TC): State<TC, TE>; | ||
static inert<TC, TE extends EventObject = EventObject>(stateValue: State<TC> | StateValue, ext: TC): State<TC, TE>; | ||
constructor(value: StateValue, context: TContext, historyValue?: HistoryValue | undefined, history?: State<TContext, EventObject> | undefined, actions?: Array<ActionObject<TContext>>, activities?: ActivityMap, data?: Record<string, any>, | ||
/** | ||
* Internal event queue | ||
*/ | ||
events?: EventObject[]); | ||
events?: TEvents[]); | ||
toStrings(value?: StateValue): string[]; | ||
matches(parentStateValue: StateValue): boolean; | ||
readonly changed: boolean; | ||
readonly changed: boolean | undefined; | ||
} |
@@ -70,5 +70,5 @@ import { EMPTY_ACTIVITY_MAP } from './constants'; | ||
if (!this.history) { | ||
return false; | ||
return undefined; | ||
} | ||
return !!this.actions.length || (typeof this.history.value !== this.value ? true : typeof this.value === 'string' ? this.value !== this.history.value : stateValuesEqual(this.value, this.history.value)); | ||
return !!this.actions.length || (typeof this.history.value !== typeof this.value ? true : typeof this.value === 'string' ? this.value !== this.history.value : stateValuesEqual(this.value, this.history.value)); | ||
}, | ||
@@ -75,0 +75,0 @@ enumerable: true, |
@@ -1,6 +0,6 @@ | ||
import { Event, StateValue, Action, EventType, StateTransition, MachineOptions, EventObject, HistoryValue, DefaultData, DefaultContext, StateNodeDefinition, TransitionDefinition, DelayedTransitionDefinition, ActivityDefinition, Delay, StateTypes, StateNodeConfig } from './types'; | ||
import { Event, StateValue, Action, StateTransition, MachineOptions, EventObject, HistoryValue, DefaultContext, StateNodeDefinition, DelayedTransitionDefinition, ActivityDefinition, Delay, StateTypes, StateNodeConfig, StateSchema, TransitionsDefinition, StateNodesConfig, AnyEvent } from './types'; | ||
import { State } from './State'; | ||
declare class StateNode<TContext = DefaultContext, TData = DefaultData> { | ||
declare class StateNode<TContext = DefaultContext, TStateSchema extends StateSchema = any, TEvents extends AnyEvent<EventObject> = AnyEvent<EventObject>> { | ||
private _config; | ||
options: Readonly<MachineOptions<TContext>>; | ||
options: Readonly<MachineOptions<TContext, TEvents>>; | ||
/** | ||
@@ -14,6 +14,6 @@ * The initial extended state | ||
path: string[]; | ||
initial?: string; | ||
initial?: keyof TStateSchema['states']; | ||
parallel: boolean; | ||
transient: boolean; | ||
states: Record<string, StateNode<TContext>>; | ||
states: StateNodesConfig<TContext, TStateSchema, TEvents>; | ||
history: false | 'shallow' | 'deep'; | ||
@@ -26,3 +26,5 @@ onEntry: Array<Action<TContext>>; | ||
machine: StateNode<TContext>; | ||
data: TData; | ||
data?: TStateSchema extends { | ||
data: infer D; | ||
} ? D : any; | ||
delimiter: string; | ||
@@ -32,3 +34,3 @@ order: number; | ||
private idMap; | ||
constructor(_config: StateNodeConfig<TContext>, options?: Readonly<MachineOptions<TContext>>, | ||
constructor(_config: StateNodeConfig<TContext, TStateSchema, TEvents>, options?: Readonly<MachineOptions<TContext, TEvents>>, | ||
/** | ||
@@ -38,12 +40,12 @@ * The initial extended state | ||
context?: Readonly<TContext> | undefined); | ||
readonly definition: StateNodeDefinition<TContext, TData>; | ||
readonly config: StateNodeConfig<TContext>; | ||
readonly on: Record<string, Array<TransitionDefinition<TContext>>>; | ||
readonly after: Array<DelayedTransitionDefinition<TContext>>; | ||
getStateNodes(state: StateValue | State<TContext>): Array<StateNode<TContext>>; | ||
handles(event: Event): boolean; | ||
readonly definition: StateNodeDefinition<TContext, TStateSchema, TEvents>; | ||
readonly config: StateNodeConfig<TContext, TStateSchema, TEvents>; | ||
readonly on: TransitionsDefinition<TContext, TEvents>; | ||
readonly after: Array<DelayedTransitionDefinition<TContext, TEvents>>; | ||
getStateNodes(state: StateValue | State<TContext, TEvents>): Array<StateNode<TContext>>; | ||
handles(event: Event<TEvents>): boolean; | ||
private transitionLeafNode; | ||
private transitionNestedNode; | ||
private transitionParallelNode; | ||
_transition(stateValue: StateValue, state: State<TContext>, event: EventObject, context?: TContext): StateTransition<TContext>; | ||
_transition(stateValue: StateValue, state: State<TContext, TEvents>, event: TEvents, context?: TContext): StateTransition<TContext>; | ||
private next; | ||
@@ -58,3 +60,3 @@ private getStateNodeValueTree; | ||
private getActivities; | ||
transition(state: StateValue | State<TContext>, event: Event, context?: TContext): State<TContext>; | ||
transition(state: StateValue | State<TContext, TEvents>, event: Event<TEvents>, context?: TContext): State<TContext, TEvents>; | ||
private resolveTransition; | ||
@@ -69,4 +71,4 @@ private ensureValidPaths; | ||
private readonly initialStateValue; | ||
getState(stateValue: StateValue, context?: TContext): State<TContext>; | ||
readonly initialState: State<TContext>; | ||
getState(stateValue: StateValue, context?: TContext): State<TContext, TEvents>; | ||
readonly initialState: State<TContext, TEvents>; | ||
readonly target: StateValue | undefined; | ||
@@ -100,3 +102,3 @@ getStates(stateValue: StateValue): Array<StateNode<TContext>>; | ||
readonly stateIds: string[]; | ||
readonly events: EventType[]; | ||
readonly events: Array<TEvents['type']>; | ||
private formatTransition; | ||
@@ -103,0 +105,0 @@ private formatTransitions; |
@@ -18,2 +18,3 @@ var __assign = this && this.__assign || function () { | ||
import { getEventType, toStatePath, toStateValue, mapValues, path, toStatePaths, pathsToStateValue, pathToStateValue, flatten, mapFilterValues, nestedPath, toArray } from './utils'; | ||
import { ActionTypes } from './types'; | ||
import { matchesState } from './matchesState'; | ||
@@ -600,6 +601,8 @@ import { State } from './State'; | ||
var historyValue = currentState.historyValue ? currentState.historyValue : stateTransition.source ? this.machine.historyValue(currentState.value) : undefined; | ||
try { | ||
this.ensureValidPaths(stateTransition.paths); | ||
} catch (e) { | ||
throw new Error("Event '" + (event ? event.type : 'none') + "' leads to an invalid configuration: " + e.message); | ||
if (process.env.NODE_ENV !== 'production') { | ||
try { | ||
this.ensureValidPaths(stateTransition.paths); | ||
} catch (e) { | ||
throw new Error("Event '" + (event ? event.type : 'none') + "' leads to an invalid configuration: " + e.message); | ||
} | ||
} | ||
@@ -621,3 +624,3 @@ var actions = this.getActions(stateTransition); | ||
if (typeof assignment === 'function') { | ||
partialUpdate = assignment(acc, event || { type: 'xstate.init' }); | ||
partialUpdate = assignment(acc, event || { type: ActionTypes.Init }); | ||
} else { | ||
@@ -649,4 +652,6 @@ Object.keys(assignment).forEach(function (key) { | ||
} | ||
// Dispose of previous histories to prevent memory leaks | ||
delete currentState.history; | ||
// Dispose of penultimate histories to prevent memory leaks | ||
if (currentState.history) { | ||
delete currentState.history.history; | ||
} | ||
var maybeNextState = nextState; | ||
@@ -752,3 +757,5 @@ while (raisedEvents.length) { | ||
} | ||
return _b = {}, _b[key] = this.states[this.initial].resolvedStateValue, _b; | ||
return _b = {}, | ||
// @ts-ignore TODO: fixme | ||
_b[key] = this.states[this.initial].resolvedStateValue, _b; | ||
}, | ||
@@ -797,3 +804,3 @@ enumerable: true, | ||
stateNode.activities.forEach(function (activity) { | ||
activityMap[getEventType(activity)] = true; | ||
activityMap[getEventType(activity)] = true; // TODO: fixme | ||
actions.push(start(activity)); | ||
@@ -814,7 +821,8 @@ }); | ||
if (typeof assignment === 'function') { | ||
partialUpdate = assignment(acc, { type: 'init' }); | ||
partialUpdate = assignment(acc, { type: 'init' }); // TODO: fix init | ||
} else { | ||
Object.keys(assignment).forEach(function (key) { | ||
var propAssignment = assignment[key]; | ||
partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(acc, { type: 'init' }) : propAssignment; | ||
partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(acc, { type: 'init' }) // TODO: fix init | ||
: propAssignment; | ||
}); | ||
@@ -821,0 +829,0 @@ } |
import { StateNode } from './StateNode'; | ||
import { State } from './State'; | ||
export declare type EventType = string | number; | ||
export declare type ActionType = string | number; | ||
export declare type ActionType = string; | ||
export declare type MetaObject = Record<string, any>; | ||
export interface EventObject { | ||
type: EventType; | ||
export interface EventObject extends Record<string, any> { | ||
type: string | number; | ||
id?: string | number; | ||
[key: string]: any; | ||
} | ||
export interface ActionObject<TContext> extends Record<string, any> { | ||
type: ActionType; | ||
type: string; | ||
exec?: ActionFunction<TContext>; | ||
} | ||
export declare type DefaultContext = Record<string, any> | undefined; | ||
export declare type DefaultData = Record<string, any>; | ||
export declare type Event = EventType | EventObject; | ||
export declare type InternalEvent = EventType | EventObject; | ||
export declare type Event<TEvents extends EventObject> = TEvents['type'] | TEvents; | ||
export interface ActionFunction<TContext> { | ||
@@ -23,4 +20,3 @@ (context: TContext, event?: EventObject): any | void; | ||
} | ||
export declare type InternalAction<TContext> = SendAction | AssignAction<TContext>; | ||
export declare type Action<TContext> = ActionType | ActionObject<TContext> | InternalAction<TContext> | ActionFunction<TContext>; | ||
export declare type Action<TContext> = ActionType | ActionObject<TContext> | ActionFunction<TContext>; | ||
export declare type StateKey = string | State<any>; | ||
@@ -40,6 +36,6 @@ export interface StateValueMap { | ||
} | ||
export declare type ConditionPredicate<TContext> = (context: TContext, event: EventObject, microstepState: StateValue) => boolean; | ||
export declare type Condition<TContext> = string | ConditionPredicate<TContext>; | ||
export interface TransitionConfig<TContext = DefaultContext> { | ||
cond?: Condition<TContext>; | ||
export declare type ConditionPredicate<TContext, TEvents extends EventObject> = (context: TContext, event: TEvents, microstepState: StateValue) => boolean; | ||
export declare type Condition<TContext, TEvents extends EventObject> = string | ConditionPredicate<TContext, TEvents>; | ||
export interface TransitionConfig<TContext, TEvents extends EventObject> { | ||
cond?: Condition<TContext, TEvents>; | ||
actions?: SingleOrArray<Action<TContext>>; | ||
@@ -50,7 +46,7 @@ in?: StateValue; | ||
} | ||
export interface TargetTransitionConfig<TContext = DefaultContext> extends TransitionConfig<TContext> { | ||
export interface TargetTransitionConfig<TContext, TEvents extends EventObject> extends TransitionConfig<TContext, TEvents> { | ||
target: string | string[] | undefined; | ||
} | ||
export declare type ConditionalTransitionConfig<TContext = DefaultContext> = Array<TransitionConfig<TContext>>; | ||
export declare type Transition<TContext = DefaultContext> = string | TransitionConfig<TContext> | ConditionalTransitionConfig<TContext>; | ||
export declare type ConditionalTransitionConfig<TContext = DefaultContext, TEvents extends EventObject = EventObject> = Array<TransitionConfig<TContext, TEvents>>; | ||
export declare type Transition<TContext, TEvents extends EventObject = EventObject> = string | TransitionConfig<TContext, TEvents> | ConditionalTransitionConfig<TContext, TEvents>; | ||
export interface ActivityConfig<TContext> { | ||
@@ -62,3 +58,3 @@ start?: Action<TContext>; | ||
export interface ActivityDefinition<TContext> extends ActionObject<TContext> { | ||
type: ActionType; | ||
type: string; | ||
start?: ActionObject<TContext>; | ||
@@ -71,11 +67,32 @@ stop?: ActionObject<TContext>; | ||
} | ||
export interface DelayedTransitionConfig<TContext> extends TransitionConfig<TContext> { | ||
export interface DelayedTransitionConfig<TContext, TEvents extends EventObject> extends TransitionConfig<TContext, TEvents> { | ||
delay: number; | ||
} | ||
export declare type DelayedTransitions<TContext> = Record<string, string | TransitionConfig<TContext> | Array<TransitionConfig<TContext>>> | Array<DelayedTransitionConfig<TContext>>; | ||
export declare type DelayedTransitions<TContext, TEvents extends EventObject> = Record<string, string | TransitionConfig<TContext, TEvents> | Array<TransitionConfig<TContext, TEvents>>> | Array<DelayedTransitionConfig<TContext, TEvents>>; | ||
export declare type StateTypes = 'atomic' | 'compound' | 'parallel' | 'final' | 'history'; | ||
export declare type SingleOrArray<T> = T[] | T; | ||
export interface StateNodeConfig<TContext = DefaultContext, TData = any> { | ||
export declare type StateNodesConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = { | ||
[K in keyof TStateSchema['states']]: StateNode<TContext, TStateSchema['states'][K], TEvents>; | ||
}; | ||
export declare type StatesConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = { | ||
[K in keyof TStateSchema['states']]: StateNodeConfig<TContext, TStateSchema['states'][K], TEvents>; | ||
}; | ||
export declare type StatesDefinition<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = { | ||
[K in keyof TStateSchema['states']]: StateNodeDefinition<TContext, TStateSchema['states'][K], TEvents>; | ||
}; | ||
export declare type TransitionsConfig<TContext, TEvents extends EventObject> = { | ||
[K in TEvents['type'] | BuiltInEvent<TEvents>['type']]?: string | TransitionConfig<TContext, TEvents extends { | ||
type: K; | ||
} ? TEvents : EventObject> | Array<TransitionConfig<TContext, TEvents extends { | ||
type: K; | ||
} ? TEvents : EventObject>>; | ||
}; | ||
export declare type TransitionsDefinition<TContext, TEvents extends EventObject> = { | ||
[K in TEvents['type']]: Array<TransitionDefinition<TContext, TEvents extends { | ||
type: K; | ||
} ? TEvents : EventObject>>; | ||
}; | ||
export interface StateNodeConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> { | ||
key?: string; | ||
initial?: string | undefined; | ||
initial?: keyof TStateSchema['states'] | undefined; | ||
parallel?: boolean | undefined; | ||
@@ -89,11 +106,13 @@ type?: StateTypes; | ||
history?: 'shallow' | 'deep' | boolean | undefined; | ||
states?: Record<string, StateNodeConfig<TContext>> | undefined; | ||
on?: Record<string, Transition<TContext> | undefined>; | ||
states?: StatesConfig<TContext, TStateSchema, TEvents> | undefined; | ||
on?: TransitionsConfig<TContext, TEvents>; | ||
onEntry?: SingleOrArray<Action<TContext>>; | ||
onExit?: SingleOrArray<Action<TContext>>; | ||
after?: DelayedTransitions<TContext>; | ||
after?: DelayedTransitions<TContext, TEvents>; | ||
activities?: SingleOrArray<Activity<TContext>>; | ||
parent?: StateNode<TContext>; | ||
strict?: boolean | undefined; | ||
data?: TData; | ||
data?: TStateSchema extends { | ||
data: infer D; | ||
} ? D : any; | ||
id?: string | undefined; | ||
@@ -103,18 +122,18 @@ delimiter?: string; | ||
} | ||
export interface StateNodeDefinition<TContext = DefaultContext, TData = any> extends StateNodeConfig<TContext> { | ||
export interface StateNodeDefinition<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends StateNodeConfig<TContext, TStateSchema, TEvents> { | ||
id: string; | ||
key: string; | ||
type: StateTypes; | ||
initial: string | undefined; | ||
initial: StateNodeConfig<TContext, TStateSchema, TEvents>['initial']; | ||
history: boolean | 'shallow' | 'deep' | undefined; | ||
states: Record<string, StateNodeDefinition<TContext>>; | ||
on: Record<string, Array<TransitionDefinition<TContext>>>; | ||
states: StatesDefinition<TContext, TStateSchema, TEvents>; | ||
on: TransitionsDefinition<TContext, TEvents>; | ||
onEntry: Array<Action<TContext>>; | ||
onExit: Array<Action<TContext>>; | ||
after: Array<DelayedTransitionDefinition<TContext>>; | ||
after: Array<DelayedTransitionDefinition<TContext, TEvents>>; | ||
activities: Array<ActivityDefinition<TContext>>; | ||
data: TData; | ||
data: any; | ||
order: number; | ||
} | ||
export interface SimpleStateNodeConfig<TContext> extends StateNodeConfig<TContext> { | ||
export interface SimpleStateNodeConfig<TContext, TEvents extends EventObject> extends StateNodeConfig<TContext, never, TEvents> { | ||
initial?: undefined; | ||
@@ -124,24 +143,22 @@ parallel?: false | undefined; | ||
} | ||
export interface HistoryStateNodeConfig<TContext> extends SimpleStateNodeConfig<TContext> { | ||
export interface HistoryStateNodeConfig<TContext, TEvents extends EventObject> extends SimpleStateNodeConfig<TContext, TEvents> { | ||
history: 'shallow' | 'deep' | true; | ||
target: StateValue | undefined; | ||
} | ||
export interface CompoundStateNodeConfig<TContext> extends StateNodeConfig<TContext> { | ||
initial?: string; | ||
export interface CompoundStateNodeConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends StateNodeConfig<TContext, TStateSchema, TEvents> { | ||
parallel?: boolean; | ||
states: Record<string, StateNodeConfig<TContext>>; | ||
states: StateNodeConfig<TContext, TStateSchema, TEvents>['states']; | ||
} | ||
export declare type SimpleOrCompoundStateNodeConfig<TContext> = SimpleStateNodeConfig<TContext> | CompoundStateNodeConfig<TContext>; | ||
export declare type SimpleOrCompoundStateNodeConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = SimpleStateNodeConfig<TContext, TEvents> | CompoundStateNodeConfig<TContext, TStateSchema, TEvents>; | ||
export declare type ActionFunctionMap<TContext> = Record<string, ActionObject<TContext> | ActionFunction<TContext>>; | ||
export interface MachineOptions<TContext> { | ||
guards?: Record<string, ConditionPredicate<TContext>>; | ||
export interface MachineOptions<TContext, TEvents extends EventObject> { | ||
guards?: Record<string, ConditionPredicate<TContext, TEvents>>; | ||
actions?: ActionFunctionMap<TContext>; | ||
activities?: Record<string, ActivityConfig<TContext>>; | ||
} | ||
export declare type MachineConfig<TContext> = CompoundStateNodeConfig<TContext>; | ||
export interface StandardMachineConfig<TContext> extends CompoundStateNodeConfig<TContext> { | ||
export declare type MachineConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = CompoundStateNodeConfig<TContext, TStateSchema, TEvents>; | ||
export interface StandardMachineConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends CompoundStateNodeConfig<TContext, TStateSchema, TEvents> { | ||
} | ||
export interface ParallelMachineConfig<TContext> extends CompoundStateNodeConfig<TContext> { | ||
initial?: string | undefined; | ||
parallel?: true; | ||
export interface ParallelMachineConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends CompoundStateNodeConfig<TContext, TStateSchema, TEvents> { | ||
initial?: undefined; | ||
type?: 'parallel'; | ||
@@ -153,12 +170,2 @@ } | ||
} | ||
export interface ComplexStateNode<TContext> extends StateNode<TContext> { | ||
initial: string; | ||
history: false; | ||
} | ||
export interface LeafStateNode<TContext> extends StateNode<TContext> { | ||
initial: never; | ||
parallel: never; | ||
states: never; | ||
parent: StateNode<TContext>; | ||
} | ||
export interface HistoryStateNode<TContext> extends StateNode<TContext> { | ||
@@ -168,14 +175,6 @@ history: 'shallow' | 'deep'; | ||
} | ||
export interface Machine<TContext = DefaultContext> extends StateNode<TContext> { | ||
export interface Machine<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends StateNode<TContext, TStateSchema, TEvents> { | ||
id: string; | ||
states: Record<string, StateNode<TContext>>; | ||
states: StateNode<TContext, TStateSchema, TEvents>['states']; | ||
} | ||
export interface StandardMachine<TContext> extends Machine<TContext> { | ||
initial: string; | ||
parallel: false; | ||
} | ||
export interface ParallelMachine<TContext> extends Machine<TContext> { | ||
initial: undefined; | ||
parallel: true; | ||
} | ||
export interface ActionMap<TContext> { | ||
@@ -193,3 +192,2 @@ onEntry: Array<Action<TContext>>; | ||
} | ||
export declare type MaybeStateValueActionsTuple<TContext> = [StateValue | undefined, ActionMap<TContext>, ActivityMap | undefined]; | ||
export interface StateTransition<TContext> { | ||
@@ -213,8 +211,19 @@ value: StateValue | undefined; | ||
Cancel = "xstate.cancel", | ||
Null = "xstate.null", | ||
Null = "", | ||
Assign = "xstate.assign", | ||
After = "xstate.after", | ||
DoneState = "done.state", | ||
Log = "xstate.log" | ||
Log = "xstate.log", | ||
Init = "xstate.init" | ||
} | ||
export interface RaisedEvent<TEvents extends EventObject> { | ||
type: ActionTypes.Raise; | ||
event: TEvents; | ||
} | ||
export declare type BuiltInEvent<TEvents extends EventObject> = { | ||
type: ActionTypes.Null; | ||
} | RaisedEvent<TEvents> | { | ||
type: ActionTypes.Init; | ||
}; | ||
export declare type AnyEvent<TEvents extends EventObject> = TEvents | BuiltInEvent<TEvents>; | ||
export interface ActivityActionObject<TContext> extends ActionObject<TContext> { | ||
@@ -225,4 +234,4 @@ type: ActionTypes.Start | ActionTypes.Stop; | ||
} | ||
export interface SendAction extends ActionObject<any> { | ||
event: EventObject; | ||
export interface SendAction<TContext, TEvents extends EventObject> extends ActionObject<TContext> { | ||
event: TEvents; | ||
delay?: number; | ||
@@ -238,10 +247,10 @@ id: string | number; | ||
} | ||
export declare type Assigner<TContext> = (extState: TContext, event: EventObject) => Partial<TContext>; | ||
export declare type PropertyAssigner<TContext> = Partial<{ | ||
[K in keyof TContext]: ((extState: TContext, event: EventObject) => TContext[K]) | TContext[K]; | ||
export declare type Assigner<TContext, TEvents extends EventObject> = (extState: TContext, event: TEvents) => Partial<TContext>; | ||
export declare type PropertyAssigner<TContext, TEvents extends EventObject> = Partial<{ | ||
[K in keyof TContext]: ((extState: TContext, event: TEvents) => TContext[K]) | TContext[K]; | ||
}>; | ||
export interface AssignAction<TContext> extends ActionObject<TContext> { | ||
assignment: Assigner<TContext> | PropertyAssigner<TContext>; | ||
export interface AssignAction<TContext, TEvents extends EventObject> extends ActionObject<TContext> { | ||
assignment: Assigner<TContext, TEvents> | PropertyAssigner<TContext, TEvents>; | ||
} | ||
export interface TransitionDefinition<TContext> extends TransitionConfig<TContext> { | ||
export interface TransitionDefinition<TContext, TEvents extends EventObject> extends TransitionConfig<TContext, TEvents> { | ||
actions: Array<Action<TContext>>; | ||
@@ -251,19 +260,21 @@ event: string; | ||
} | ||
export interface DelayedTransitionDefinition<TContext> extends TransitionDefinition<TContext> { | ||
export interface DelayedTransitionDefinition<TContext, TEvents extends EventObject> extends TransitionDefinition<TContext, TEvents> { | ||
delay: number; | ||
} | ||
export interface Edge<TContext> { | ||
event: string; | ||
export interface Edge<TContext, TEvents extends EventObject, TEventType extends TEvents['type'] = string> { | ||
event: TEventType; | ||
source: StateNode<TContext>; | ||
target: StateNode<TContext>; | ||
cond?: Condition<TContext>; | ||
cond?: Condition<TContext, TEvents & { | ||
type: TEventType; | ||
}>; | ||
actions: Array<Action<TContext>>; | ||
meta?: MetaObject; | ||
transition: TransitionDefinition<TContext>; | ||
transition: TransitionDefinition<TContext, TEvents>; | ||
} | ||
export interface NodesAndEdges<TContext> { | ||
export interface NodesAndEdges<TContext, TEvents extends EventObject> { | ||
nodes: StateNode[]; | ||
edges: Array<Edge<TContext>>; | ||
edges: Array<Edge<TContext, TEvents, TEvents['type']>>; | ||
} | ||
export interface Segment<TContext = DefaultContext> { | ||
export interface Segment<TContext = DefaultContext, TEvents extends EventObject = EventObject> { | ||
/** | ||
@@ -278,3 +289,3 @@ * From state | ||
*/ | ||
event: Event; | ||
event: Event<TEvents>; | ||
} | ||
@@ -308,3 +319,3 @@ export interface PathMap { | ||
} | ||
export interface StateInterface<TContext = DefaultContext, TData = DefaultData> { | ||
export interface StateInterface<TContext = DefaultContext, TEvents extends EventObject = EventObject> { | ||
value: StateValue; | ||
@@ -314,6 +325,12 @@ history?: State<TContext>; | ||
activities: ActivityMap; | ||
data: TData; | ||
events: EventObject[]; | ||
data: any; | ||
events: TEvents[]; | ||
context: TContext; | ||
toStrings: () => string[]; | ||
} | ||
export interface StateSchema { | ||
data?: any; | ||
states?: { | ||
[key: string]: StateSchema; | ||
}; | ||
} |
@@ -8,3 +8,3 @@ export var ActionTypes; | ||
ActionTypes["Cancel"] = "xstate.cancel"; | ||
ActionTypes["Null"] = "xstate.null"; | ||
ActionTypes["Null"] = ""; | ||
ActionTypes["Assign"] = "xstate.assign"; | ||
@@ -14,2 +14,3 @@ ActionTypes["After"] = "xstate.after"; | ||
ActionTypes["Log"] = "xstate.log"; | ||
ActionTypes["Init"] = "xstate.init"; | ||
})(ActionTypes || (ActionTypes = {})); |
import { State } from './State'; | ||
import { Event, StateValue, EventType, ActionType, Action } from './types'; | ||
export declare function getEventType(event: Event): EventType; | ||
import { Event, StateValue, ActionType, Action, EventObject } from './types'; | ||
export declare function getEventType<TEvents extends EventObject = EventObject>(event: Event<TEvents>): TEvents['type']; | ||
export declare function getActionType(action: Action<any>): ActionType; | ||
@@ -5,0 +5,0 @@ export declare function toStatePath(stateId: string | string[], delimiter: string): string[]; |
import { Action, Event, EventObject, SendAction, SendActionOptions, CancelAction, ActionObject, Assigner, AssignAction, ActionFunction, ActivityActionObject, ActionTypes, ActivityDefinition } from './types'; | ||
import * as actionTypes from './actionTypes'; | ||
export { actionTypes }; | ||
export declare const toEventObject: (event: Event, id?: string | number | undefined) => EventObject; | ||
export declare function toEventObject<TEvents extends EventObject>(event: Event<TEvents>): TEvents; | ||
export declare const toActionObject: <TContext>(action: Action<TContext>, actionFunctionMap?: Record<string, ActionObject<TContext> | ActionFunction<TContext>> | undefined) => ActionObject<TContext>; | ||
export declare function toActivityDefinition<TContext>(action: string | ActionObject<TContext> | ActivityDefinition<TContext>): ActivityDefinition<TContext>; | ||
export declare const toActionObjects: <TContext>(action: Action<TContext>[] | undefined, actionFunctionMap?: Record<string, ActionObject<TContext> | ActionFunction<TContext>> | undefined) => ActionObject<TContext>[]; | ||
export declare const raise: (eventType: string | number) => EventObject; | ||
export declare const send: (event: Event, options?: SendActionOptions | undefined) => SendAction; | ||
export declare function log<TContext>(expr: (ctx: TContext, event: EventObject) => void, label?: string): { | ||
interface RaiseEvent<TContext, TEvents extends EventObject> extends ActionObject<TContext> { | ||
event: TEvents['type']; | ||
} | ||
export declare function raise<TContext, TEvents extends EventObject>(eventType: TEvents['type']): RaiseEvent<TContext, TEvents>; | ||
export declare function send<TContext, TEvents extends EventObject>(event: Event<TEvents>, options?: SendActionOptions): SendAction<TContext, TEvents>; | ||
export declare function log<TContext, TEvents extends EventObject>(expr: (ctx: TContext, event: TEvents) => void, label?: string): { | ||
type: ActionTypes; | ||
label: string | undefined; | ||
expr: (ctx: TContext, event: EventObject) => void; | ||
expr: (ctx: TContext, event: TEvents) => void; | ||
}; | ||
@@ -18,5 +21,5 @@ export declare const cancel: (sendId: string | number) => CancelAction; | ||
export declare function stop<TContext>(activity: string | ActionObject<TContext> | ActivityDefinition<TContext>): ActivityActionObject<TContext>; | ||
export declare const assign: <TContext>(assignment: Assigner<TContext> | Partial<{ [K in keyof TContext]: ((extState: TContext, event: EventObject) => TContext[K]) | TContext[K]; }>) => AssignAction<TContext>; | ||
export declare const assign: <TContext, TEvents extends EventObject = EventObject>(assignment: Assigner<TContext, TEvents> | Partial<{ [K in keyof TContext]: ((extState: TContext, event: TEvents) => TContext[K]) | TContext[K]; }>) => AssignAction<TContext, TEvents>; | ||
export declare function isActionObject<TContext>(action: Action<TContext>): action is ActionObject<TContext>; | ||
export declare function after(delay: number, id?: string): string; | ||
export declare function done(id: string): string; |
@@ -18,12 +18,15 @@ "use strict"; | ||
var utils_1 = require("./utils"); | ||
exports.toEventObject = function (event, id) { | ||
function toEventObject(event | ||
// id?: TEvents['type'] | ||
) { | ||
if (typeof event === 'string' || typeof event === 'number') { | ||
var eventObject = { type: event }; | ||
if (id !== undefined) { | ||
eventObject.id = id; | ||
} | ||
// if (id !== undefined) { | ||
// eventObject.id = id; | ||
// } | ||
return eventObject; | ||
} | ||
return event; | ||
}; | ||
} | ||
exports.toEventObject = toEventObject; | ||
function getActionFunction(actionType, actionFunctionMap) { | ||
@@ -83,14 +86,20 @@ if (!actionFunctionMap) { | ||
}; | ||
exports.raise = function (eventType) { return ({ | ||
type: actionTypes.raise, | ||
event: eventType | ||
}); }; | ||
exports.send = function (event, options) { | ||
function raise(eventType) { | ||
return { | ||
type: actionTypes.raise, | ||
event: eventType | ||
}; | ||
} | ||
exports.raise = raise; | ||
function send(event, options) { | ||
return { | ||
type: actionTypes.send, | ||
event: exports.toEventObject(event), | ||
event: toEventObject(event), | ||
delay: options ? options.delay : undefined, | ||
id: options && options.id !== undefined ? options.id : utils_1.getEventType(event) | ||
id: options && options.id !== undefined | ||
? options.id | ||
: utils_1.getEventType(event) | ||
}; | ||
}; | ||
} | ||
exports.send = send; | ||
function log(expr, label) { | ||
@@ -97,0 +106,0 @@ return { |
@@ -13,1 +13,2 @@ import { ActionTypes } from './types'; | ||
export declare const log: ActionTypes; | ||
export declare const init: ActionTypes; |
@@ -16,1 +16,2 @@ "use strict"; | ||
exports.log = types_1.ActionTypes.Log; | ||
exports.init = types_1.ActionTypes.Init; |
import { StateNode, State } from './index'; | ||
import { StateValue, Edge, PathMap, PathItem, PathsItem, PathsMap, AdjacencyMap, DefaultContext, ValueAdjacencyMap, Event } from './types'; | ||
import { StateValue, Edge, PathMap, PathItem, PathsItem, PathsMap, AdjacencyMap, DefaultContext, ValueAdjacencyMap, Event, EventObject } from './types'; | ||
export declare function getNodes(node: StateNode): StateNode[]; | ||
export declare function getEventEdges<TContext = DefaultContext>(node: StateNode<TContext>, event: string): Array<Edge<TContext>>; | ||
export declare function getEdges<TContext = DefaultContext>(node: StateNode<TContext>, options?: { | ||
export declare function getEventEdges<TContext = DefaultContext, TEvents extends EventObject = EventObject>(node: StateNode<TContext>, event: string): Array<Edge<TContext, TEvents>>; | ||
export declare function getEdges<TContext = DefaultContext, TEvents extends EventObject = EventObject>(node: StateNode<TContext>, options?: { | ||
depth: null | number; | ||
}): Array<Edge<TContext>>; | ||
}): Array<Edge<TContext, TEvents>>; | ||
export declare function getAdjacencyMap<TContext = DefaultContext>(node: StateNode<TContext>, context?: TContext): AdjacencyMap; | ||
@@ -13,8 +13,10 @@ export declare function deserializeStateString(valueContextString: string): { | ||
}; | ||
export interface GetValueAdjacencyMapOptions<TContext> { | ||
events: Record<string, Event[]>; | ||
export interface GetValueAdjacencyMapOptions<TContext, TEvents extends EventObject> { | ||
events: { | ||
[K in TEvents['type']]: Event<TEvents>; | ||
}; | ||
filter?: (state: State<TContext>) => boolean; | ||
} | ||
export declare function getValueAdjacencyMap<TContext = DefaultContext>(node: StateNode<TContext>, options: GetValueAdjacencyMapOptions<TContext>): ValueAdjacencyMap; | ||
export declare function getShortestValuePaths<TContext = DefaultContext>(machine: StateNode<TContext>, options: GetValueAdjacencyMapOptions<TContext>): PathMap; | ||
export declare function getValueAdjacencyMap<TContext = DefaultContext, TEvents extends EventObject = EventObject>(node: StateNode<TContext, any, TEvents>, options: GetValueAdjacencyMapOptions<TContext, TEvents>): ValueAdjacencyMap; | ||
export declare function getShortestValuePaths<TContext = DefaultContext, TEvents extends EventObject = EventObject>(machine: StateNode<TContext>, options: GetValueAdjacencyMapOptions<TContext, TEvents>): PathMap; | ||
export declare function getShortestPaths<TContext = DefaultContext>(machine: StateNode<TContext>, context?: TContext): PathMap; | ||
@@ -21,0 +23,0 @@ export declare function getShortestPathsAsArray<TContext = DefaultContext>(machine: StateNode<TContext>, context?: TContext): PathItem[]; |
@@ -116,2 +116,3 @@ "use strict"; | ||
} | ||
// @ts-ignore - TODO: fix? | ||
var type = event.type, rest = __rest(event, ["type"]); | ||
@@ -135,3 +136,5 @@ return type + " | " + JSON.stringify(rest); | ||
var adjacency = {}; | ||
var potentialEvents = utils_1.flatten(node.events.map(function (event) { return events[event] || [event]; })); | ||
var potentialEvents = utils_1.flatten( | ||
// @ts-ignore | ||
node.events.map(function (event) { return events[event] || [event]; })); | ||
function findAdjacencies(state) { | ||
@@ -138,0 +141,0 @@ var stateKey = serializeState(state); |
@@ -1,2 +0,2 @@ | ||
import { Machine, Event, EventObject, DefaultContext } from './types'; | ||
import { Machine, Event, EventObject, DefaultContext, StateSchema } from './types'; | ||
import { State } from './State'; | ||
@@ -28,8 +28,8 @@ export declare type StateListener = <TContext = DefaultContext>(state: State<TContext>) => void; | ||
} | ||
export declare class Interpreter<TContext> { | ||
machine: Machine<TContext>; | ||
export declare class Interpreter<TContext, TStateSchema extends StateSchema = any, TEvents extends EventObject = EventObject> { | ||
machine: Machine<TContext, TStateSchema, TEvents>; | ||
static defaultOptions: InterpreterOptions; | ||
state: State<TContext>; | ||
state: State<TContext, TEvents>; | ||
extState: TContext; | ||
eventQueue: EventObject[]; | ||
eventQueue: TEvents[]; | ||
delayedEventsMap: Record<string, number>; | ||
@@ -41,3 +41,3 @@ listeners: Set<StateListener>; | ||
initialized: boolean; | ||
constructor(machine: Machine<TContext>, listener?: StateListener, options?: Partial<InterpreterOptions>); | ||
constructor(machine: Machine<TContext, TStateSchema, TEvents>, listener?: StateListener, options?: Partial<InterpreterOptions>); | ||
static interpret: typeof interpret; | ||
@@ -56,6 +56,6 @@ private update; | ||
off(listener: StateListener): Interpreter<TContext>; | ||
init: (initialState?: State<TContext>) => Interpreter<TContext>; | ||
start(initialState?: State<TContext>): Interpreter<TContext>; | ||
init: (initialState?: State<TContext, TEvents>) => Interpreter<TContext, any, EventObject>; | ||
start(initialState?: State<TContext, TEvents>): Interpreter<TContext>; | ||
stop(): Interpreter<TContext>; | ||
send: (event: Event) => State<TContext>; | ||
send: (event: Event<TEvents>) => State<TContext, TEvents>; | ||
private defer; | ||
@@ -66,3 +66,3 @@ private cancel; | ||
} | ||
export declare function interpret<TContext = DefaultContext>(machine: Machine<TContext>, listener?: StateListener, options?: Partial<InterpreterOptions>): Interpreter<TContext>; | ||
export declare function interpret<TContext = DefaultContext, TStateSchema extends StateSchema = any, TEvents extends EventObject = EventObject>(machine: Machine<TContext, TStateSchema, TEvents>, listener?: StateListener, options?: Partial<InterpreterOptions>): Interpreter<TContext, TStateSchema, TEvents>; | ||
export {}; |
@@ -80,3 +80,3 @@ "use strict"; | ||
} | ||
var nextState = _this.machine.transition(_this.state, eventObject, _this.extState); | ||
var nextState = _this.machine.transition(_this.state, eventObject, _this.extState); // TODO: fixme | ||
_this.update(nextState, event); | ||
@@ -181,6 +181,8 @@ _this.flushEventQueue(); | ||
Interpreter.prototype.flushEventQueue = function () { | ||
if (this.eventQueue.length) { | ||
this.send(this.eventQueue.unshift()); | ||
var flushedEvent = this.eventQueue.shift(); | ||
if (flushedEvent) { | ||
this.send(flushedEvent); | ||
} | ||
}; | ||
// TODO: fixme | ||
Interpreter.defaultOptions = { | ||
@@ -187,0 +189,0 @@ clock: { setTimeout: setTimeout, clearTimeout: clearTimeout }, |
@@ -1,2 +0,2 @@ | ||
import { Machine, MachineOptions, DefaultContext, MachineConfig } from './types'; | ||
export declare function Machine<TContext = DefaultContext>(config: MachineConfig<TContext>, options?: MachineOptions<TContext>, initialContext?: TContext): Machine<TContext>; | ||
import { Machine, MachineOptions, DefaultContext, MachineConfig, StateSchema, EventObject } from './types'; | ||
export declare function Machine<TContext = DefaultContext, TStateSchema extends StateSchema = any, TEvents extends EventObject = EventObject>(config: MachineConfig<TContext, TStateSchema, TEvents>, options?: MachineOptions<TContext, TEvents>, initialContext?: TContext): Machine<TContext, TStateSchema, TEvents>; |
import { SimpleStateNodeConfig } from './types'; | ||
export declare function toggle(onState: string, offState: string, eventType: string): Record<string, SimpleStateNodeConfig<any>>; | ||
export declare function toggle<TEventType extends string = string>(onState: string, offState: string, eventType: TEventType): Record<string, SimpleStateNodeConfig<any, { | ||
type: TEventType; | ||
}>>; |
@@ -286,5 +286,4 @@ "use strict"; | ||
: undefined; | ||
// console.log(dataModelEl, extState); | ||
return index_1.Machine(__assign({}, toConfig(machineElement, '(machine)', options, extState), { delimiter: options.delimiter }), undefined, extState); | ||
} | ||
exports.toMachine = toMachine; |
import { StateValue, ActivityMap, EventObject, StateInterface, HistoryValue, ActionObject } from './types'; | ||
export declare class State<TContext> implements StateInterface<TContext> { | ||
export declare class State<TContext, TEvents extends EventObject = EventObject> implements StateInterface<TContext> { | ||
value: StateValue; | ||
context: TContext; | ||
historyValue?: HistoryValue | undefined; | ||
history?: State<TContext> | undefined; | ||
history?: State<TContext, EventObject> | undefined; | ||
actions: Array<ActionObject<TContext>>; | ||
@@ -13,13 +13,13 @@ activities: ActivityMap; | ||
*/ | ||
events: EventObject[]; | ||
static from<T>(stateValue: State<T> | StateValue, context: T): State<T>; | ||
static inert<T>(stateValue: State<T> | StateValue, ext: T): State<T>; | ||
constructor(value: StateValue, context: TContext, historyValue?: HistoryValue | undefined, history?: State<TContext> | undefined, actions?: Array<ActionObject<TContext>>, activities?: ActivityMap, data?: Record<string, any>, | ||
events: TEvents[]; | ||
static from<TC, TE extends EventObject = EventObject>(stateValue: State<TC, TE> | StateValue, context: TC): State<TC, TE>; | ||
static inert<TC, TE extends EventObject = EventObject>(stateValue: State<TC> | StateValue, ext: TC): State<TC, TE>; | ||
constructor(value: StateValue, context: TContext, historyValue?: HistoryValue | undefined, history?: State<TContext, EventObject> | undefined, actions?: Array<ActionObject<TContext>>, activities?: ActivityMap, data?: Record<string, any>, | ||
/** | ||
* Internal event queue | ||
*/ | ||
events?: EventObject[]); | ||
events?: TEvents[]); | ||
toStrings(value?: StateValue): string[]; | ||
matches(parentStateValue: StateValue): boolean; | ||
readonly changed: boolean; | ||
readonly changed: boolean | undefined; | ||
} |
@@ -58,6 +58,6 @@ "use strict"; | ||
if (!this.history) { | ||
return false; | ||
return undefined; | ||
} | ||
return (!!this.actions.length || | ||
(typeof this.history.value !== this.value | ||
(typeof this.history.value !== typeof this.value | ||
? true | ||
@@ -64,0 +64,0 @@ : typeof this.value === 'string' |
@@ -1,6 +0,6 @@ | ||
import { Event, StateValue, Action, EventType, StateTransition, MachineOptions, EventObject, HistoryValue, DefaultData, DefaultContext, StateNodeDefinition, TransitionDefinition, DelayedTransitionDefinition, ActivityDefinition, Delay, StateTypes, StateNodeConfig } from './types'; | ||
import { Event, StateValue, Action, StateTransition, MachineOptions, EventObject, HistoryValue, DefaultContext, StateNodeDefinition, DelayedTransitionDefinition, ActivityDefinition, Delay, StateTypes, StateNodeConfig, StateSchema, TransitionsDefinition, StateNodesConfig, AnyEvent } from './types'; | ||
import { State } from './State'; | ||
declare class StateNode<TContext = DefaultContext, TData = DefaultData> { | ||
declare class StateNode<TContext = DefaultContext, TStateSchema extends StateSchema = any, TEvents extends AnyEvent<EventObject> = AnyEvent<EventObject>> { | ||
private _config; | ||
options: Readonly<MachineOptions<TContext>>; | ||
options: Readonly<MachineOptions<TContext, TEvents>>; | ||
/** | ||
@@ -14,6 +14,6 @@ * The initial extended state | ||
path: string[]; | ||
initial?: string; | ||
initial?: keyof TStateSchema['states']; | ||
parallel: boolean; | ||
transient: boolean; | ||
states: Record<string, StateNode<TContext>>; | ||
states: StateNodesConfig<TContext, TStateSchema, TEvents>; | ||
history: false | 'shallow' | 'deep'; | ||
@@ -26,3 +26,5 @@ onEntry: Array<Action<TContext>>; | ||
machine: StateNode<TContext>; | ||
data: TData; | ||
data?: TStateSchema extends { | ||
data: infer D; | ||
} ? D : any; | ||
delimiter: string; | ||
@@ -32,3 +34,3 @@ order: number; | ||
private idMap; | ||
constructor(_config: StateNodeConfig<TContext>, options?: Readonly<MachineOptions<TContext>>, | ||
constructor(_config: StateNodeConfig<TContext, TStateSchema, TEvents>, options?: Readonly<MachineOptions<TContext, TEvents>>, | ||
/** | ||
@@ -38,12 +40,12 @@ * The initial extended state | ||
context?: Readonly<TContext> | undefined); | ||
readonly definition: StateNodeDefinition<TContext, TData>; | ||
readonly config: StateNodeConfig<TContext>; | ||
readonly on: Record<string, Array<TransitionDefinition<TContext>>>; | ||
readonly after: Array<DelayedTransitionDefinition<TContext>>; | ||
getStateNodes(state: StateValue | State<TContext>): Array<StateNode<TContext>>; | ||
handles(event: Event): boolean; | ||
readonly definition: StateNodeDefinition<TContext, TStateSchema, TEvents>; | ||
readonly config: StateNodeConfig<TContext, TStateSchema, TEvents>; | ||
readonly on: TransitionsDefinition<TContext, TEvents>; | ||
readonly after: Array<DelayedTransitionDefinition<TContext, TEvents>>; | ||
getStateNodes(state: StateValue | State<TContext, TEvents>): Array<StateNode<TContext>>; | ||
handles(event: Event<TEvents>): boolean; | ||
private transitionLeafNode; | ||
private transitionNestedNode; | ||
private transitionParallelNode; | ||
_transition(stateValue: StateValue, state: State<TContext>, event: EventObject, context?: TContext): StateTransition<TContext>; | ||
_transition(stateValue: StateValue, state: State<TContext, TEvents>, event: TEvents, context?: TContext): StateTransition<TContext>; | ||
private next; | ||
@@ -58,3 +60,3 @@ private getStateNodeValueTree; | ||
private getActivities; | ||
transition(state: StateValue | State<TContext>, event: Event, context?: TContext): State<TContext>; | ||
transition(state: StateValue | State<TContext, TEvents>, event: Event<TEvents>, context?: TContext): State<TContext, TEvents>; | ||
private resolveTransition; | ||
@@ -69,4 +71,4 @@ private ensureValidPaths; | ||
private readonly initialStateValue; | ||
getState(stateValue: StateValue, context?: TContext): State<TContext>; | ||
readonly initialState: State<TContext>; | ||
getState(stateValue: StateValue, context?: TContext): State<TContext, TEvents>; | ||
readonly initialState: State<TContext, TEvents>; | ||
readonly target: StateValue | undefined; | ||
@@ -100,3 +102,3 @@ getStates(stateValue: StateValue): Array<StateNode<TContext>>; | ||
readonly stateIds: string[]; | ||
readonly events: EventType[]; | ||
readonly events: Array<TEvents['type']>; | ||
private formatTransition; | ||
@@ -103,0 +105,0 @@ private formatTransitions; |
@@ -24,2 +24,3 @@ "use strict"; | ||
var utils_1 = require("./utils"); | ||
var types_1 = require("./types"); | ||
var matchesState_1 = require("./matchesState"); | ||
@@ -390,3 +391,4 @@ var State_1 = require("./State"); | ||
var entryExitStates = nextStateNodes.reduce(function (allEntryExitStates, nextStateNode) { | ||
var _a = _this.getEntryExitStates(nextStateNode, !!selectedTransition.internal), entry = _a.entry, exit = _a.exit; | ||
var _a = _this.getEntryExitStates(nextStateNode, !!selectedTransition | ||
.internal), entry = _a.entry, exit = _a.exit; | ||
return { | ||
@@ -604,8 +606,10 @@ entry: new Set(Array.from(allEntryExitStates.entry).concat(Array.from(entry))), | ||
: undefined; | ||
try { | ||
this.ensureValidPaths(stateTransition.paths); | ||
if (process.env.NODE_ENV !== 'production') { | ||
try { | ||
this.ensureValidPaths(stateTransition.paths); | ||
} | ||
catch (e) { | ||
throw new Error("Event '" + (event ? event.type : 'none') + "' leads to an invalid configuration: " + e.message); | ||
} | ||
} | ||
catch (e) { | ||
throw new Error("Event '" + (event ? event.type : 'none') + "' leads to an invalid configuration: " + e.message); | ||
} | ||
var actions = this.getActions(stateTransition); | ||
@@ -629,3 +633,3 @@ var activities = this.getActivities(stateTransition.entryExitStates, currentState.activities); | ||
if (typeof assignment === 'function') { | ||
partialUpdate = assignment(acc, event || { type: 'xstate.init' }); | ||
partialUpdate = assignment(acc, event || { type: types_1.ActionTypes.Init }); | ||
} | ||
@@ -666,4 +670,6 @@ else { | ||
} | ||
// Dispose of previous histories to prevent memory leaks | ||
delete currentState.history; | ||
// Dispose of penultimate histories to prevent memory leaks | ||
if (currentState.history) { | ||
delete currentState.history.history; | ||
} | ||
var maybeNextState = nextState; | ||
@@ -673,3 +679,5 @@ while (raisedEvents.length) { | ||
var raisedEvent = raisedEvents.shift(); | ||
maybeNextState = this.transition(maybeNextState, raisedEvent.type === actionTypes.null ? NULL_EVENT : raisedEvent.event, maybeNextState.context); | ||
maybeNextState = this.transition(maybeNextState, raisedEvent.type === actionTypes.null | ||
? NULL_EVENT | ||
: raisedEvent.event, maybeNextState.context); | ||
(_a = maybeNextState.actions).unshift.apply(_a, currentActions); | ||
@@ -775,2 +783,3 @@ } | ||
return _b = {}, | ||
// @ts-ignore TODO: fixme | ||
_b[key] = this.states[this.initial].resolvedStateValue, | ||
@@ -819,3 +828,3 @@ _b; | ||
stateNode.activities.forEach(function (activity) { | ||
activityMap[utils_1.getEventType(activity)] = true; | ||
activityMap[utils_1.getEventType(activity)] = true; // TODO: fixme | ||
actions.push(actions_1.start(activity)); | ||
@@ -836,3 +845,3 @@ }); | ||
if (typeof assignment === 'function') { | ||
partialUpdate = assignment(acc, { type: 'init' }); | ||
partialUpdate = assignment(acc, { type: 'init' }); // TODO: fix init | ||
} | ||
@@ -844,3 +853,3 @@ else { | ||
typeof propAssignment === 'function' | ||
? propAssignment(acc, { type: 'init' }) | ||
? propAssignment(acc, { type: 'init' }) // TODO: fix init | ||
: propAssignment; | ||
@@ -847,0 +856,0 @@ }); |
import { StateNode } from './StateNode'; | ||
import { State } from './State'; | ||
export declare type EventType = string | number; | ||
export declare type ActionType = string | number; | ||
export declare type ActionType = string; | ||
export declare type MetaObject = Record<string, any>; | ||
export interface EventObject { | ||
type: EventType; | ||
export interface EventObject extends Record<string, any> { | ||
type: string | number; | ||
id?: string | number; | ||
[key: string]: any; | ||
} | ||
export interface ActionObject<TContext> extends Record<string, any> { | ||
type: ActionType; | ||
type: string; | ||
exec?: ActionFunction<TContext>; | ||
} | ||
export declare type DefaultContext = Record<string, any> | undefined; | ||
export declare type DefaultData = Record<string, any>; | ||
export declare type Event = EventType | EventObject; | ||
export declare type InternalEvent = EventType | EventObject; | ||
export declare type Event<TEvents extends EventObject> = TEvents['type'] | TEvents; | ||
export interface ActionFunction<TContext> { | ||
@@ -23,4 +20,3 @@ (context: TContext, event?: EventObject): any | void; | ||
} | ||
export declare type InternalAction<TContext> = SendAction | AssignAction<TContext>; | ||
export declare type Action<TContext> = ActionType | ActionObject<TContext> | InternalAction<TContext> | ActionFunction<TContext>; | ||
export declare type Action<TContext> = ActionType | ActionObject<TContext> | ActionFunction<TContext>; | ||
export declare type StateKey = string | State<any>; | ||
@@ -40,6 +36,6 @@ export interface StateValueMap { | ||
} | ||
export declare type ConditionPredicate<TContext> = (context: TContext, event: EventObject, microstepState: StateValue) => boolean; | ||
export declare type Condition<TContext> = string | ConditionPredicate<TContext>; | ||
export interface TransitionConfig<TContext = DefaultContext> { | ||
cond?: Condition<TContext>; | ||
export declare type ConditionPredicate<TContext, TEvents extends EventObject> = (context: TContext, event: TEvents, microstepState: StateValue) => boolean; | ||
export declare type Condition<TContext, TEvents extends EventObject> = string | ConditionPredicate<TContext, TEvents>; | ||
export interface TransitionConfig<TContext, TEvents extends EventObject> { | ||
cond?: Condition<TContext, TEvents>; | ||
actions?: SingleOrArray<Action<TContext>>; | ||
@@ -50,7 +46,7 @@ in?: StateValue; | ||
} | ||
export interface TargetTransitionConfig<TContext = DefaultContext> extends TransitionConfig<TContext> { | ||
export interface TargetTransitionConfig<TContext, TEvents extends EventObject> extends TransitionConfig<TContext, TEvents> { | ||
target: string | string[] | undefined; | ||
} | ||
export declare type ConditionalTransitionConfig<TContext = DefaultContext> = Array<TransitionConfig<TContext>>; | ||
export declare type Transition<TContext = DefaultContext> = string | TransitionConfig<TContext> | ConditionalTransitionConfig<TContext>; | ||
export declare type ConditionalTransitionConfig<TContext = DefaultContext, TEvents extends EventObject = EventObject> = Array<TransitionConfig<TContext, TEvents>>; | ||
export declare type Transition<TContext, TEvents extends EventObject = EventObject> = string | TransitionConfig<TContext, TEvents> | ConditionalTransitionConfig<TContext, TEvents>; | ||
export interface ActivityConfig<TContext> { | ||
@@ -62,3 +58,3 @@ start?: Action<TContext>; | ||
export interface ActivityDefinition<TContext> extends ActionObject<TContext> { | ||
type: ActionType; | ||
type: string; | ||
start?: ActionObject<TContext>; | ||
@@ -71,11 +67,32 @@ stop?: ActionObject<TContext>; | ||
} | ||
export interface DelayedTransitionConfig<TContext> extends TransitionConfig<TContext> { | ||
export interface DelayedTransitionConfig<TContext, TEvents extends EventObject> extends TransitionConfig<TContext, TEvents> { | ||
delay: number; | ||
} | ||
export declare type DelayedTransitions<TContext> = Record<string, string | TransitionConfig<TContext> | Array<TransitionConfig<TContext>>> | Array<DelayedTransitionConfig<TContext>>; | ||
export declare type DelayedTransitions<TContext, TEvents extends EventObject> = Record<string, string | TransitionConfig<TContext, TEvents> | Array<TransitionConfig<TContext, TEvents>>> | Array<DelayedTransitionConfig<TContext, TEvents>>; | ||
export declare type StateTypes = 'atomic' | 'compound' | 'parallel' | 'final' | 'history'; | ||
export declare type SingleOrArray<T> = T[] | T; | ||
export interface StateNodeConfig<TContext = DefaultContext, TData = any> { | ||
export declare type StateNodesConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = { | ||
[K in keyof TStateSchema['states']]: StateNode<TContext, TStateSchema['states'][K], TEvents>; | ||
}; | ||
export declare type StatesConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = { | ||
[K in keyof TStateSchema['states']]: StateNodeConfig<TContext, TStateSchema['states'][K], TEvents>; | ||
}; | ||
export declare type StatesDefinition<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = { | ||
[K in keyof TStateSchema['states']]: StateNodeDefinition<TContext, TStateSchema['states'][K], TEvents>; | ||
}; | ||
export declare type TransitionsConfig<TContext, TEvents extends EventObject> = { | ||
[K in TEvents['type'] | BuiltInEvent<TEvents>['type']]?: string | TransitionConfig<TContext, TEvents extends { | ||
type: K; | ||
} ? TEvents : EventObject> | Array<TransitionConfig<TContext, TEvents extends { | ||
type: K; | ||
} ? TEvents : EventObject>>; | ||
}; | ||
export declare type TransitionsDefinition<TContext, TEvents extends EventObject> = { | ||
[K in TEvents['type']]: Array<TransitionDefinition<TContext, TEvents extends { | ||
type: K; | ||
} ? TEvents : EventObject>>; | ||
}; | ||
export interface StateNodeConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> { | ||
key?: string; | ||
initial?: string | undefined; | ||
initial?: keyof TStateSchema['states'] | undefined; | ||
parallel?: boolean | undefined; | ||
@@ -89,11 +106,13 @@ type?: StateTypes; | ||
history?: 'shallow' | 'deep' | boolean | undefined; | ||
states?: Record<string, StateNodeConfig<TContext>> | undefined; | ||
on?: Record<string, Transition<TContext> | undefined>; | ||
states?: StatesConfig<TContext, TStateSchema, TEvents> | undefined; | ||
on?: TransitionsConfig<TContext, TEvents>; | ||
onEntry?: SingleOrArray<Action<TContext>>; | ||
onExit?: SingleOrArray<Action<TContext>>; | ||
after?: DelayedTransitions<TContext>; | ||
after?: DelayedTransitions<TContext, TEvents>; | ||
activities?: SingleOrArray<Activity<TContext>>; | ||
parent?: StateNode<TContext>; | ||
strict?: boolean | undefined; | ||
data?: TData; | ||
data?: TStateSchema extends { | ||
data: infer D; | ||
} ? D : any; | ||
id?: string | undefined; | ||
@@ -103,18 +122,18 @@ delimiter?: string; | ||
} | ||
export interface StateNodeDefinition<TContext = DefaultContext, TData = any> extends StateNodeConfig<TContext> { | ||
export interface StateNodeDefinition<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends StateNodeConfig<TContext, TStateSchema, TEvents> { | ||
id: string; | ||
key: string; | ||
type: StateTypes; | ||
initial: string | undefined; | ||
initial: StateNodeConfig<TContext, TStateSchema, TEvents>['initial']; | ||
history: boolean | 'shallow' | 'deep' | undefined; | ||
states: Record<string, StateNodeDefinition<TContext>>; | ||
on: Record<string, Array<TransitionDefinition<TContext>>>; | ||
states: StatesDefinition<TContext, TStateSchema, TEvents>; | ||
on: TransitionsDefinition<TContext, TEvents>; | ||
onEntry: Array<Action<TContext>>; | ||
onExit: Array<Action<TContext>>; | ||
after: Array<DelayedTransitionDefinition<TContext>>; | ||
after: Array<DelayedTransitionDefinition<TContext, TEvents>>; | ||
activities: Array<ActivityDefinition<TContext>>; | ||
data: TData; | ||
data: any; | ||
order: number; | ||
} | ||
export interface SimpleStateNodeConfig<TContext> extends StateNodeConfig<TContext> { | ||
export interface SimpleStateNodeConfig<TContext, TEvents extends EventObject> extends StateNodeConfig<TContext, never, TEvents> { | ||
initial?: undefined; | ||
@@ -124,24 +143,22 @@ parallel?: false | undefined; | ||
} | ||
export interface HistoryStateNodeConfig<TContext> extends SimpleStateNodeConfig<TContext> { | ||
export interface HistoryStateNodeConfig<TContext, TEvents extends EventObject> extends SimpleStateNodeConfig<TContext, TEvents> { | ||
history: 'shallow' | 'deep' | true; | ||
target: StateValue | undefined; | ||
} | ||
export interface CompoundStateNodeConfig<TContext> extends StateNodeConfig<TContext> { | ||
initial?: string; | ||
export interface CompoundStateNodeConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends StateNodeConfig<TContext, TStateSchema, TEvents> { | ||
parallel?: boolean; | ||
states: Record<string, StateNodeConfig<TContext>>; | ||
states: StateNodeConfig<TContext, TStateSchema, TEvents>['states']; | ||
} | ||
export declare type SimpleOrCompoundStateNodeConfig<TContext> = SimpleStateNodeConfig<TContext> | CompoundStateNodeConfig<TContext>; | ||
export declare type SimpleOrCompoundStateNodeConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = SimpleStateNodeConfig<TContext, TEvents> | CompoundStateNodeConfig<TContext, TStateSchema, TEvents>; | ||
export declare type ActionFunctionMap<TContext> = Record<string, ActionObject<TContext> | ActionFunction<TContext>>; | ||
export interface MachineOptions<TContext> { | ||
guards?: Record<string, ConditionPredicate<TContext>>; | ||
export interface MachineOptions<TContext, TEvents extends EventObject> { | ||
guards?: Record<string, ConditionPredicate<TContext, TEvents>>; | ||
actions?: ActionFunctionMap<TContext>; | ||
activities?: Record<string, ActivityConfig<TContext>>; | ||
} | ||
export declare type MachineConfig<TContext> = CompoundStateNodeConfig<TContext>; | ||
export interface StandardMachineConfig<TContext> extends CompoundStateNodeConfig<TContext> { | ||
export declare type MachineConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> = CompoundStateNodeConfig<TContext, TStateSchema, TEvents>; | ||
export interface StandardMachineConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends CompoundStateNodeConfig<TContext, TStateSchema, TEvents> { | ||
} | ||
export interface ParallelMachineConfig<TContext> extends CompoundStateNodeConfig<TContext> { | ||
initial?: string | undefined; | ||
parallel?: true; | ||
export interface ParallelMachineConfig<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends CompoundStateNodeConfig<TContext, TStateSchema, TEvents> { | ||
initial?: undefined; | ||
type?: 'parallel'; | ||
@@ -153,12 +170,2 @@ } | ||
} | ||
export interface ComplexStateNode<TContext> extends StateNode<TContext> { | ||
initial: string; | ||
history: false; | ||
} | ||
export interface LeafStateNode<TContext> extends StateNode<TContext> { | ||
initial: never; | ||
parallel: never; | ||
states: never; | ||
parent: StateNode<TContext>; | ||
} | ||
export interface HistoryStateNode<TContext> extends StateNode<TContext> { | ||
@@ -168,14 +175,6 @@ history: 'shallow' | 'deep'; | ||
} | ||
export interface Machine<TContext = DefaultContext> extends StateNode<TContext> { | ||
export interface Machine<TContext, TStateSchema extends StateSchema, TEvents extends EventObject> extends StateNode<TContext, TStateSchema, TEvents> { | ||
id: string; | ||
states: Record<string, StateNode<TContext>>; | ||
states: StateNode<TContext, TStateSchema, TEvents>['states']; | ||
} | ||
export interface StandardMachine<TContext> extends Machine<TContext> { | ||
initial: string; | ||
parallel: false; | ||
} | ||
export interface ParallelMachine<TContext> extends Machine<TContext> { | ||
initial: undefined; | ||
parallel: true; | ||
} | ||
export interface ActionMap<TContext> { | ||
@@ -193,3 +192,2 @@ onEntry: Array<Action<TContext>>; | ||
} | ||
export declare type MaybeStateValueActionsTuple<TContext> = [StateValue | undefined, ActionMap<TContext>, ActivityMap | undefined]; | ||
export interface StateTransition<TContext> { | ||
@@ -213,8 +211,19 @@ value: StateValue | undefined; | ||
Cancel = "xstate.cancel", | ||
Null = "xstate.null", | ||
Null = "", | ||
Assign = "xstate.assign", | ||
After = "xstate.after", | ||
DoneState = "done.state", | ||
Log = "xstate.log" | ||
Log = "xstate.log", | ||
Init = "xstate.init" | ||
} | ||
export interface RaisedEvent<TEvents extends EventObject> { | ||
type: ActionTypes.Raise; | ||
event: TEvents; | ||
} | ||
export declare type BuiltInEvent<TEvents extends EventObject> = { | ||
type: ActionTypes.Null; | ||
} | RaisedEvent<TEvents> | { | ||
type: ActionTypes.Init; | ||
}; | ||
export declare type AnyEvent<TEvents extends EventObject> = TEvents | BuiltInEvent<TEvents>; | ||
export interface ActivityActionObject<TContext> extends ActionObject<TContext> { | ||
@@ -225,4 +234,4 @@ type: ActionTypes.Start | ActionTypes.Stop; | ||
} | ||
export interface SendAction extends ActionObject<any> { | ||
event: EventObject; | ||
export interface SendAction<TContext, TEvents extends EventObject> extends ActionObject<TContext> { | ||
event: TEvents; | ||
delay?: number; | ||
@@ -238,10 +247,10 @@ id: string | number; | ||
} | ||
export declare type Assigner<TContext> = (extState: TContext, event: EventObject) => Partial<TContext>; | ||
export declare type PropertyAssigner<TContext> = Partial<{ | ||
[K in keyof TContext]: ((extState: TContext, event: EventObject) => TContext[K]) | TContext[K]; | ||
export declare type Assigner<TContext, TEvents extends EventObject> = (extState: TContext, event: TEvents) => Partial<TContext>; | ||
export declare type PropertyAssigner<TContext, TEvents extends EventObject> = Partial<{ | ||
[K in keyof TContext]: ((extState: TContext, event: TEvents) => TContext[K]) | TContext[K]; | ||
}>; | ||
export interface AssignAction<TContext> extends ActionObject<TContext> { | ||
assignment: Assigner<TContext> | PropertyAssigner<TContext>; | ||
export interface AssignAction<TContext, TEvents extends EventObject> extends ActionObject<TContext> { | ||
assignment: Assigner<TContext, TEvents> | PropertyAssigner<TContext, TEvents>; | ||
} | ||
export interface TransitionDefinition<TContext> extends TransitionConfig<TContext> { | ||
export interface TransitionDefinition<TContext, TEvents extends EventObject> extends TransitionConfig<TContext, TEvents> { | ||
actions: Array<Action<TContext>>; | ||
@@ -251,19 +260,21 @@ event: string; | ||
} | ||
export interface DelayedTransitionDefinition<TContext> extends TransitionDefinition<TContext> { | ||
export interface DelayedTransitionDefinition<TContext, TEvents extends EventObject> extends TransitionDefinition<TContext, TEvents> { | ||
delay: number; | ||
} | ||
export interface Edge<TContext> { | ||
event: string; | ||
export interface Edge<TContext, TEvents extends EventObject, TEventType extends TEvents['type'] = string> { | ||
event: TEventType; | ||
source: StateNode<TContext>; | ||
target: StateNode<TContext>; | ||
cond?: Condition<TContext>; | ||
cond?: Condition<TContext, TEvents & { | ||
type: TEventType; | ||
}>; | ||
actions: Array<Action<TContext>>; | ||
meta?: MetaObject; | ||
transition: TransitionDefinition<TContext>; | ||
transition: TransitionDefinition<TContext, TEvents>; | ||
} | ||
export interface NodesAndEdges<TContext> { | ||
export interface NodesAndEdges<TContext, TEvents extends EventObject> { | ||
nodes: StateNode[]; | ||
edges: Array<Edge<TContext>>; | ||
edges: Array<Edge<TContext, TEvents, TEvents['type']>>; | ||
} | ||
export interface Segment<TContext = DefaultContext> { | ||
export interface Segment<TContext = DefaultContext, TEvents extends EventObject = EventObject> { | ||
/** | ||
@@ -278,3 +289,3 @@ * From state | ||
*/ | ||
event: Event; | ||
event: Event<TEvents>; | ||
} | ||
@@ -308,3 +319,3 @@ export interface PathMap { | ||
} | ||
export interface StateInterface<TContext = DefaultContext, TData = DefaultData> { | ||
export interface StateInterface<TContext = DefaultContext, TEvents extends EventObject = EventObject> { | ||
value: StateValue; | ||
@@ -314,6 +325,12 @@ history?: State<TContext>; | ||
activities: ActivityMap; | ||
data: TData; | ||
events: EventObject[]; | ||
data: any; | ||
events: TEvents[]; | ||
context: TContext; | ||
toStrings: () => string[]; | ||
} | ||
export interface StateSchema { | ||
data?: any; | ||
states?: { | ||
[key: string]: StateSchema; | ||
}; | ||
} |
@@ -10,3 +10,3 @@ "use strict"; | ||
ActionTypes["Cancel"] = "xstate.cancel"; | ||
ActionTypes["Null"] = "xstate.null"; | ||
ActionTypes["Null"] = ""; | ||
ActionTypes["Assign"] = "xstate.assign"; | ||
@@ -16,2 +16,3 @@ ActionTypes["After"] = "xstate.after"; | ||
ActionTypes["Log"] = "xstate.log"; | ||
ActionTypes["Init"] = "xstate.init"; | ||
})(ActionTypes = exports.ActionTypes || (exports.ActionTypes = {})); |
import { State } from './State'; | ||
import { Event, StateValue, EventType, ActionType, Action } from './types'; | ||
export declare function getEventType(event: Event): EventType; | ||
import { Event, StateValue, ActionType, Action, EventObject } from './types'; | ||
export declare function getEventType<TEvents extends EventObject = EventObject>(event: Event<TEvents>): TEvents['type']; | ||
export declare function getActionType(action: Action<any>): ActionType; | ||
@@ -5,0 +5,0 @@ export declare function toStatePath(stateId: string | string[], delimiter: string): string[]; |
{ | ||
"name": "xstate", | ||
"version": "4.0.0-7", | ||
"version": "4.0.0-8", | ||
"description": "Simple JavaScript Finite State Machines and Statecharts", | ||
@@ -61,3 +61,3 @@ "main": "lib/index.js", | ||
"tslint": "^5.11.0", | ||
"typescript": "^3.0.1", | ||
"typescript": "^3.0.3", | ||
"xml-js": "^1.6.7" | ||
@@ -64,0 +64,0 @@ }, |
@@ -6,2 +6,3 @@ # xstate | ||
[![Statecharts gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/statecharts/statecharts) | ||
<img src="https://opencollective.com/xstate/tiers/backer/badge.svg?label=sponsors&color=brightgreen" /> | ||
@@ -337,3 +338,9 @@ Functional, stateless JavaScript [finite state machines](https://en.wikipedia.org/wiki/Finite-state_machine) and [statecharts](http://www.inf.ed.ac.uk/teaching/courses/seoc/2005_2006/resources/statecharts.pdf). | ||
## Sponsors | ||
Huge thanks to the following companies for sponsoring `xstate`. You can sponsor further `xstate` development [on OpenCollective](https://opencollective.com/xstate). | ||
<a href="https://tipe.io" title="Tipe.io"><img src="https://cdn.tipe.io/tipe/tipe-logo.svg?w=240" style="background:#613DEF" /></a> | ||
## Interpreters | ||
- [`xstateful` by @avaragado](https://www.npmjs.com/package/@avaragado/xstateful) |
import { | ||
Action, | ||
Event, | ||
EventType, | ||
EventObject, | ||
@@ -25,17 +24,17 @@ SendAction, | ||
export const toEventObject = ( | ||
event: Event, | ||
id?: string | number | ||
): EventObject => { | ||
export function toEventObject<TEvents extends EventObject>( | ||
event: Event<TEvents> | ||
// id?: TEvents['type'] | ||
): TEvents { | ||
if (typeof event === 'string' || typeof event === 'number') { | ||
const eventObject: EventObject = { type: event }; | ||
if (id !== undefined) { | ||
eventObject.id = id; | ||
} | ||
const eventObject = { type: event }; | ||
// if (id !== undefined) { | ||
// eventObject.id = id; | ||
// } | ||
return eventObject; | ||
return eventObject as TEvents; | ||
} | ||
return event; | ||
}; | ||
return event as TEvents; | ||
} | ||
@@ -126,18 +125,33 @@ function getActionFunction<TContext>( | ||
export const raise = (eventType: EventType): EventObject => ({ | ||
type: actionTypes.raise, | ||
event: eventType | ||
}); | ||
interface RaiseEvent<TContext, TEvents extends EventObject> | ||
extends ActionObject<TContext> { | ||
event: TEvents['type']; | ||
} | ||
export const send = (event: Event, options?: SendActionOptions): SendAction => { | ||
export function raise<TContext, TEvents extends EventObject>( | ||
eventType: TEvents['type'] | ||
): RaiseEvent<TContext, TEvents> { | ||
return { | ||
type: actionTypes.raise, | ||
event: eventType | ||
}; | ||
} | ||
export function send<TContext, TEvents extends EventObject>( | ||
event: Event<TEvents>, | ||
options?: SendActionOptions | ||
): SendAction<TContext, TEvents> { | ||
return { | ||
type: actionTypes.send, | ||
event: toEventObject(event), | ||
event: toEventObject<TEvents>(event), | ||
delay: options ? options.delay : undefined, | ||
id: options && options.id !== undefined ? options.id : getEventType(event) | ||
id: | ||
options && options.id !== undefined | ||
? options.id | ||
: (getEventType<TEvents>(event) as string) | ||
}; | ||
}; | ||
} | ||
export function log<TContext>( | ||
expr: (ctx: TContext, event: EventObject) => void, | ||
export function log<TContext, TEvents extends EventObject>( | ||
expr: (ctx: TContext, event: TEvents) => void, | ||
label?: string | ||
@@ -183,5 +197,5 @@ ) { | ||
export const assign = <TContext>( | ||
assignment: Assigner<TContext> | PropertyAssigner<TContext> | ||
): AssignAction<TContext> => { | ||
export const assign = <TContext, TEvents extends EventObject = EventObject>( | ||
assignment: Assigner<TContext, TEvents> | PropertyAssigner<TContext, TEvents> | ||
): AssignAction<TContext, TEvents> => { | ||
return { | ||
@@ -188,0 +202,0 @@ type: actionTypes.assign, |
@@ -15,1 +15,2 @@ import { ActionTypes } from './types'; | ||
export const log = ActionTypes.Log; | ||
export const init = ActionTypes.Init; |
@@ -14,3 +14,4 @@ import { StateNode, State } from './index'; | ||
ValueAdjacencyMap, | ||
Event | ||
Event, | ||
EventObject | ||
} from './types'; | ||
@@ -36,6 +37,6 @@ | ||
export function getEventEdges<TContext = DefaultContext>( | ||
node: StateNode<TContext>, | ||
event: string | ||
): Array<Edge<TContext>> { | ||
export function getEventEdges< | ||
TContext = DefaultContext, | ||
TEvents extends EventObject = EventObject | ||
>(node: StateNode<TContext>, event: string): Array<Edge<TContext, TEvents>> { | ||
const transitions = node.definition.on[event]; | ||
@@ -65,3 +66,3 @@ | ||
return targets | ||
.map<Edge<TContext> | undefined>(target => { | ||
.map<Edge<TContext, TEvents> | undefined>(target => { | ||
try { | ||
@@ -88,3 +89,5 @@ const targetNode = target | ||
}) | ||
.filter(maybeEdge => maybeEdge !== undefined) as Array<Edge<TContext>>; | ||
.filter(maybeEdge => maybeEdge !== undefined) as Array< | ||
Edge<TContext, TEvents> | ||
>; | ||
}) | ||
@@ -94,8 +97,11 @@ ); | ||
export function getEdges<TContext = DefaultContext>( | ||
export function getEdges< | ||
TContext = DefaultContext, | ||
TEvents extends EventObject = EventObject | ||
>( | ||
node: StateNode<TContext>, | ||
options?: { depth: null | number } | ||
): Array<Edge<TContext>> { | ||
): Array<Edge<TContext, TEvents>> { | ||
const { depth = null } = options || {}; | ||
const edges: Array<Edge<TContext>> = []; | ||
const edges: Array<Edge<TContext, TEvents>> = []; | ||
@@ -140,3 +146,3 @@ if (node.states && depth === null) { | ||
const nextState = node.transition(stateValue, event, context); | ||
adjacency[stateKey][event] = { state: nextState.value }; | ||
adjacency[stateKey][event as string] = { state: nextState.value }; | ||
@@ -152,3 +158,5 @@ findAdjacencies(nextState.value); | ||
function eventToString(event: Event): string { | ||
function eventToString<TEvents extends EventObject = EventObject>( | ||
event: Event<TEvents> | ||
): string { | ||
if (typeof event === 'string' || typeof event === 'number') { | ||
@@ -158,2 +166,3 @@ return `${event}`; | ||
// @ts-ignore - TODO: fix? | ||
const { type, ...rest } = event; | ||
@@ -180,10 +189,17 @@ | ||
export interface GetValueAdjacencyMapOptions<TContext> { | ||
events: Record<string, Event[]>; | ||
export interface GetValueAdjacencyMapOptions< | ||
TContext, | ||
TEvents extends EventObject | ||
> { | ||
// events: Record<string, Array<Event<TEvents>>>; | ||
events: { [K in TEvents['type']]: Event<TEvents> }; | ||
filter?: (state: State<TContext>) => boolean; | ||
} | ||
export function getValueAdjacencyMap<TContext = DefaultContext>( | ||
node: StateNode<TContext>, | ||
options: GetValueAdjacencyMapOptions<TContext> | ||
export function getValueAdjacencyMap< | ||
TContext = DefaultContext, | ||
TEvents extends EventObject = EventObject | ||
>( | ||
node: StateNode<TContext, any, TEvents>, | ||
options: GetValueAdjacencyMapOptions<TContext, TEvents> | ||
): ValueAdjacencyMap { | ||
@@ -194,6 +210,7 @@ const { events, filter } = options; | ||
const potentialEvents = flatten( | ||
// @ts-ignore | ||
node.events.map(event => events[event] || [event]) | ||
); | ||
function findAdjacencies(state: State<TContext>) { | ||
function findAdjacencies(state: State<TContext, TEvents>) { | ||
const stateKey = serializeState(state); | ||
@@ -226,5 +243,8 @@ | ||
export function getShortestValuePaths<TContext = DefaultContext>( | ||
export function getShortestValuePaths< | ||
TContext = DefaultContext, | ||
TEvents extends EventObject = EventObject | ||
>( | ||
machine: StateNode<TContext>, | ||
options: GetValueAdjacencyMapOptions<TContext> | ||
options: GetValueAdjacencyMapOptions<TContext, TEvents> | ||
): PathMap { | ||
@@ -231,0 +251,0 @@ if (!machine.states) { |
@@ -8,3 +8,4 @@ import { | ||
DefaultContext, | ||
ActionObject | ||
ActionObject, | ||
StateSchema | ||
} from './types'; | ||
@@ -88,3 +89,8 @@ import { State } from './State'; | ||
// tslint:disable-next-line:max-classes-per-file | ||
export class Interpreter<TContext> { | ||
export class Interpreter< | ||
TContext, | ||
TStateSchema extends StateSchema = any, | ||
TEvents extends EventObject = EventObject | ||
> { | ||
// TODO: fixme | ||
public static defaultOptions: InterpreterOptions = { | ||
@@ -94,5 +100,5 @@ clock: { setTimeout, clearTimeout }, | ||
}; | ||
public state: State<TContext>; | ||
public state: State<TContext, TEvents>; | ||
public extState: TContext; | ||
public eventQueue: EventObject[] = []; | ||
public eventQueue: TEvents[] = []; | ||
public delayedEventsMap: Record<string, number> = {}; | ||
@@ -105,3 +111,3 @@ public listeners: Set<StateListener> = new Set(); | ||
constructor( | ||
public machine: Machine<TContext>, | ||
public machine: Machine<TContext, TStateSchema, TEvents>, | ||
listener?: StateListener, | ||
@@ -123,3 +129,6 @@ options: Partial<InterpreterOptions> = Interpreter.defaultOptions | ||
public static interpret = interpret; | ||
private update(state: State<TContext>, event?: Event): void { | ||
private update( | ||
state: State<TContext, TEvents>, | ||
event?: Event<TEvents> | ||
): void { | ||
this.state = state; | ||
@@ -156,3 +165,6 @@ const { context } = this.state; | ||
public start( | ||
initialState: State<TContext> = this.machine.initialState | ||
initialState: State<TContext, TEvents> = this.machine.initialState as State< | ||
TContext, | ||
TEvents | ||
> | ||
): Interpreter<TContext> { | ||
@@ -172,3 +184,3 @@ this.update(initialState); | ||
} | ||
public send = (event: Event): State<TContext> => { | ||
public send = (event: Event<TEvents>): State<TContext, TEvents> => { | ||
const eventObject = toEventObject(event); | ||
@@ -186,3 +198,3 @@ if (!this.initialized) { | ||
this.extState | ||
); | ||
) as State<TContext, TEvents>; // TODO: fixme | ||
@@ -194,3 +206,3 @@ this.update(nextState, event); | ||
}; | ||
private defer(sendAction: SendAction): number { | ||
private defer(sendAction: SendAction<TContext, TEvents>): number { | ||
return this.clock.setTimeout( | ||
@@ -208,3 +220,3 @@ () => this.send(sendAction.event), | ||
context: TContext, | ||
event?: EventObject | ||
event?: TEvents | ||
): Partial<TContext> | undefined { | ||
@@ -217,3 +229,3 @@ if (action.exec) { | ||
case actionTypes.send: | ||
const sendAction = action as SendAction; | ||
const sendAction = action as SendAction<TContext, TEvents>; | ||
@@ -251,4 +263,5 @@ if (!sendAction.delay) { | ||
private flushEventQueue() { | ||
if (this.eventQueue.length) { | ||
this.send(this.eventQueue.unshift()); | ||
const flushedEvent = this.eventQueue.shift(); | ||
if (flushedEvent) { | ||
this.send(flushedEvent); | ||
} | ||
@@ -258,4 +271,8 @@ } | ||
export function interpret<TContext = DefaultContext>( | ||
machine: Machine<TContext>, | ||
export function interpret< | ||
TContext = DefaultContext, | ||
TStateSchema extends StateSchema = any, | ||
TEvents extends EventObject = EventObject | ||
>( | ||
machine: Machine<TContext, TStateSchema, TEvents>, | ||
listener?: StateListener, | ||
@@ -262,0 +279,0 @@ options?: Partial<InterpreterOptions> |
@@ -5,14 +5,22 @@ import { | ||
DefaultContext, | ||
MachineConfig | ||
MachineConfig, | ||
StateSchema, | ||
EventObject | ||
} from './types'; | ||
import { StateNode } from './StateNode'; | ||
export function Machine<TContext = DefaultContext>( | ||
config: MachineConfig<TContext>, | ||
options?: MachineOptions<TContext>, | ||
export function Machine< | ||
TContext = DefaultContext, | ||
TStateSchema extends StateSchema = any, | ||
TEvents extends EventObject = EventObject | ||
>( | ||
config: MachineConfig<TContext, TStateSchema, TEvents>, | ||
options?: MachineOptions<TContext, TEvents>, | ||
initialContext?: TContext | ||
): Machine<TContext> { | ||
return new StateNode<TContext>(config, options, initialContext) as Machine< | ||
TContext | ||
>; | ||
): Machine<TContext, TStateSchema, TEvents> { | ||
return new StateNode<TContext, TStateSchema, TEvents>( | ||
config, | ||
options, | ||
initialContext | ||
) as Machine<TContext, TStateSchema, TEvents>; | ||
} |
import { SimpleStateNodeConfig } from './types'; | ||
export function toggle( | ||
export function toggle<TEventType extends string = string>( | ||
onState: string, | ||
offState: string, | ||
eventType: string | ||
): Record<string, SimpleStateNodeConfig<any>> { | ||
eventType: TEventType | ||
): Record<string, SimpleStateNodeConfig<any, { type: TEventType }>> { | ||
return { | ||
@@ -15,3 +15,3 @@ [onState]: { | ||
} | ||
}; | ||
} as Record<string, SimpleStateNodeConfig<any, { type: TEventType }>>; | ||
} |
@@ -34,3 +34,3 @@ import { js2xml, xml2js, Element as XMLElement } from 'xml-js'; | ||
attributes: { | ||
target: stateNode.states[stateNode.initial].id | ||
target: stateNode.states[stateNode.initial as string].id | ||
} | ||
@@ -218,3 +218,3 @@ } | ||
case 'raise': | ||
return actions.raise(element.attributes!.event!); | ||
return actions.raise(element.attributes!.event! as string); | ||
case 'assign': | ||
@@ -247,3 +247,3 @@ return actions.assign(xs => { | ||
: 0; | ||
return actions.send(element.attributes!.event!, { | ||
return actions.send(element.attributes!.event! as string, { | ||
delay: numberDelay | ||
@@ -408,4 +408,2 @@ }); | ||
// console.log(dataModelEl, extState); | ||
return Machine( | ||
@@ -412,0 +410,0 @@ { |
@@ -13,10 +13,11 @@ import { | ||
export class State<TContext> implements StateInterface<TContext> { | ||
public static from<T>( | ||
stateValue: State<T> | StateValue, | ||
context: T | ||
): State<T> { | ||
export class State<TContext, TEvents extends EventObject = EventObject> | ||
implements StateInterface<TContext> { | ||
public static from<TC, TE extends EventObject = EventObject>( | ||
stateValue: State<TC, TE> | StateValue, | ||
context: TC | ||
): State<TC, TE> { | ||
if (stateValue instanceof State) { | ||
if (stateValue.context !== context) { | ||
return new State<T>( | ||
return new State<TC, TE>( | ||
stateValue.value, | ||
@@ -36,3 +37,3 @@ context, | ||
return new State( | ||
return new State<TC, TE>( | ||
stateValue, | ||
@@ -48,6 +49,9 @@ context, | ||
} | ||
public static inert<T>(stateValue: State<T> | StateValue, ext: T): State<T> { | ||
public static inert<TC, TE extends EventObject = EventObject>( | ||
stateValue: State<TC> | StateValue, | ||
ext: TC | ||
): State<TC, TE> { | ||
if (stateValue instanceof State) { | ||
if (!stateValue.actions.length) { | ||
return stateValue; | ||
return stateValue as State<TC, TE>; | ||
} | ||
@@ -66,3 +70,3 @@ return new State( | ||
return State.from(stateValue, ext); | ||
return State.from<TC, TE>(stateValue, ext); | ||
} | ||
@@ -81,3 +85,3 @@ | ||
*/ | ||
public events: EventObject[] = [] | ||
public events: TEvents[] = [] | ||
) {} | ||
@@ -100,5 +104,5 @@ | ||
public get changed(): boolean { | ||
public get changed(): boolean | undefined { | ||
if (!this.history) { | ||
return false; | ||
return undefined; | ||
} | ||
@@ -108,3 +112,3 @@ | ||
!!this.actions.length || | ||
(typeof this.history.value !== this.value | ||
(typeof this.history.value !== typeof this.value | ||
? true | ||
@@ -111,0 +115,0 @@ : typeof this.value === 'string' |
@@ -19,3 +19,2 @@ import { | ||
Action, | ||
EventType, | ||
TransitionConfig, | ||
@@ -33,3 +32,2 @@ ActivityMap, | ||
HistoryValue, | ||
DefaultData, | ||
DefaultContext, | ||
@@ -45,3 +43,10 @@ StateNodeDefinition, | ||
Activity, | ||
StateNodeValueTree | ||
StateNodeValueTree, | ||
StateSchema, | ||
TransitionsDefinition, | ||
StatesDefinition, | ||
StateNodesConfig, | ||
ActionTypes, | ||
AnyEvent, | ||
RaisedEvent | ||
} from './types'; | ||
@@ -74,7 +79,11 @@ import { matchesState } from './matchesState'; | ||
const isStateId = (str: string) => str[0] === STATE_IDENTIFIER; | ||
const createDefaultOptions = <TContext>(): MachineOptions<TContext> => ({ | ||
const createDefaultOptions = <TContext>(): MachineOptions<TContext, any> => ({ | ||
guards: EMPTY_OBJECT | ||
}); | ||
class StateNode<TContext = DefaultContext, TData = DefaultData> { | ||
class StateNode< | ||
TContext = DefaultContext, | ||
TStateSchema extends StateSchema = any, | ||
TEvents extends AnyEvent<EventObject> = AnyEvent<EventObject> | ||
> { | ||
public key: string; | ||
@@ -84,6 +93,6 @@ public id: string; | ||
public path: string[]; | ||
public initial?: string; | ||
public initial?: keyof TStateSchema['states']; | ||
public parallel: boolean; | ||
public transient: boolean; | ||
public states: Record<string, StateNode<TContext>>; | ||
public states: StateNodesConfig<TContext, TStateSchema, TEvents>; | ||
public history: false | 'shallow' | 'deep'; | ||
@@ -96,3 +105,3 @@ public onEntry: Array<Action<TContext>>; | ||
public machine: StateNode<TContext>; | ||
public data: TData; | ||
public data?: TStateSchema extends { data: infer D } ? D : any; | ||
public delimiter: string; | ||
@@ -102,3 +111,3 @@ public order: number; | ||
private __cache = { | ||
events: undefined as EventType[] | undefined, | ||
events: undefined as Array<TEvents['type']> | undefined, | ||
relativeValue: new Map() as Map<StateNode<TContext>, StateValue>, | ||
@@ -111,6 +120,6 @@ initialState: undefined as StateValue | undefined | ||
constructor( | ||
private _config: StateNodeConfig<TContext>, | ||
public options: Readonly<MachineOptions<TContext>> = createDefaultOptions< | ||
TContext | ||
>(), | ||
private _config: StateNodeConfig<TContext, TStateSchema, TEvents>, | ||
public options: Readonly< | ||
MachineOptions<TContext, TEvents> | ||
> = createDefaultOptions<TContext>(), | ||
/** | ||
@@ -146,5 +155,5 @@ * The initial extended state | ||
this.states = (_config.states | ||
? mapValues<StateNodeConfig<TContext>, StateNode<TContext>>( | ||
? mapValues( | ||
_config.states, | ||
(stateConfig, key, _, i) => { | ||
(stateConfig: StateNodeConfig<TContext, any, TEvents>, key, _, i) => { | ||
const stateNode = new StateNode({ | ||
@@ -163,3 +172,3 @@ ...stateConfig, | ||
) | ||
: EMPTY_OBJECT) as Record<string, StateNode<TContext>>; | ||
: EMPTY_OBJECT) as StateNodesConfig<TContext, TStateSchema, TEvents>; | ||
@@ -180,3 +189,7 @@ // History config | ||
} | ||
public get definition(): StateNodeDefinition<TContext, TData> { | ||
public get definition(): StateNodeDefinition< | ||
TContext, | ||
TStateSchema, | ||
TEvents | ||
> { | ||
return { | ||
@@ -188,3 +201,6 @@ id: this.id, | ||
history: this.history, | ||
states: mapValues(this.states, state => state.definition), | ||
states: mapValues( | ||
this.states, | ||
(state: StateNode<TContext, any, TEvents>) => state.definition | ||
) as StatesDefinition<TContext, TStateSchema, TEvents>, | ||
on: this.on, | ||
@@ -199,3 +215,3 @@ onEntry: this.onEntry, | ||
} | ||
public get config(): StateNodeConfig<TContext> { | ||
public get config(): StateNodeConfig<TContext, TStateSchema, TEvents> { | ||
const { parent, ...config } = this._config; | ||
@@ -205,6 +221,6 @@ | ||
} | ||
public get on(): Record<string, Array<TransitionDefinition<TContext>>> { | ||
public get on(): TransitionsDefinition<TContext, TEvents> { | ||
return this.formatTransitions(); | ||
} | ||
public get after(): Array<DelayedTransitionDefinition<TContext>> { | ||
public get after(): Array<DelayedTransitionDefinition<TContext, TEvents>> { | ||
const { | ||
@@ -230,3 +246,4 @@ config: { after: afterConfig } | ||
number | string, | ||
TransitionConfig<TContext> | Array<TransitionConfig<TContext>> | ||
| TransitionConfig<TContext, TEvents> | ||
| Array<TransitionConfig<TContext, TEvents>> | ||
>)[delayKey]; | ||
@@ -256,3 +273,3 @@ const delay = +delayKey; | ||
public getStateNodes( | ||
state: StateValue | State<TContext> | ||
state: StateValue | State<TContext, TEvents> | ||
): Array<StateNode<TContext>> { | ||
@@ -271,3 +288,3 @@ if (!state) { | ||
return initialStateValue | ||
? this.getStateNodes({ [stateValue]: initialStateValue }) | ||
? this.getStateNodes({ [stateValue]: initialStateValue } as StateValue) | ||
: [this.states[stateValue]]; | ||
@@ -294,4 +311,4 @@ } | ||
} | ||
public handles(event: Event): boolean { | ||
const eventType = getEventType(event); | ||
public handles(event: Event<TEvents>): boolean { | ||
const eventType = getEventType<TEvents>(event); | ||
@@ -302,4 +319,4 @@ return this.events.indexOf(eventType) !== -1; | ||
stateValue: string, | ||
state: State<TContext>, | ||
eventObject: EventObject, | ||
state: State<TContext, TEvents>, | ||
eventObject: TEvents, | ||
context?: TContext | ||
@@ -338,4 +355,4 @@ ): StateTransition<TContext> { | ||
stateValue: StateValueMap, | ||
state: State<TContext>, | ||
eventObject: EventObject, | ||
state: State<TContext, TEvents>, | ||
eventObject: TEvents, | ||
context?: TContext | ||
@@ -384,4 +401,4 @@ ): StateTransition<TContext> { | ||
stateValue: StateValueMap, | ||
state: State<TContext>, | ||
eventObject: EventObject, | ||
state: State<TContext, TEvents>, | ||
eventObject: TEvents, | ||
context?: TContext | ||
@@ -534,4 +551,4 @@ ): StateTransition<TContext> { | ||
stateValue: StateValue, | ||
state: State<TContext>, | ||
event: EventObject, | ||
state: State<TContext, TEvents>, | ||
event: TEvents, | ||
context?: TContext | ||
@@ -553,4 +570,4 @@ ): StateTransition<TContext> { | ||
private next( | ||
state: State<TContext>, | ||
eventObject: EventObject, | ||
state: State<TContext, TEvents>, | ||
eventObject: TEvents, | ||
context?: TContext | ||
@@ -575,3 +592,3 @@ ): StateTransition<TContext> { | ||
let nextStateStrings: string[] = []; | ||
let selectedTransition: TransitionConfig<TContext>; | ||
let selectedTransition: unknown; | ||
@@ -583,3 +600,3 @@ for (const candidate of candidates) { | ||
// actions: transitionActions | ||
} = candidate as TransitionConfig<TContext>; | ||
} = candidate as TransitionConfig<TContext, TEvents>; | ||
const resolvedContext = context || (EMPTY_OBJECT as TContext); | ||
@@ -639,3 +656,4 @@ | ||
nextStateNode, | ||
!!selectedTransition.internal | ||
!!(selectedTransition as TransitionDefinition<TContext, TEvents>) | ||
.internal | ||
); | ||
@@ -748,8 +766,8 @@ | ||
private evaluateCond( | ||
condition: Condition<TContext>, | ||
condition: Condition<TContext, TEvents>, | ||
context: TContext, | ||
eventObject: EventObject, | ||
eventObject: TEvents, | ||
interimState: StateValue | ||
): boolean { | ||
let condFn: ConditionPredicate<TContext>; | ||
let condFn: ConditionPredicate<TContext, TEvents>; | ||
const { guards } = this.machine.options; | ||
@@ -907,6 +925,6 @@ | ||
public transition( | ||
state: StateValue | State<TContext>, | ||
event: Event, | ||
state: StateValue | State<TContext, TEvents>, | ||
event: Event<TEvents>, | ||
context?: TContext | ||
): State<TContext> { | ||
): State<TContext, TEvents> { | ||
const resolvedStateValue = | ||
@@ -932,3 +950,3 @@ typeof state === 'string' | ||
const currentState = State.from<TContext>( | ||
const currentState = State.from<TContext, TEvents>( | ||
resolvedStateValue, | ||
@@ -949,5 +967,5 @@ resolvedContext | ||
stateTransition: StateTransition<TContext>, | ||
currentState: State<TContext>, | ||
event?: EventObject | ||
): State<TContext> { | ||
currentState: State<TContext, TEvents>, | ||
event?: TEvents | ||
): State<TContext, TEvents> { | ||
const historyValue = currentState.historyValue | ||
@@ -959,10 +977,12 @@ ? currentState.historyValue | ||
try { | ||
this.ensureValidPaths(stateTransition.paths); | ||
} catch (e) { | ||
throw new Error( | ||
`Event '${ | ||
event ? event.type : 'none' | ||
}' leads to an invalid configuration: ${e.message}` | ||
); | ||
if (process.env.NODE_ENV !== 'production') { | ||
try { | ||
this.ensureValidPaths(stateTransition.paths); | ||
} catch (e) { | ||
throw new Error( | ||
`Event '${ | ||
event ? event.type : 'none' | ||
}' leads to an invalid configuration: ${e.message}` | ||
); | ||
} | ||
} | ||
@@ -980,3 +1000,3 @@ | ||
(action.type === actionTypes.raise || action.type === actionTypes.null) | ||
) as Array<ActionObject<TContext>>; | ||
) as Array<RaisedEvent<TEvents> | { type: ActionTypes.Null }>; | ||
@@ -992,3 +1012,3 @@ const nonEventActions = actions.filter( | ||
action => typeof action === 'object' && action.type === actionTypes.assign | ||
) as Array<AssignAction<TContext>>; | ||
) as Array<AssignAction<TContext, TEvents>>; | ||
@@ -1002,3 +1022,6 @@ const updatedContext = currentState.context | ||
if (typeof assignment === 'function') { | ||
partialUpdate = assignment(acc, event || { type: 'xstate.init' }); | ||
partialUpdate = assignment( | ||
acc, | ||
event || ({ type: ActionTypes.Init } as TEvents) | ||
); | ||
} else { | ||
@@ -1036,3 +1059,3 @@ Object.keys(assignment).forEach(key => { | ||
const nextState = stateTransition.value | ||
? new State<TContext>( | ||
? new State<TContext, TEvents>( | ||
stateTransition.value, | ||
@@ -1047,3 +1070,3 @@ updatedContext, | ||
data, | ||
raisedEvents | ||
raisedEvents as TEvents[] | ||
) | ||
@@ -1054,7 +1077,9 @@ : undefined; | ||
// Unchanged state should be returned with no actions | ||
return State.inert<TContext>(currentState, updatedContext); | ||
return State.inert<TContext, TEvents>(currentState, updatedContext); | ||
} | ||
// Dispose of previous histories to prevent memory leaks | ||
delete currentState.history; | ||
// Dispose of penultimate histories to prevent memory leaks | ||
if (currentState.history) { | ||
delete currentState.history.history; | ||
} | ||
@@ -1067,3 +1092,5 @@ let maybeNextState = nextState; | ||
maybeNextState, | ||
raisedEvent.type === actionTypes.null ? NULL_EVENT : raisedEvent.event, | ||
raisedEvent.type === actionTypes.null | ||
? NULL_EVENT | ||
: (raisedEvent as RaisedEvent<TEvents>).event, | ||
maybeNextState.context | ||
@@ -1198,3 +1225,3 @@ ); | ||
return { | ||
[key]: mapFilterValues( | ||
[key]: mapFilterValues<StateNode<TContext>, StateValue>( | ||
this.states, | ||
@@ -1213,2 +1240,3 @@ stateNode => stateNode.resolvedStateValue[stateNode.key], | ||
return { | ||
// @ts-ignore TODO: fixme | ||
[key]: this.states[this.initial].resolvedStateValue | ||
@@ -1254,3 +1282,3 @@ }; | ||
context: TContext = this.machine.context! | ||
): State<TContext> { | ||
): State<TContext, TEvents> { | ||
const activityMap: ActivityMap = {}; | ||
@@ -1265,3 +1293,3 @@ const actions: Array<Action<TContext>> = []; | ||
stateNode.activities.forEach(activity => { | ||
activityMap[getEventType(activity)] = true; | ||
activityMap[getEventType(activity) as string] = true; // TODO: fixme | ||
actions.push(start(activity)); | ||
@@ -1281,3 +1309,3 @@ }); | ||
action => typeof action === 'object' && action.type === actionTypes.assign | ||
) as Array<AssignAction<TContext>>; | ||
) as Array<AssignAction<TContext, TEvents>>; | ||
@@ -1291,3 +1319,3 @@ const updatedContext = context | ||
if (typeof assignment === 'function') { | ||
partialUpdate = assignment(acc, { type: 'init' }); | ||
partialUpdate = assignment(acc, { type: 'init' } as TEvents); // TODO: fix init | ||
} else { | ||
@@ -1299,3 +1327,3 @@ Object.keys(assignment).forEach(key => { | ||
typeof propAssignment === 'function' | ||
? propAssignment(acc, { type: 'init' }) | ||
? propAssignment(acc, { type: 'init' }) // TODO: fix init | ||
: propAssignment; | ||
@@ -1309,3 +1337,3 @@ }); | ||
const initialNextState = new State<TContext>( | ||
const initialNextState = new State<TContext, TEvents>( | ||
stateValue, | ||
@@ -1332,3 +1360,3 @@ updatedContext, | ||
} | ||
public get initialState(): State<TContext> { | ||
public get initialState(): State<TContext, TEvents> { | ||
const { initialStateValue } = this; | ||
@@ -1360,3 +1388,6 @@ | ||
if (this.history) { | ||
const historyConfig = this.config as HistoryStateNodeConfig<TContext>; | ||
const historyConfig = this.config as HistoryStateNodeConfig< | ||
TContext, | ||
TEvents | ||
>; | ||
if (historyConfig.target && typeof historyConfig.target === 'string') { | ||
@@ -1516,3 +1547,3 @@ target = isStateId(historyConfig.target) | ||
current: relativeStateValue || this.initialStateValue, | ||
states: mapFilterValues( | ||
states: mapFilterValues<StateNode<TContext>, HistoryValue | undefined>( | ||
this.states, | ||
@@ -1581,3 +1612,3 @@ (stateNode, key) => { | ||
Object.keys(this.states).map(stateKey => { | ||
return this.states[stateKey].stateIds; | ||
return (this.states[stateKey] as StateNode<TContext>).stateIds; | ||
}) | ||
@@ -1587,3 +1618,3 @@ ); | ||
} | ||
public get events(): EventType[] { | ||
public get events(): Array<TEvents['type']> { | ||
if (this.__cache.events) { | ||
@@ -1610,5 +1641,5 @@ return this.__cache.events; | ||
target: string | string[] | undefined, | ||
transitionConfig: TransitionConfig<TContext> | undefined, | ||
transitionConfig: TransitionConfig<TContext, TEvents> | undefined, | ||
event: string | ||
): TransitionDefinition<TContext> { | ||
): TransitionDefinition<TContext, TEvents> { | ||
let internal = transitionConfig ? transitionConfig.internal : false; | ||
@@ -1657,12 +1688,9 @@ | ||
} | ||
private formatTransitions(): Record< | ||
string, | ||
Array<TransitionDefinition<TContext>> | ||
> { | ||
private formatTransitions(): TransitionsDefinition<TContext, TEvents> { | ||
const onConfig = this.config.on || EMPTY_OBJECT; | ||
const delayedTransitions = this.after; | ||
const formattedTransitions: Record< | ||
string, | ||
Array<TransitionDefinition<TContext>> | ||
const formattedTransitions: TransitionsDefinition< | ||
TContext, | ||
TEvents | ||
> = mapValues(onConfig, (value, event) => { | ||
@@ -1703,3 +1731,3 @@ if (value === undefined) { | ||
this.formatTransition( | ||
(value as TransitionConfig<TContext>).target, | ||
(value as TransitionConfig<TContext, TEvents>).target, | ||
value, | ||
@@ -1709,3 +1737,3 @@ event | ||
]; | ||
}); | ||
}) as TransitionsDefinition<TContext, TEvents>; | ||
@@ -1715,3 +1743,8 @@ delayedTransitions.forEach(delayedTransition => { | ||
formattedTransitions[delayedTransition.event] || []; | ||
formattedTransitions[delayedTransition.event].push(delayedTransition); | ||
formattedTransitions[delayedTransition.event].push( | ||
delayedTransition as TransitionDefinition< | ||
TContext, | ||
TEvents | EventObject | ||
> | ||
); | ||
}); | ||
@@ -1718,0 +1751,0 @@ |
343
src/types.ts
@@ -5,12 +5,12 @@ import { StateNode } from './StateNode'; | ||
export type EventType = string | number; | ||
export type ActionType = string | number; | ||
export type ActionType = string; | ||
export type MetaObject = Record<string, any>; | ||
export interface EventObject { | ||
type: EventType; | ||
export interface EventObject extends Record<string, any> { | ||
type: string | number; | ||
id?: string | number; | ||
[key: string]: any; | ||
} | ||
export interface ActionObject<TContext> extends Record<string, any> { | ||
type: ActionType; | ||
type: string; | ||
exec?: ActionFunction<TContext>; | ||
@@ -20,6 +20,5 @@ } | ||
export type DefaultContext = Record<string, any> | undefined; | ||
export type DefaultData = Record<string, any>; | ||
export type Event = EventType | EventObject; | ||
export type InternalEvent = EventType | EventObject; | ||
export type Event<TEvents extends EventObject> = TEvents['type'] | TEvents; | ||
export interface ActionFunction<TContext> { | ||
@@ -29,7 +28,6 @@ (context: TContext, event?: EventObject): any | void; | ||
} | ||
export type InternalAction<TContext> = SendAction | AssignAction<TContext>; | ||
// export type InternalAction<TContext> = SendAction | AssignAction<TContext>; | ||
export type Action<TContext> = | ||
| ActionType | ||
| ActionObject<TContext> | ||
| InternalAction<TContext> | ||
| ActionFunction<TContext>; | ||
@@ -54,12 +52,14 @@ export type StateKey = string | State<any>; | ||
export type ConditionPredicate<TContext> = ( | ||
export type ConditionPredicate<TContext, TEvents extends EventObject> = ( | ||
context: TContext, | ||
event: EventObject, | ||
event: TEvents, | ||
microstepState: StateValue | ||
) => boolean; | ||
export type Condition<TContext> = string | ConditionPredicate<TContext>; | ||
export type Condition<TContext, TEvents extends EventObject> = | ||
| string | ||
| ConditionPredicate<TContext, TEvents>; | ||
export interface TransitionConfig<TContext = DefaultContext> { | ||
cond?: Condition<TContext>; | ||
export interface TransitionConfig<TContext, TEvents extends EventObject> { | ||
cond?: Condition<TContext, TEvents>; | ||
actions?: SingleOrArray<Action<TContext>>; | ||
@@ -71,15 +71,16 @@ in?: StateValue; | ||
export interface TargetTransitionConfig<TContext = DefaultContext> | ||
extends TransitionConfig<TContext> { | ||
export interface TargetTransitionConfig<TContext, TEvents extends EventObject> | ||
extends TransitionConfig<TContext, TEvents> { | ||
target: string | string[] | undefined; | ||
} | ||
export type ConditionalTransitionConfig<TContext = DefaultContext> = Array< | ||
TransitionConfig<TContext> | ||
>; | ||
export type ConditionalTransitionConfig< | ||
TContext = DefaultContext, | ||
TEvents extends EventObject = EventObject | ||
> = Array<TransitionConfig<TContext, TEvents>>; | ||
export type Transition<TContext = DefaultContext> = | ||
export type Transition<TContext, TEvents extends EventObject = EventObject> = | ||
| string | ||
| TransitionConfig<TContext> | ||
| ConditionalTransitionConfig<TContext>; | ||
| TransitionConfig<TContext, TEvents> | ||
| ConditionalTransitionConfig<TContext, TEvents>; | ||
@@ -94,3 +95,3 @@ export interface ActivityConfig<TContext> { | ||
export interface ActivityDefinition<TContext> extends ActionObject<TContext> { | ||
type: ActionType; | ||
type: string; | ||
start?: ActionObject<TContext>; | ||
@@ -105,13 +106,15 @@ stop?: ActionObject<TContext>; | ||
export interface DelayedTransitionConfig<TContext> | ||
extends TransitionConfig<TContext> { | ||
export interface DelayedTransitionConfig<TContext, TEvents extends EventObject> | ||
extends TransitionConfig<TContext, TEvents> { | ||
delay: number; | ||
} | ||
export type DelayedTransitions<TContext> = | ||
export type DelayedTransitions<TContext, TEvents extends EventObject> = | ||
| Record< | ||
string, | ||
string | TransitionConfig<TContext> | Array<TransitionConfig<TContext>> | ||
| string | ||
| TransitionConfig<TContext, TEvents> | ||
| Array<TransitionConfig<TContext, TEvents>> | ||
> | ||
| Array<DelayedTransitionConfig<TContext>>; | ||
| Array<DelayedTransitionConfig<TContext, TEvents>>; | ||
@@ -127,5 +130,69 @@ export type StateTypes = | ||
export interface StateNodeConfig<TContext = DefaultContext, TData = any> { | ||
export type StateNodesConfig< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> = { | ||
[K in keyof TStateSchema['states']]: StateNode< | ||
TContext, | ||
TStateSchema['states'][K], | ||
TEvents | ||
> | ||
}; | ||
export type StatesConfig< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> = { | ||
[K in keyof TStateSchema['states']]: StateNodeConfig< | ||
TContext, | ||
TStateSchema['states'][K], | ||
TEvents | ||
> | ||
}; | ||
export type StatesDefinition< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> = { | ||
[K in keyof TStateSchema['states']]: StateNodeDefinition< | ||
TContext, | ||
TStateSchema['states'][K], | ||
TEvents | ||
> | ||
}; | ||
export type TransitionsConfig<TContext, TEvents extends EventObject> = { | ||
[K in TEvents['type'] | BuiltInEvent<TEvents>['type']]?: | ||
| string | ||
| TransitionConfig< | ||
TContext, | ||
TEvents extends { type: K } ? TEvents : EventObject | ||
> | ||
| Array< | ||
TransitionConfig< | ||
TContext, | ||
TEvents extends { type: K } ? TEvents : EventObject | ||
> | ||
> | ||
}; | ||
export type TransitionsDefinition<TContext, TEvents extends EventObject> = { | ||
[K in TEvents['type']]: Array< | ||
TransitionDefinition< | ||
TContext, | ||
TEvents extends { type: K } ? TEvents : EventObject | ||
> | ||
> | ||
}; | ||
export interface StateNodeConfig< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> { | ||
key?: string; | ||
initial?: string | undefined; | ||
initial?: keyof TStateSchema['states'] | undefined; | ||
parallel?: boolean | undefined; | ||
@@ -139,11 +206,12 @@ type?: StateTypes; | ||
history?: 'shallow' | 'deep' | boolean | undefined; | ||
states?: Record<string, StateNodeConfig<TContext>> | undefined; | ||
on?: Record<string, Transition<TContext> | undefined>; | ||
states?: StatesConfig<TContext, TStateSchema, TEvents> | undefined; | ||
// on?: Record<string, Transition<TContext> | undefined>; | ||
on?: TransitionsConfig<TContext, TEvents>; | ||
onEntry?: SingleOrArray<Action<TContext>>; | ||
onExit?: SingleOrArray<Action<TContext>>; | ||
after?: DelayedTransitions<TContext>; | ||
after?: DelayedTransitions<TContext, TEvents>; | ||
activities?: SingleOrArray<Activity<TContext>>; | ||
parent?: StateNode<TContext>; | ||
strict?: boolean | undefined; | ||
data?: TData; | ||
data?: TStateSchema extends { data: infer D } ? D : any; | ||
id?: string | undefined; | ||
@@ -154,20 +222,23 @@ delimiter?: string; | ||
export interface StateNodeDefinition<TContext = DefaultContext, TData = any> | ||
extends StateNodeConfig<TContext> { | ||
export interface StateNodeDefinition< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> extends StateNodeConfig<TContext, TStateSchema, TEvents> { | ||
id: string; | ||
key: string; | ||
type: StateTypes; | ||
initial: string | undefined; | ||
initial: StateNodeConfig<TContext, TStateSchema, TEvents>['initial']; | ||
history: boolean | 'shallow' | 'deep' | undefined; | ||
states: Record<string, StateNodeDefinition<TContext>>; | ||
on: Record<string, Array<TransitionDefinition<TContext>>>; | ||
states: StatesDefinition<TContext, TStateSchema, TEvents>; | ||
on: TransitionsDefinition<TContext, TEvents>; | ||
onEntry: Array<Action<TContext>>; | ||
onExit: Array<Action<TContext>>; | ||
after: Array<DelayedTransitionDefinition<TContext>>; | ||
after: Array<DelayedTransitionDefinition<TContext, TEvents>>; | ||
activities: Array<ActivityDefinition<TContext>>; | ||
data: TData; | ||
data: any; | ||
order: number; | ||
} | ||
export interface SimpleStateNodeConfig<TContext> | ||
extends StateNodeConfig<TContext> { | ||
export interface SimpleStateNodeConfig<TContext, TEvents extends EventObject> | ||
extends StateNodeConfig<TContext, never, TEvents> { | ||
initial?: undefined; | ||
@@ -178,4 +249,4 @@ parallel?: false | undefined; | ||
export interface HistoryStateNodeConfig<TContext> | ||
extends SimpleStateNodeConfig<TContext> { | ||
export interface HistoryStateNodeConfig<TContext, TEvents extends EventObject> | ||
extends SimpleStateNodeConfig<TContext, TEvents> { | ||
history: 'shallow' | 'deep' | true; | ||
@@ -185,12 +256,18 @@ target: StateValue | undefined; | ||
export interface CompoundStateNodeConfig<TContext> | ||
extends StateNodeConfig<TContext> { | ||
initial?: string; | ||
export interface CompoundStateNodeConfig< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> extends StateNodeConfig<TContext, TStateSchema, TEvents> { | ||
parallel?: boolean; | ||
states: Record<string, StateNodeConfig<TContext>>; | ||
states: StateNodeConfig<TContext, TStateSchema, TEvents>['states']; | ||
} | ||
export type SimpleOrCompoundStateNodeConfig<TContext> = | ||
| SimpleStateNodeConfig<TContext> | ||
| CompoundStateNodeConfig<TContext>; | ||
export type SimpleOrCompoundStateNodeConfig< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> = | ||
| SimpleStateNodeConfig<TContext, TEvents> | ||
| CompoundStateNodeConfig<TContext, TStateSchema, TEvents>; | ||
@@ -201,16 +278,26 @@ export type ActionFunctionMap<TContext> = Record< | ||
>; | ||
export interface MachineOptions<TContext> { | ||
guards?: Record<string, ConditionPredicate<TContext>>; | ||
export interface MachineOptions<TContext, TEvents extends EventObject> { | ||
guards?: Record<string, ConditionPredicate<TContext, TEvents>>; | ||
actions?: ActionFunctionMap<TContext>; | ||
activities?: Record<string, ActivityConfig<TContext>>; | ||
} | ||
export type MachineConfig<TContext> = CompoundStateNodeConfig<TContext>; | ||
export type MachineConfig< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> = CompoundStateNodeConfig<TContext, TStateSchema, TEvents>; | ||
export interface StandardMachineConfig<TContext> | ||
extends CompoundStateNodeConfig<TContext> {} | ||
export interface StandardMachineConfig< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> extends CompoundStateNodeConfig<TContext, TStateSchema, TEvents> {} | ||
export interface ParallelMachineConfig<TContext> | ||
extends CompoundStateNodeConfig<TContext> { | ||
initial?: string | undefined; | ||
parallel?: true; | ||
export interface ParallelMachineConfig< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> extends CompoundStateNodeConfig<TContext, TStateSchema, TEvents> { | ||
initial?: undefined; | ||
type?: 'parallel'; | ||
@@ -224,30 +311,2 @@ } | ||
// export interface IStateNode<TContext = DefaulTContext> { | ||
// key: string; | ||
// id: string; | ||
// initial: string | undefined; | ||
// parallel: boolean; | ||
// transient: boolean; | ||
// history: false | 'shallow' | 'deep'; | ||
// states: Record<string, IStateNode<TContext = DefaulTContext>>; | ||
// on?: Record<string, Transition<TContext = DefaulTContext>>; | ||
// onEntry?: Action | Action[]; | ||
// onExit?: Action | Action[]; | ||
// parent: StateNode | undefined; | ||
// machine: Machine; | ||
// config: StateNodeConfig<TContext = DefaulTContext>; | ||
// } | ||
export interface ComplexStateNode<TContext> extends StateNode<TContext> { | ||
initial: string; | ||
history: false; | ||
} | ||
export interface LeafStateNode<TContext> extends StateNode<TContext> { | ||
initial: never; | ||
parallel: never; | ||
states: never; | ||
parent: StateNode<TContext>; | ||
} | ||
export interface HistoryStateNode<TContext> extends StateNode<TContext> { | ||
@@ -258,17 +317,11 @@ history: 'shallow' | 'deep'; | ||
export interface Machine<TContext = DefaultContext> | ||
extends StateNode<TContext> { | ||
export interface Machine< | ||
TContext, | ||
TStateSchema extends StateSchema, | ||
TEvents extends EventObject | ||
> extends StateNode<TContext, TStateSchema, TEvents> { | ||
id: string; | ||
states: Record<string, StateNode<TContext>>; | ||
states: StateNode<TContext, TStateSchema, TEvents>['states']; | ||
} | ||
export interface StandardMachine<TContext> extends Machine<TContext> { | ||
initial: string; | ||
parallel: false; | ||
} | ||
export interface ParallelMachine<TContext> extends Machine<TContext> { | ||
initial: undefined; | ||
parallel: true; | ||
} | ||
export interface ActionMap<TContext> { | ||
@@ -288,7 +341,2 @@ onEntry: Array<Action<TContext>>; | ||
} | ||
export type MaybeStateValueActionsTuple<TContext> = [ | ||
StateValue | undefined, | ||
ActionMap<TContext>, | ||
ActivityMap | undefined | ||
]; | ||
@@ -316,9 +364,22 @@ // tslint:disable-next-line:class-name | ||
Cancel = 'xstate.cancel', | ||
Null = 'xstate.null', | ||
Null = '', | ||
Assign = 'xstate.assign', | ||
After = 'xstate.after', | ||
DoneState = 'done.state', | ||
Log = 'xstate.log' | ||
Log = 'xstate.log', | ||
Init = 'xstate.init' | ||
} | ||
export interface RaisedEvent<TEvents extends EventObject> { | ||
type: ActionTypes.Raise; | ||
event: TEvents; | ||
} | ||
export type BuiltInEvent<TEvents extends EventObject> = | ||
| { type: ActionTypes.Null } | ||
| RaisedEvent<TEvents> | ||
| { type: ActionTypes.Init }; | ||
export type AnyEvent<TEvents extends EventObject> = | ||
| TEvents | ||
| BuiltInEvent<TEvents>; | ||
export interface ActivityActionObject<TContext> extends ActionObject<TContext> { | ||
@@ -330,4 +391,5 @@ type: ActionTypes.Start | ActionTypes.Stop; | ||
export interface SendAction extends ActionObject<any> { | ||
event: EventObject; | ||
export interface SendAction<TContext, TEvents extends EventObject> | ||
extends ActionObject<TContext> { | ||
event: TEvents; | ||
delay?: number; | ||
@@ -345,11 +407,11 @@ id: string | number; | ||
export type Assigner<TContext> = ( | ||
export type Assigner<TContext, TEvents extends EventObject> = ( | ||
extState: TContext, | ||
event: EventObject | ||
event: TEvents | ||
) => Partial<TContext>; | ||
export type PropertyAssigner<TContext> = Partial< | ||
export type PropertyAssigner<TContext, TEvents extends EventObject> = Partial< | ||
{ | ||
[K in keyof TContext]: | ||
| ((extState: TContext, event: EventObject) => TContext[K]) | ||
| ((extState: TContext, event: TEvents) => TContext[K]) | ||
| TContext[K] | ||
@@ -359,8 +421,9 @@ } | ||
export interface AssignAction<TContext> extends ActionObject<TContext> { | ||
assignment: Assigner<TContext> | PropertyAssigner<TContext>; | ||
export interface AssignAction<TContext, TEvents extends EventObject> | ||
extends ActionObject<TContext> { | ||
assignment: Assigner<TContext, TEvents> | PropertyAssigner<TContext, TEvents>; | ||
} | ||
export interface TransitionDefinition<TContext> | ||
extends TransitionConfig<TContext> { | ||
export interface TransitionDefinition<TContext, TEvents extends EventObject> | ||
extends TransitionConfig<TContext, TEvents> { | ||
actions: Array<Action<TContext>>; | ||
@@ -371,22 +434,31 @@ event: string; | ||
export interface DelayedTransitionDefinition<TContext> | ||
extends TransitionDefinition<TContext> { | ||
export interface DelayedTransitionDefinition< | ||
TContext, | ||
TEvents extends EventObject | ||
> extends TransitionDefinition<TContext, TEvents> { | ||
delay: number; | ||
} | ||
export interface Edge<TContext> { | ||
event: string; | ||
export interface Edge< | ||
TContext, | ||
TEvents extends EventObject, | ||
TEventType extends TEvents['type'] = string | ||
> { | ||
event: TEventType; | ||
source: StateNode<TContext>; | ||
target: StateNode<TContext>; | ||
cond?: Condition<TContext>; | ||
cond?: Condition<TContext, TEvents & { type: TEventType }>; | ||
actions: Array<Action<TContext>>; | ||
meta?: MetaObject; | ||
transition: TransitionDefinition<TContext>; | ||
transition: TransitionDefinition<TContext, TEvents>; | ||
} | ||
export interface NodesAndEdges<TContext> { | ||
export interface NodesAndEdges<TContext, TEvents extends EventObject> { | ||
nodes: StateNode[]; | ||
edges: Array<Edge<TContext>>; | ||
edges: Array<Edge<TContext, TEvents, TEvents['type']>>; | ||
} | ||
export interface Segment<TContext = DefaultContext> { | ||
export interface Segment< | ||
TContext = DefaultContext, | ||
TEvents extends EventObject = EventObject | ||
> { | ||
/** | ||
@@ -401,3 +473,3 @@ * From state | ||
*/ | ||
event: Event; | ||
event: Event<TEvents>; | ||
} | ||
@@ -442,3 +514,3 @@ | ||
TContext = DefaultContext, | ||
TData = DefaultData | ||
TEvents extends EventObject = EventObject | ||
> { | ||
@@ -449,6 +521,13 @@ value: StateValue; | ||
activities: ActivityMap; | ||
data: TData; | ||
events: EventObject[]; | ||
data: any; | ||
events: TEvents[]; | ||
context: TContext; | ||
toStrings: () => string[]; | ||
} | ||
export interface StateSchema { | ||
data?: any; | ||
states?: { | ||
[key: string]: StateSchema; | ||
}; | ||
} |
import { State } from './State'; | ||
import { Event, StateValue, EventType, ActionType, Action } from './types'; | ||
import { Event, StateValue, ActionType, Action, EventObject } from './types'; | ||
export function getEventType(event: Event): EventType { | ||
export function getEventType<TEvents extends EventObject = EventObject>( | ||
event: Event<TEvents> | ||
): TEvents['type'] { | ||
try { | ||
return typeof event === 'string' || typeof event === 'number' | ||
? `${event}` | ||
: event.type; | ||
: (event as TEvents).type; | ||
} catch (e) { | ||
@@ -10,0 +12,0 @@ throw new Error( |
@@ -69,3 +69,7 @@ import { assert } from 'chai'; | ||
const condMachine = Machine<{ id: string }>({ | ||
const condMachine = Machine< | ||
{ id: string }, | ||
any, | ||
{ type: 'EVENT'; id: string } | { type: 'STATE' } | ||
>({ | ||
key: 'cond', | ||
@@ -72,0 +76,0 @@ initial: 'pending', |
@@ -5,2 +5,6 @@ import { assert } from 'chai'; | ||
describe('guard conditions', () => { | ||
// type LightMachineEvents = | ||
// | { type: 'TIMER'; elapsed: number } | ||
// | { type: 'EMERGENCY'; isEmergency: boolean }; | ||
const lightMachine = Machine<{ elapsed: number }>( | ||
@@ -7,0 +11,0 @@ { |
@@ -70,4 +70,5 @@ import { assert } from 'chai'; | ||
const offState = historyMachine.transition(onSecondState, 'H_POWER'); | ||
const nextState = historyMachine.transition(offState, 'H_POWER'); | ||
assert.isUndefined(nextState.history!.history); | ||
const onState = historyMachine.transition(offState, 'H_POWER'); | ||
const nextState = historyMachine.transition(onState, 'H_POWER'); | ||
assert.isUndefined(nextState.history!.history!.history); | ||
}); | ||
@@ -74,0 +75,0 @@ }); |
@@ -23,3 +23,11 @@ import { assert } from 'chai'; | ||
const lightMachine = Machine({ | ||
interface LightStateSchema { | ||
states: { | ||
green: any; | ||
yellow: any; | ||
red: any; | ||
}; | ||
} | ||
const lightMachine = Machine<undefined, LightStateSchema>({ | ||
key: 'light', | ||
@@ -26,0 +34,0 @@ initial: 'green', |
@@ -10,19 +10,50 @@ import { assert } from 'chai'; | ||
on: { | ||
INERT: undefined | ||
EXTERNAL: { | ||
target: 'one', | ||
internal: false | ||
}, | ||
INERT: { | ||
target: 'one', | ||
internal: true | ||
}, | ||
INTERNAL: { | ||
target: 'one', | ||
internal: true, | ||
actions: ['doSomething'] | ||
}, | ||
TO_TWO: 'two' | ||
} | ||
} | ||
}, | ||
two: {} | ||
} | ||
}); | ||
xdescribe('State', () => { | ||
xit('should indicate that it is not changed if initial state', () => { | ||
assert.ok(machine.initialState.changed); | ||
describe('State', () => { | ||
it('should indicate that it is not changed if initial state', () => { | ||
assert.isUndefined(machine.initialState.changed); | ||
}); | ||
it('should indicate that it is not changed if transition is inert', () => { | ||
const changedState = machine.transition(machine.initialState, 'INERT'); | ||
it('states from external transitions with onEntry actions should be changed', () => { | ||
const changedState = machine.transition(machine.initialState, 'EXTERNAL'); | ||
assert.isTrue(changedState.changed, 'changed due to onEntry action'); | ||
}); | ||
it('states from internal transitions with no actions should be unchanged', () => { | ||
const changedState = machine.transition(machine.initialState, 'EXTERNAL'); | ||
const unchangedState = machine.transition(changedState, 'INERT'); | ||
assert.isFalse(changedState.changed, 'changed due to onEntry action'); | ||
assert.isTrue(unchangedState.changed, 'unchanged - same state, no actions'); | ||
assert.isFalse( | ||
unchangedState.changed, | ||
'unchanged - same state, no actions' | ||
); | ||
}); | ||
it('states from internal transitions with actions should be changed', () => { | ||
const changedState = machine.transition(machine.initialState, 'INTERNAL'); | ||
assert.isTrue(changedState.changed, 'changed - transition actions'); | ||
}); | ||
it('normal state transitions should be changed', () => { | ||
const changedState = machine.transition(machine.initialState, 'TO_TWO'); | ||
assert.isTrue(changedState.changed, 'changed - different state'); | ||
}); | ||
}); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1446676
193
18354
345
4