UNPKG

mobx-state-tree

Version:

Opinionated, transactional, MobX powered state container

1 lines 86.7 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var Hook,mobx=require("mobx"),livelinessChecking="warn";function setLivelinessChecking(e){livelinessChecking=e}function getLivelinessChecking(){return livelinessChecking}function setLivelynessChecking(e){setLivelinessChecking(e)}!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(Hook||(Hook={}));var extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function __extends(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var __assign=function(){return(__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function __rest(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function __decorate(e,t,n,r){var i,o=arguments.length,a=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(a=(o<3?i(a):o>3?i(t,n,a):i(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}function __read(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}function getType(e){return getStateTreeNode(e).type}function getChildType(e,t){return getStateTreeNode(e).getChildType(t)}function onPatch(e,t){return getStateTreeNode(e).onPatch(t)}function onSnapshot(e,t){return getStateTreeNode(e).onSnapshot(t)}function applyPatch(e,t){getStateTreeNode(e).applyPatches(asArray(t))}function recordPatches(e,t){var n,r={patches:[],reversedInversePatches:[]},i={},o={get recording(){return!!n},get patches(){return i.patches||(i.patches=r.patches.slice()),i.patches},get reversedInversePatches(){return i.reversedInversePatches||(i.reversedInversePatches=r.reversedInversePatches.slice()),i.reversedInversePatches},get inversePatches(){return i.inversePatches||(i.inversePatches=r.reversedInversePatches.slice().reverse()),i.inversePatches},stop:function(){n&&(n(),n=void 0)},resume:function(){n||(n=onPatch(e,function(e,n){t&&!t(e,n,getRunningActionContext())||(r.patches.push(e),r.reversedInversePatches.unshift(n),i.patches=void 0,i.inversePatches=void 0,i.reversedInversePatches=void 0)}))},replay:function(t){applyPatch(t||e,r.patches)},undo:function(t){applyPatch(t||e,r.reversedInversePatches)}};return o.resume(),o}function protect(e){var t=getStateTreeNode(e);if(!t.isRoot)throw fail("`protect` can only be invoked on root nodes");t.isProtectionEnabled=!0}function unprotect(e){var t=getStateTreeNode(e);if(!t.isRoot)throw fail("`unprotect` can only be invoked on root nodes");t.isProtectionEnabled=!1}function isProtected(e){return getStateTreeNode(e).isProtected}function applySnapshot(e,t){return getStateTreeNode(e).applySnapshot(t)}function getSnapshot(e,t){void 0===t&&(t=!0);var n=getStateTreeNode(e);return t?n.snapshot:freeze(n.type.getSnapshot(n,!1))}function hasParent(e,t){void 0===t&&(t=1);for(var n=getStateTreeNode(e).parent;n;){if(0==--t)return!0;n=n.parent}return!1}function getParent(e,t){void 0===t&&(t=1);for(var n=t,r=getStateTreeNode(e).parent;r;){if(0==--n)return r.storedValue;r=r.parent}throw fail("Failed to find the parent of "+getStateTreeNode(e)+" at depth "+t)}function hasParentOfType(e,t){for(var n=getStateTreeNode(e).parent;n;){if(t.is(n.storedValue))return!0;n=n.parent}return!1}function getParentOfType(e,t){for(var n=getStateTreeNode(e).parent;n;){if(t.is(n.storedValue))return n.storedValue;n=n.parent}throw fail("Failed to find the parent of "+getStateTreeNode(e)+" of a given type")}function getRoot(e){return getStateTreeNode(e).root.storedValue}function getPath(e){return getStateTreeNode(e).path}function getPathParts(e){return splitJsonPath(getStateTreeNode(e).path)}function isRoot(e){return getStateTreeNode(e).isRoot}function resolvePath(e,t){var n=resolveNodeByPath(getStateTreeNode(e),t);return n?n.value:void 0}function resolveIdentifier(e,t,n){var r=getStateTreeNode(t).root.identifierCache.resolve(e,normalizeIdentifier(n));return r?r.value:void 0}function getIdentifier(e){return getStateTreeNode(e).identifier}function tryReference(e,t){void 0===t&&(t=!0);try{var n=e();if(null==n)return;if(isStateTreeNode(n))return t?isAlive(n)?n:void 0:n;throw fail("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof InvalidReferenceError)return;throw e}}function isValidReference(e,t){void 0===t&&(t=!0);try{var n=e();if(null==n)return!1;if(isStateTreeNode(n))return!t||isAlive(n);throw fail("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof InvalidReferenceError)return!1;throw e}}function tryResolve(e,t){var n=resolveNodeByPath(getStateTreeNode(e),t,!1);if(void 0!==n)try{return n.value}catch(e){return}}function getRelativePath(e,t){return getRelativePathBetweenNodes(getStateTreeNode(e),getStateTreeNode(t))}function clone(e,t){void 0===t&&(t=!0);var n=getStateTreeNode(e);return n.type.create(n.snapshot,!0===t?n.root.environment:!1===t?void 0:t)}function detach(e){return getStateTreeNode(e).detach(),e}function destroy(e){var t=getStateTreeNode(e);t.isRoot?t.die():t.parent.removeChild(t.subpath)}function isAlive(e){return getStateTreeNode(e).observableIsAlive}function addDisposer(e,t){return getStateTreeNode(e).addDisposer(t),t}function getEnv(e){var t=getStateTreeNode(e).root.environment;return t||EMPTY_OBJECT}function walk(e,t){var n=getStateTreeNode(e);n.getChildren().forEach(function(e){isStateTreeNode(e.storedValue)&&walk(e.storedValue,t)}),t(n.storedValue)}function getPropertyMembers(e){var t;return{name:(t=isStateTreeNode(e)?getType(e):e).name,properties:__assign({},t.properties)}}function getMembers(e){var t=getStateTreeNode(e).type,n=__assign({},getPropertyMembers(t),{actions:[],volatile:[],views:[]});return Object.getOwnPropertyNames(e).forEach(function(t){if(!(t in n.properties)){var r=Object.getOwnPropertyDescriptor(e,t);r.get?mobx.isComputedProp(e,t)?n.views.push(t):n.volatile.push(t):!0===r.value._isMSTAction?n.actions.push(t):mobx.isObservableProp(e,t)?n.volatile.push(t):n.views.push(t)}}),n}function cast(e){return e}function castToSnapshot(e){return e}function castToReferenceSnapshot(e){return e}function getNodeId(e){return getStateTreeNode(e).nodeId}var TypeFlags,BaseNode=function(){function e(e,t,n,r){this.type=e,this.environment=r,this._state=NodeLifeCycle.INITIALIZING,this.environment=r,this.baseSetParent(t,n)}return Object.defineProperty(e.prototype,"subpath",{get:function(){return this._subpath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"subpathUponDeath",{get:function(){return this._subpathUponDeath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pathUponDeath",{get:function(){return this._pathUponDeath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.type.getValue(this)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},set:function(e){var t=this.isAlive;this._state=e;var n=this.isAlive;this.aliveAtom&&t!==n&&this.aliveAtom.reportChanged()},enumerable:!0,configurable:!0}),e.prototype.fireInternalHook=function(e){this._hookSubscribers&&this._hookSubscribers.emit(e,this,e)},e.prototype.registerHook=function(e,t){return this._hookSubscribers||(this._hookSubscribers=new EventHandlers),this._hookSubscribers.register(e,t)},Object.defineProperty(e.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),e.prototype.baseSetParent=function(e,t){this._parent=e,this._subpath=t,this._escapedSubpath=void 0,this.pathAtom&&this.pathAtom.reportChanged()},Object.defineProperty(e.prototype,"path",{get:function(){return this.getEscapedPath(!0)},enumerable:!0,configurable:!0}),e.prototype.getEscapedPath=function(e){return e&&(this.pathAtom||(this.pathAtom=mobx.createAtom("path")),this.pathAtom.reportObserved()),this.parent?(void 0===this._escapedSubpath&&(this._escapedSubpath=this._subpath?escapeJsonPath(this._subpath):""),this.parent.getEscapedPath(e)+"/"+this._escapedSubpath):""},Object.defineProperty(e.prototype,"isRoot",{get:function(){return null===this.parent},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isAlive",{get:function(){return this.state!==NodeLifeCycle.DEAD},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isDetaching",{get:function(){return this.state===NodeLifeCycle.DETACHING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"observableIsAlive",{get:function(){return this.aliveAtom||(this.aliveAtom=mobx.createAtom("alive")),this.aliveAtom.reportObserved(),this.isAlive},enumerable:!0,configurable:!0}),e.prototype.baseFinalizeCreation=function(e){if(this.state===NodeLifeCycle.CREATED){if(this.parent){if(this.parent.state!==NodeLifeCycle.FINALIZED)return;this.fireHook(Hook.afterAttach)}this.state=NodeLifeCycle.FINALIZED,e&&e()}},e.prototype.baseFinalizeDeath=function(){this._hookSubscribers&&this._hookSubscribers.clearAll(),this._subpathUponDeath=this._subpath,this._pathUponDeath=this.getEscapedPath(!1),this.baseSetParent(null,""),this.state=NodeLifeCycle.DEAD},e.prototype.baseAboutToDie=function(){this.fireHook(Hook.beforeDestroy)},e}(),ScalarNode=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;try{a.storedValue=t.createNewInstance(o)}catch(e){throw a.state=NodeLifeCycle.DEAD,e}return a.state=NodeLifeCycle.CREATED,a.finalizeCreation(),a}return __extends(t,e),Object.defineProperty(t.prototype,"root",{get:function(){if(!this.parent)throw fail("This scalar node is not part of a tree");return this.parent.root},enumerable:!0,configurable:!0}),t.prototype.setParent=function(e,t){var n=this.parent!==e,r=this.subpath!==t;(n||r)&&(this.environment=void 0,this.baseSetParent(this.parent,t))},Object.defineProperty(t.prototype,"snapshot",{get:function(){return freeze(this.getSnapshot())},enumerable:!0,configurable:!0}),t.prototype.getSnapshot=function(){return this.type.getSnapshot(this)},t.prototype.toString=function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"<root>";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")},t.prototype.die=function(){this.isAlive&&this.state!==NodeLifeCycle.DETACHING&&(this.aboutToDie(),this.finalizeDeath())},t.prototype.finalizeCreation=function(){this.baseFinalizeCreation()},t.prototype.aboutToDie=function(){this.baseAboutToDie()},t.prototype.finalizeDeath=function(){this.baseFinalizeDeath()},t.prototype.fireHook=function(e){this.fireInternalHook(e)},__decorate([mobx.action],t.prototype,"die",null),t}(BaseNode),nextNodeId=1,snapshotReactionOptions={onError:function(e){throw e}},ObjectNode=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;if(a.nodeId=++nextNodeId,a.isProtectionEnabled=!0,a._autoUnbox=!0,a._isRunningAction=!1,a._hasSnapshotReaction=!1,a._observableInstanceState=0,a._cachedInitialSnapshotCreated=!1,a.unbox=a.unbox.bind(a),a._initialSnapshot=freeze(o),a.identifierAttribute=t.identifierAttribute,n||(a.identifierCache=new IdentifierCache),a._childNodes=t.initializeChildNodes(a,a._initialSnapshot),a.identifier=null,a.unnormalizedIdentifier=null,a.identifierAttribute&&a._initialSnapshot){var s=a._initialSnapshot[a.identifierAttribute];if(void 0===s){var p=a._childNodes[a.identifierAttribute];p&&(s=p.value)}if("string"!=typeof s&&"number"!=typeof s)throw fail("Instance identifier '"+a.identifierAttribute+"' for type '"+a.type.name+"' must be a string or a number");a.identifier=normalizeIdentifier(s),a.unnormalizedIdentifier=s}return n?n.root.identifierCache.addNodeToCache(a):a.identifierCache.addNodeToCache(a),a}return __extends(t,e),t.prototype.applyPatches=function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)},t.prototype.applySnapshot=function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)},t.prototype.createObservableInstanceIfNeeded=function(){var e,t;if(0===this._observableInstanceState){this._observableInstanceState=1;for(var n=[],r=this.parent;r&&0===r._observableInstanceState;)n.unshift(r),r=r.parent;try{for(var i=__values(n),o=i.next();!o.done;o=i.next()){o.value.createObservableInstanceIfNeeded()}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}var a=this.type;try{this.storedValue=a.createNewInstance(this._childNodes),this.preboot(),this._isRunningAction=!0,a.finalizeNewInstance(this,this.storedValue)}catch(e){throw this.state=NodeLifeCycle.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,invalidateComputed(this,"snapshot"),this.isRoot&&this._addSnapshotReaction(),this._childNodes=EMPTY_OBJECT,this.state=NodeLifeCycle.CREATED,this.fireHook(Hook.afterCreate),this.finalizeCreation()}},Object.defineProperty(t.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!0,configurable:!0}),t.prototype.clearParent=function(){if(this.parent){this.fireHook(Hook.beforeDetach);var e=this.state;this.state=NodeLifeCycle.DETACHING;var t=this.root,n=t.environment,r=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=n,this.identifierCache=r}finally{this.state=e}}},t.prototype.setParent=function(e,t){var n=e!==this.parent,r=t!==this.subpath;(n||r)&&(n?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(Hook.afterAttach)):r&&this.baseSetParent(this.parent,t))},t.prototype.fireHook=function(e){var t=this;this.fireInternalHook(e);var n=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof n&&(mobx._allowStateChangesInsideComputed?mobx._allowStateChangesInsideComputed(function(){n.apply(t.storedValue)}):n.apply(this.storedValue))},Object.defineProperty(t.prototype,"snapshot",{get:function(){return freeze(this.getSnapshot())},enumerable:!0,configurable:!0}),t.prototype.getSnapshot=function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath},t.prototype._getActualSnapshot=function(){return this.type.getSnapshot(this)},t.prototype._getCachedInitialSnapshot=function(){if(!this._cachedInitialSnapshotCreated){var e=this.type,t=this._childNodes,n=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,n),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot},t.prototype.isRunningAction=function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()},t.prototype.assertAlive=function(e){var t=getLivelinessChecking();if(!this.isAlive&&"ignore"!==t){var n=this._getAssertAliveError(e);switch(t){case"error":throw fail(n);case"warn":warnError(n)}}},t.prototype._getAssertAliveError=function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",n=e.subpath&&escapeJsonPath(e.subpath)||"",r=e.actionContext||getCurrentActionContext();r&&"action"!==r.type&&r.parentActionEvent&&(r=r.parentActionEvent);var i="";r&&null!=r.name&&(i=(r&&r.context&&getPath(r.context)||t)+"."+r.name+"()");return"You are trying to read or write to an object that is no longer part of a state tree. (Object type: '"+this.type.name+"', Path upon death: '"+t+"', Subpath: '"+n+"', Action: '"+i+"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."},t.prototype.getChildNode=function(e){this.assertAlive({subpath:e}),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildNode(this,e):this._childNodes[e]}finally{this._autoUnbox=!0}},t.prototype.getChildren=function(){this.assertAlive(EMPTY_OBJECT),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):convertChildNodesToArray(this._childNodes)}finally{this._autoUnbox=!0}},t.prototype.getChildType=function(e){return this.type.getChildType(e)},Object.defineProperty(t.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!0,configurable:!0}),t.prototype.assertWritable=function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw fail("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")},t.prototype.removeChild=function(e){this.type.removeChild(this,e)},t.prototype.unbox=function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e},t.prototype.toString=function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"<root>",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")},t.prototype.finalizeCreation=function(){var e=this;this.baseFinalizeCreation(function(){var t,n;try{for(var r=__values(e.getChildren()),i=r.next();!i.done;i=r.next()){i.value.finalizeCreation()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}e.fireInternalHook(Hook.afterCreationFinalization)})},t.prototype.detach=function(){if(!this.isAlive)throw fail("Error while detaching, node is not alive.");this.clearParent()},t.prototype.preboot=function(){var e=this;this._applyPatches=createActionInvoker(this.storedValue,"@APPLY_PATCHES",function(t){t.forEach(function(t){var n=splitJsonPath(t.path);resolveNodeByPathParts(e,n.slice(0,-1)).applyPatchLocally(n[n.length-1],t)})}),this._applySnapshot=createActionInvoker(this.storedValue,"@APPLY_SNAPSHOT",function(t){if(t!==e.snapshot)return e.type.applySnapshot(e,t)}),addHiddenFinalProp(this.storedValue,"$treenode",this),addHiddenFinalProp(this.storedValue,"toJSON",toJSON)},t.prototype.die=function(){this.isAlive&&this.state!==NodeLifeCycle.DETACHING&&(this.aboutToDie(),this.finalizeDeath())},t.prototype.aboutToDie=function(){0!==this._observableInstanceState&&(this.getChildren().forEach(function(e){e.aboutToDie()}),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))},t.prototype.finalizeDeath=function(){this.getChildren().forEach(function(e){e.finalizeDeath()}),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()},t.prototype.onSnapshot=function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)},t.prototype.emitSnapshot=function(e){this._internalEventsEmit("snapshot",e)},t.prototype.onPatch=function(e){return this._internalEventsRegister("patch",e)},t.prototype.emitPatch=function(e,t){if(this._internalEventsHasSubscribers("patch")){var n=__read(splitPatch(extend({},e,{path:t.path.substr(this.path.length)+"/"+e.path})),2),r=n[0],i=n[1];this._internalEventsEmit("patch",r,i)}this.parent&&this.parent.emitPatch(e,t)},t.prototype.hasDisposer=function(e){return this._internalEventsHas("dispose",e)},t.prototype.addDisposer=function(e){if(this.hasDisposer(e))throw fail("cannot add a disposer when it is already registered for execution");this._internalEventsRegister("dispose",e,!0)},t.prototype.removeDisposer=function(e){if(!this._internalEventsHas("dispose",e))throw fail("cannot remove a disposer which was never registered for execution");this._internalEventsUnregister("dispose",e)},t.prototype.removeMiddleware=function(e){if(this.middlewares){var t=this.middlewares.indexOf(e);t>=0&&this.middlewares.splice(t,1)}},t.prototype.addMiddleWare=function(e,t){var n=this;void 0===t&&(t=!0);var r={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(r):this.middlewares=[r],function(){n.removeMiddleware(r)}},t.prototype.applyPatchLocally=function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)},t.prototype._addSnapshotReaction=function(){var e=this;if(!this._hasSnapshotReaction){var t=mobx.reaction(function(){return e.snapshot},function(t){return e.emitSnapshot(t)},snapshotReactionOptions);this.addDisposer(t),this._hasSnapshotReaction=!0}},t.prototype._internalEventsHasSubscribers=function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)},t.prototype._internalEventsRegister=function(e,t,n){return void 0===n&&(n=!1),this._internalEvents||(this._internalEvents=new EventHandlers),this._internalEvents.register(e,t,n)},t.prototype._internalEventsHas=function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)},t.prototype._internalEventsUnregister=function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)},t.prototype._internalEventsEmit=function(e){for(var t,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];this._internalEvents&&(t=this._internalEvents).emit.apply(t,__spread([e],n))},t.prototype._internalEventsClear=function(e){this._internalEvents&&this._internalEvents.clear(e)},t.prototype._internalEventsClearAll=function(){this._internalEvents&&this._internalEvents.clearAll()},__decorate([mobx.action],t.prototype,"createObservableInstanceIfNeeded",null),__decorate([mobx.computed],t.prototype,"snapshot",null),__decorate([mobx.action],t.prototype,"detach",null),__decorate([mobx.action],t.prototype,"die",null),t}(BaseNode);!function(e){e[e.String=1]="String",e[e.Number=2]="Number",e[e.Boolean=4]="Boolean",e[e.Date=8]="Date",e[e.Literal=16]="Literal",e[e.Array=32]="Array",e[e.Map=64]="Map",e[e.Object=128]="Object",e[e.Frozen=256]="Frozen",e[e.Optional=512]="Optional",e[e.Reference=1024]="Reference",e[e.Identifier=2048]="Identifier",e[e.Late=4096]="Late",e[e.Refinement=8192]="Refinement",e[e.Union=16384]="Union",e[e.Null=32768]="Null",e[e.Undefined=65536]="Undefined",e[e.Integer=131072]="Integer",e[e.Custom=262144]="Custom",e[e.SnapshotProcessor=524288]="SnapshotProcessor"}(TypeFlags||(TypeFlags={}));var cannotDetermineSubtype="cannotDetermine",BaseType=function(){function e(e){this.isType=!0,this.name=e}return e.prototype.create=function(e,t){return typecheckInternal(this,e),this.instantiate(null,"",t,e).value},e.prototype.getSnapshot=function(e,t){throw fail("unimplemented method")},e.prototype.isAssignableFrom=function(e){return e===this},e.prototype.validate=function(e,t){if(getStateTreeNodeSafe(e)){var n=getType(e);return this.isAssignableFrom(n)?typeCheckSuccess():typeCheckFailure(t,e)}return this.isValidSnapshot(e,t)},e.prototype.is=function(e){return 0===this.validate(e,[{path:"",type:this}]).length},Object.defineProperty(e.prototype,"Type",{get:function(){throw fail("Factory.Type should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.Type`")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"TypeWithoutSTN",{get:function(){throw fail("Factory.TypeWithoutSTN should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.TypeWithoutSTN`")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"SnapshotType",{get:function(){throw fail("Factory.SnapshotType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.SnapshotType`")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CreationType",{get:function(){throw fail("Factory.CreationType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.CreationType`")},enumerable:!0,configurable:!0}),__decorate([mobx.action],e.prototype,"create",null),e}(),ComplexType=function(e){function t(t){return e.call(this,t)||this}return __extends(t,e),t.prototype.create=function(t,n){return void 0===t&&(t=this.getDefaultSnapshot()),e.prototype.create.call(this,t,n)},t.prototype.getValue=function(e){return e.createObservableInstanceIfNeeded(),e.storedValue},t.prototype.tryToReconcileNode=function(e,t){return!e.isDetaching&&(e.snapshot===t||(!(!isStateTreeNode(t)||getStateTreeNode(t)!==e)||!(e.type!==this||!isMutable(t)||isStateTreeNode(t)||e.identifierAttribute&&e.identifier!==normalizeIdentifier(t[e.identifierAttribute]))&&(e.applySnapshot(t),!0)))},t.prototype.reconcile=function(e,t,n,r){if(this.tryToReconcileNode(e,t))return e.setParent(n,r),e;if(e.die(),isStateTreeNode(t)&&this.isAssignableFrom(getType(t))){var i=getStateTreeNode(t);return i.setParent(n,r),i}return this.instantiate(n,r,void 0,t)},t.prototype.getSubTypes=function(){return null},__decorate([mobx.action],t.prototype,"create",null),t}(BaseType),SimpleType=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.createNewInstance=function(e){return e},t.prototype.getValue=function(e){return e.storedValue},t.prototype.getSnapshot=function(e){return e.storedValue},t.prototype.reconcile=function(e,t,n,r){if(!e.isDetaching&&e.type===this&&e.storedValue===t)return e;var i=this.instantiate(n,r,void 0,t);return e.die(),i},t.prototype.getSubTypes=function(){return null},t}(BaseType);function isType(e){return"object"==typeof e&&e&&!0===e.isType}var runningActions=new Map;function createActionTrackingMiddleware(e){return function(t,n,r){switch(t.type){case"action":if(e.filter&&!0!==e.filter(t))return n(t);var i=e.onStart(t);e.onResume(t,i),runningActions.set(t.id,{call:t,context:i,async:!1});try{var o=n(t);return e.onSuspend(t,i),!1===runningActions.get(t.id).async&&(runningActions.delete(t.id),e.onSuccess(t,i,o)),o}catch(n){throw runningActions.delete(t.id),e.onFail(t,i,n),n}case"flow_spawn":return(a=runningActions.get(t.rootId)).async=!0,n(t);case"flow_resume":case"flow_resume_error":var a=runningActions.get(t.rootId);e.onResume(t,a.context);try{return n(t)}finally{e.onSuspend(t,a.context)}case"flow_throw":a=runningActions.get(t.rootId);return runningActions.delete(t.rootId),e.onFail(t,a.context,t.args[0]),n(t);case"flow_return":a=runningActions.get(t.rootId);return runningActions.delete(t.rootId),e.onSuccess(t,a.context,t.args[0]),n(t)}}}var RunningAction=function(){function e(e,t){this.hooks=e,this.call=t,this.flowsPending=0,this.running=!0,e&&e.onStart(t)}return e.prototype.finish=function(e){this.running&&(this.running=!1,this.hooks&&this.hooks.onFinish(this.call,e))},e.prototype.incFlowsPending=function(){this.flowsPending++},e.prototype.decFlowsPending=function(){this.flowsPending--},Object.defineProperty(e.prototype,"hasFlowsPending",{get:function(){return this.flowsPending>0},enumerable:!0,configurable:!0}),e}();function createActionTrackingMiddleware2(e){var t=new WeakMap;return function(n,r){var i=n.parentActionEvent?t.get(n.parentActionEvent):void 0;if("action"===n.type){var o=__assign({},n,{env:i&&i.call.env,parentCall:i&&i.call}),a=!e.filter||e.filter(o),s=new RunningAction(a?e:void 0,o);t.set(n,s);var p=void 0;try{p=r(n)}catch(e){throw s.finish(e),e}return s.hasFlowsPending||s.finish(),p}if(!i)return r(n);switch(n.type){case"flow_spawn":return i.incFlowsPending(),r(n);case"flow_resume":case"flow_resume_error":return r(n);case"flow_throw":var c=n.args[0];try{return r(n)}finally{i.decFlowsPending(),i.hasFlowsPending||i.finish(c)}case"flow_return":try{return r(n)}finally{i.decFlowsPending(),i.hasFlowsPending||i.finish()}}}}function serializeArgument(e,t,n,r){if(r instanceof Date)return{$MST_DATE:r.getTime()};if(isPrimitive(r))return r;if(isStateTreeNode(r))return serializeTheUnserializable("[MSTNode: "+getType(r).name+"]");if("function"==typeof r)return serializeTheUnserializable("[function]");if("object"==typeof r&&!isPlainObject(r)&&!isArray(r))return serializeTheUnserializable("[object "+(r&&r.constructor&&r.constructor.name||"Complex Object")+"]");try{return JSON.stringify(r),r}catch(e){return serializeTheUnserializable(""+e)}}function deserializeArgument(e,t){return t&&"object"==typeof t&&"$MST_DATE"in t?new Date(t.$MST_DATE):t}function serializeTheUnserializable(e){return{$MST_UNSERIALIZABLE:!0,type:e}}function applyAction(e,t){mobx.runInAction(function(){asArray(t).forEach(function(t){return baseApplyAction(e,t)})})}function baseApplyAction(e,t){var n=tryResolve(e,t.path||"");if(!n)throw fail("Invalid action path: "+(t.path||""));var r=getStateTreeNode(n);if("@APPLY_PATCHES"===t.name)return applyPatch.call(null,n,t.args[0]);if("@APPLY_SNAPSHOT"===t.name)return applySnapshot.call(null,n,t.args[0]);if("function"!=typeof n[t.name])throw fail("Action '"+t.name+"' does not exist in '"+r.path+"'");return n[t.name].apply(n,t.args?t.args.map(function(e){return deserializeArgument(r,e)}):[])}function recordActions(e,t){var n,r=[],i=function(e){(!t||t(e,getRunningActionContext()))&&r.push(e)},o={actions:r,get recording(){return!!n},stop:function(){n&&(n(),n=void 0)},resume:function(){n||(n=onAction(e,i))},replay:function(e){applyAction(e,r)}};return o.resume(),o}function onAction(e,t,n){return void 0===n&&(n=!1),addMiddleware(e,function(r,i){if("action"===r.type&&r.id===r.rootId){var o=getStateTreeNode(r.context),a={name:r.name,path:getRelativePathBetweenNodes(getStateTreeNode(e),o),args:r.args.map(function(e,t){return serializeArgument(o,r.name,t,e)})};if(n){var s=i(r);return t(a),s}return t(a),i(r)}return i(r)})}var currentActionContext,nextActionId=1;function getCurrentActionContext(){return currentActionContext}function getNextActionId(){return nextActionId++}function runWithActionContext(e,t){var n=getStateTreeNode(e.context);"action"===e.type&&n.assertAlive({actionContext:e});var r=n._isRunningAction;n._isRunningAction=!0;var i=currentActionContext;currentActionContext=e;try{return runMiddleWares(n,e,t)}finally{currentActionContext=i,n._isRunningAction=r}}function getParentActionContext(e){if(e)return"action"===e.type?e:e.parentActionEvent}function createActionInvoker(e,t,n){var r=function(){var r=getNextActionId(),i=currentActionContext,o=getParentActionContext(i);return runWithActionContext({type:"action",name:t,id:r,args:argsToArray(arguments),context:e,tree:getRoot(e),rootId:i?i.rootId:r,parentId:i?i.id:0,allParentIds:i?__spread(i.allParentIds,[i.id]):[],parentEvent:i,parentActionEvent:o},n)};return r._isMSTAction=!0,r}function addMiddleware(e,t,n){return void 0===n&&(n=!0),getStateTreeNode(e).addMiddleWare(t,n)}function decorate(e,t,n){void 0===n&&(n=!0);var r={handler:e,includeHooks:n};return t.$mst_middleware=t.$mst_middleware||[],t.$mst_middleware.push(r),t}var CollectedMiddlewares=function(){function e(e,t){this.arrayIndex=0,this.inArrayIndex=0,this.middlewares=[],t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);for(var n=e;n;)n.middlewares&&this.middlewares.push(n.middlewares),n=n.parent}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return this.middlewares.length<=0},enumerable:!0,configurable:!0}),e.prototype.getNextMiddleware=function(){var e=this.middlewares[this.arrayIndex];if(e){var t=e[this.inArrayIndex++];return t||(this.arrayIndex++,this.inArrayIndex=0,this.getNextMiddleware())}},e}();function runMiddleWares(e,t,n){var r=new CollectedMiddlewares(e,n);if(r.isEmpty)return mobx.action(n).apply(null,t.args);var i=null;return function e(t){var o=r.getNextMiddleware(),a=o&&o.handler;if(!a)return mobx.action(n).apply(null,t.args);if(!o.includeHooks&&Hook[t.name])return e(t);return a(t,function(t,n){i=e(t),n&&(i=n(i))},function(e){i=e}),i}(t)}function getRunningActionContext(){for(var e=getCurrentActionContext();e&&"action"!==e.type;)e=e.parentActionEvent;return e}function _isActionContextThisOrChildOf(e,t,n){for(var r="number"==typeof t?t:t.id,i=n?e:e.parentActionEvent;i;){if(i.id===r)return!0;i=i.parentActionEvent}return!1}function isActionContextChildOf(e,t){return _isActionContextThisOrChildOf(e,t,!1)}function isActionContextThisOrChildOf(e,t){return _isActionContextThisOrChildOf(e,t,!0)}function safeStringify(e){try{return JSON.stringify(e)}catch(e){return"<Unserializable: "+e+">"}}function prettyPrintValue(e){return"function"==typeof e?"<function"+(e.name?" "+e.name:"")+">":isStateTreeNode(e)?"<"+e+">":"`"+safeStringify(e)+"`"}function shortenPrintValue(e){return e.length<280?e:e.substring(0,272)+"......"+e.substring(e.length-8)}function toErrorString(e){var t=e.value,n=e.context[e.context.length-1].type,r=e.context.map(function(e){return e.path}).filter(function(e){return e.length>0}).join("/"),i=r.length>0?'at path "/'+r+'" ':"",o=isStateTreeNode(t)?"value of type "+getStateTreeNode(t).type.name+":":isPrimitive(t)?"value":"snapshot",a=n&&isStateTreeNode(t)&&n.is(getStateTreeNode(t).snapshot);return""+i+o+" "+prettyPrintValue(t)+" is not assignable "+(n?"to type: `"+n.name+"`":"")+(e.message?" ("+e.message+")":"")+(n?isPrimitiveType(n)||isPrimitive(t)?".":", expected an instance of `"+n.name+"` or a snapshot like `"+n.describe()+"` instead."+(a?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".")}function getContextForPath(e,t,n){return e.concat([{path:t,type:n}])}function typeCheckSuccess(){return EMPTY_ARRAY}function typeCheckFailure(e,t,n){return[{context:e,value:t,message:n}]}function flattenTypeErrors(e){return e.reduce(function(e,t){return e.concat(t)},[])}function typecheckInternal(e,t){isTypeCheckingEnabled()&&typecheck(e,t)}function typecheck(e,t){var n=e.validate(t,[{path:"",type:e}]);if(n.length>0)throw fail(validationErrorsToString(e,t,n))}function validationErrorsToString(e,t,n){if(0!==n.length)return"Error while converting "+shortenPrintValue(prettyPrintValue(t))+" to `"+e.name+"`:\n\n "+n.map(toErrorString).join("\n ")}var NodeLifeCycle,identifierCacheId=0,IdentifierCache=function(){function e(){this.cacheId=identifierCacheId++,this.cache=mobx.observable.map(),this.lastCacheModificationPerId=mobx.observable.map()}return e.prototype.updateLastCacheModificationPerId=function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)},e.prototype.getLastCacheModificationPerId=function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t},e.prototype.addNodeToCache=function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var n=e.identifier;this.cache.has(n)||this.cache.set(n,mobx.observable.array([],mobxShallow));var r=this.cache.get(n);if(-1!==r.indexOf(e))throw fail("Already registered");r.push(e),t&&this.updateLastCacheModificationPerId(n)}},e.prototype.mergeCache=function(e){var t=this;mobx.values(e.identifierCache.cache).forEach(function(e){return e.forEach(function(e){t.addNodeToCache(e)})})},e.prototype.notifyDied=function(e){if(e.identifierAttribute){var t=e.identifier,n=this.cache.get(t);n&&(n.remove(e),n.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}},e.prototype.splitCache=function(t){var n=this,r=new e,i=t.path;return mobx.entries(this.cache).forEach(function(e){for(var t=__read(e,2),o=t[0],a=t[1],s=!1,p=a.length-1;p>=0;p--)0===a[p].path.indexOf(i)&&(r.addNodeToCache(a[p],!1),a.splice(p,1),s=!0);s&&n.updateLastCacheModificationPerId(o)}),r},e.prototype.has=function(e,t){var n=this.cache.get(t);return!!n&&n.some(function(t){return e.isAssignableFrom(t.type)})},e.prototype.resolve=function(e,t){var n=this.cache.get(t);if(!n)return null;var r=n.filter(function(t){return e.isAssignableFrom(t.type)});switch(r.length){case 0:return null;case 1:return r[0];default:throw fail("Cannot resolve a reference to type '"+e.name+"' with id: '"+t+"' unambigously, there are multiple candidates: "+r.map(function(e){return e.path}).join(", "))}},e}();function createObjectNode(e,t,n,r,i){var o=getStateTreeNodeSafe(i);if(o){if(o.parent)throw fail("Cannot add an object to a state tree if it is already part of the same or another state tree. Tried to assign an object to '"+(t?t.path:"")+"/"+n+"', but it lives already at '"+o.path+"'");return t&&o.setParent(t,n),o}return new ObjectNode(e,t,n,r,i)}function createScalarNode(e,t,n,r,i){return new ScalarNode(e,t,n,r,i)}function isNode(e){return e instanceof ScalarNode||e instanceof ObjectNode}function isStateTreeNode(e){return!(!e||!e.$treenode)}function getStateTreeNode(e){if(!isStateTreeNode(e))throw fail("Value "+e+" is no MST Node");return e.$treenode}function getStateTreeNodeSafe(e){return e&&e.$treenode||null}function toJSON(){return getStateTreeNode(this).snapshot}!function(e){e[e.INITIALIZING=0]="INITIALIZING",e[e.CREATED=1]="CREATED",e[e.FINALIZED=2]="FINALIZED",e[e.DETACHING=3]="DETACHING",e[e.DEAD=4]="DEAD"}(NodeLifeCycle||(NodeLifeCycle={}));var doubleDot=function(e){return".."};function getRelativePathBetweenNodes(e,t){if(e.root!==t.root)throw fail("Cannot calculate relative path: objects '"+e+"' and '"+t+"' are not part of the same object tree");for(var n=splitJsonPath(e.path),r=splitJsonPath(t.path),i=0;i<n.length&&n[i]===r[i];i++);return n.slice(i).map(doubleDot).join("/")+joinJsonPath(r.slice(i))}function resolveNodeByPath(e,t,n){return void 0===n&&(n=!0),resolveNodeByPathParts(e,splitJsonPath(t),n)}function resolveNodeByPathParts(e,t,n){void 0===n&&(n=!0);for(var r=e,i=0;i<t.length;i++){var o=t[i];if(".."===o){if(r=r.parent)continue}else{if("."===o)continue;if(r){if(r instanceof ScalarNode)try{var a=r.value;isStateTreeNode(a)&&(r=getStateTreeNode(a))}catch(e){if(!n)return;throw e}if(r instanceof ObjectNode)if(r.getChildType(o)&&(r=r.getChildNode(o)))continue}}if(n)throw fail("Could not resolve '"+o+"' in path '"+(joinJsonPath(t.slice(0,i))||"/")+"' while resolving '"+joinJsonPath(t)+"'");return}return r}function convertChildNodesToArray(e){if(!e)return EMPTY_ARRAY;var t=Object.keys(e);if(!t.length)return EMPTY_ARRAY;var n=new Array(t.length);return t.forEach(function(t,r){n[r]=e[t]}),n}var DEPRECATION_MESSAGE="See https://github.com/mobxjs/mobx-state-tree/issues/399 for more information. Note that the middleware event types starting with `process` now start with `flow`.";function process$1(e){return deprecated("process","`process()` has been renamed to `flow()`. "+DEPRECATION_MESSAGE),flow(e)}var EMPTY_ARRAY=Object.freeze([]),EMPTY_OBJECT=Object.freeze({}),mobxShallow="string"==typeof mobx.$mobx?{deep:!1}:{deep:!1,proxy:!1};function fail(e){return void 0===e&&(e="Illegal state"),new Error("[mobx-state-tree] "+e)}function identity(e){return e}Object.freeze(mobxShallow);var isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function isArray(e){return Array.isArray(e)||mobx.isObservableArray(e)}function asArray(e){return e?isArray(e)?e:[e]:EMPTY_ARRAY}function extend(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0;r<t.length;r++){var i=t[r];for(var o in i)e[o]=i[o]}return e}function isPlainObject(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function isMutable(e){return!(null===e||"object"!=typeof e||e instanceof Date||e instanceof RegExp)}function isPrimitive(e,t){return void 0===t&&(t=!0),null==e||!!("string"==typeof e||"number"==typeof e||"boolean"==typeof e||t&&e instanceof Date)}function freeze(e){return e}function deepFreeze(e){return e}function isSerializable(e){return"function"!=typeof e}function addHiddenFinalProp(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}var EventHandler=function(){function e(){this.handlers=[]}return Object.defineProperty(e.prototype,"hasSubscribers",{get:function(){return this.handlers.length>0},enumerable:!0,configurable:!0}),e.prototype.register=function(e,t){var n=this;return void 0===t&&(t=!1),t?this.handlers.unshift(e):this.handlers.push(e),function(){n.unregister(e)}},e.prototype.has=function(e){return this.handlers.indexOf(e)>=0},e.prototype.unregister=function(e){var t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)},e.prototype.clear=function(){this.handlers.length=0},e.prototype.emit=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.handlers.slice().forEach(function(t){return t.apply(void 0,__spread(e))})},e}(),EventHandlers=function(){function e(){}return e.prototype.hasSubscribers=function(e){var t=this.eventHandlers&&this.eventHandlers[e];return!!t&&t.hasSubscribers},e.prototype.register=function(e,t,n){void 0===n&&(n=!1),this.eventHandlers||(this.eventHandlers={});var r=this.eventHandlers[e];return r||(r=this.eventHandlers[e]=new EventHandler),r.register(t,n)},e.prototype.has=function(e,t){var n=this.eventHandlers&&this.eventHandlers[e];return!!n&&n.has(t)},e.prototype.unregister=function(e,t){var n=this.eventHandlers&&this.eventHandlers[e];n&&n.unregister(t)},e.prototype.clear=function(e){this.eventHandlers&&delete this.eventHandlers[e]},e.prototype.clearAll=function(){this.eventHandlers=void 0},e.prototype.emit=function(e){for(var t,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];var i=this.eventHandlers&&this.eventHandlers[e];i&&(t=i).emit.apply(t,__spread(n))},e}();function argsToArray(e){for(var t=new Array(e.length),n=0;n<e.length;n++)t[n]=e[n];return t}function invalidateComputed(e,t){mobx.getAtom(e,t).trackAndCompute()}function stringStartsWith(e,t){return 0===e.indexOf(t)}var deprecated=function(e,t){};function warnError(e){console.warn(new Error("[mobx-state-tree] "+e))}function isTypeCheckingEnabled(){return"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK}function flow(e){return createFlowSpawner(e.name,e)}function castFlowReturn(e){return e}function createFlowSpawner(e,t){var n=function(){var r=getNextActionId(),i=getCurrentActionContext();if(!i)throw fail("a mst flow must always have a parent context");var o=getParentActionContext(i);if(!o)throw fail("a mst flow must always have a parent action context");var a={name:e,id:r,tree:i.tree,context:i.context,parentId:i.id,allParentIds:__spread(i.allParentIds,[i.id]),rootId:i.rootId,parentEvent:i,parentActionEvent:o},s=arguments;function p(e,t,r){e.$mst_middleware=n.$mst_middleware,runWithActionContext(__assign({},a,{type:t,args:[r]}),e)}return new Promise(function(e,r){var i,o=function(){i=t.apply(null,arguments),c(void 0)};function c(e){var t;try{p(function(e){t=i.next(e)},"flow_resume",e)}catch(e){return void setImmediate(function(){p(function(t){r(e)},"flow_throw",e)})}l(t)}function u(e){var t;try{p(function(e){t=i.throw(e)},"flow_resume_error",e)}catch(e){return void setImmediate(function(){p(function(t){r(e)},"flow_throw",e)})}l(t)}function l(t){if(!t.done){if(!t.value||"function"!=typeof t.value.then)throw fail("Only promises can be yielded to `async`, got: "+t);return t.value.then(c,u)}setImmediate(function(){p(function(t){e(t)},"flow_return",t.value)})}o.$mst_middleware=n.$mst_middleware,runWithActionContext(__assign({},a,{type:"flow_spawn",args:argsToArray(s)}),o)})};return n}function splitPatch(e){if(!("oldValue"in e))throw fail("Patches without `oldValue` field cannot be inversed");return[stripPatch(e),invertPatch(e)]}function stripPatch(e){switch(e.op){case"add":return{op:"add",path:e.path,value:e.value};case"remove":return{op:"remove",path:e.path};case"replace":return{op:"replace",path:e.path,value:e.value}}}function invertPatch(e){switch(e.op){case"add":return{op:"remove",path:e.path};case"remove":return{op:"add",path:e.path,value:e.oldValue};case"replace":return{op:"replace",path:e.path,value:e.oldValue}}}function isNumber(e){return"number"==typeof e}function escapeJsonPath(e){return!0===isNumber(e)?""+e:-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeJsonPath(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function joinJsonPath(e){if(0===e.length)return"";var t=function(e){return e.map(escapeJsonPath).join("/")};return"."===e[0]||".."===e[0]?t(e):"/"+t(e)}function splitJsonPath(e){var t=e.split("/").map(unescapeJsonPath);if(!(""===e||"."===e||".."===e||stringStartsWith(e,"/")||stringStartsWith(e,"./")||stringStartsWith(e,"../")))throw fail("a json path must be either rooted, empty or relative, but got '"+e+"'");return""===t[0]&&t.shift(),t}deprecated.ids={};var SnapshotProcessor=function(e){function t(t,n,r){var i=e.call(this,r||t.name)||this;return i._subtype=t,i._processors=n,i}return __extends(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return this._subtype.flags|TypeFlags.SnapshotProcessor},enumerable:!0,configurable:!0}),t.prototype.describe=function(){return"snapshotProcessor("+this._subtype.describe()+")"},t.prototype.preProcessSnapshot=function(e){return this._processors.preProcessor?this._processors.preProcessor.call(null,e):e},t.prototype.postProcessSnapshot=function(e){return this._processors.postProcessor?this._processors.postProcessor.call(null,e):e},t.prototype._fixNode=function(e){var t=this;proxyNodeTypeMethods(e.type,this,"isAssignableFrom","create");var n=e.getSnapshot;e.getSnapshot=function(){return t.postProcessSnapshot(n.call(e))}},t.prototype.instantiate=function(e,t,n,r){var i=isStateTreeNode(r)?r:this.preProcessSnapshot(r),o=this._subtype.instantiate(e,t,n,i);return this._fixNode(o),o},t.prototype.reconcile=function(e,t,n,r){var i=this._subtype.reconcile(e,isStateTreeNode(t)?t:this.preProcessSnapshot(t),n,r);return i!==e&&this._fixNode(i),i},t.prototype.getSnapshot=function(e,t){void 0===t&&(t=!0);var n=this._subtype.getSnapshot(e);return t?this.postProcessSnapshot(n):n},t.prototype.isValidSnapshot=function(e,t){var n=this.preProcessSnapshot(e);return this._subtype.validate(n,t)},t.prototype.getSubTypes=function(){return this._subtype},t.prototype.is=function(e){return 0===this._subtype.validate(isType(e)?this._subtype:this.preProcessSnapshot(e),[{path:"",type:this._subtype}]).length},t}(BaseType);function proxyNodeTypeMethods(e,t){for(var n,r,i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];try{for(var a=__values(i),s=a.next();!s.done;s=a.next()){var p=s.value;e[p]=t[p].bind(t)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}function snapshotProcessor(e,t,n){return new SnapshotProcessor(e,t,n)}var MapIdentifierMode,needsIdentifierError="Map.put can only be used to store complex values that have an identifier type attribute";function tryCollectModelTypes(e,t){var n,r,i=e.getSubTypes();if(i===cannotDetermineSubtype)return!1;if(i){var o=asArray(i);try{for(var a=__values(o),s=a.next();!s.done;s=a.next()){if(!tryCollectModelTypes(s.value,t))return!1}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}return e instanceof ModelType&&t.push(e),!0}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.YES=1]="YES",e[e.NO=2]="NO"}(MapIdentifierMode||(MapIdentifierMode={}));var MSTMap=function(e){function t(t){return e.call(this,t,mobx.observable.ref.enhancer)||this}return __extends(t,e),t.prototype.get=function(t){return e.prototype.get.call(this,""+t)},t.prototype.has=function(t){return e.prototype.has.call(this,""+t)},t.prototype.delete=function(t){return e.prototype.delete.call(this,""+t)},t.prototype.set=function(t,n){return e.prototype.set.call(this,""+t,n)},t.prototype.put=function(e){if(!e)throw fail("Map.put cannot be used to set empty values");if(isStateTreeNode(e)){var t=getStateTreeNode(e);if(null===t.identifier)throw fail(needsIdentifierError);return this.set(t.identifier,e),e}if(isMutable(e)){var n=getStateTreeNode(this),r=n.type;if(r.identifierMode!==MapIdentifierMode.YES)throw fail(needsIdentifierError);var i=e[r.mapIdentifierAttribute];if(!isValidIdentifier(i)){var o=this.put(r.getChildType().create(e,n.environment));return this.put(getSnapshot(o))}var a=normalizeIdentifier(i);return this.set(a,e),this.get(a)}throw fail("Map.put can only be used to store complex values")},t}(mobx.ObservableMap),MapType=function(e){function t(t,n){var r=e.call(this,t)||this;return r._subType=n,r.identifierMode=MapIdentifierMode.UNKNOWN,r.mapIdentifierAttribute=void 0,r.flags=TypeFlags.Map,r._determineIdentifierMode(),r}return __extends(t,e),t.prototype.instantiate=function(e,t,n,r){return this._determineIdentifierMode(),createObjectNode(this,e,t,n,r)},t.prototype._determineIdentifierMode=function(){if(this.identifierMode===MapIdentifierMode.UNKNOWN){var e=[];if(tryCollectModelTypes(this._subType,e)){var t=void 0;e.forEach(function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw fail("The objects in a map should all have the same identifier attribute, expected '"+t+"', but child of type '"+e.name+"' declared attribute '"+e.identifierAttribute+"' as identifier");t=e.identifierAttribute}}),t?(this.identifierMode=MapIdentifierMode.YES,this.mapIdentifierAttribute=t):this.identifierMode=MapIdentifierMode.NO}}},t.prototype.initializeChildNodes=function(e,t){void 0===t&&(t={});var n=e.type._subType,r={};return Object.keys(t).forEach(function(i){r[i]=n.instantiate(e,i,void 0,t[i])}),r},t.prototype.createNewInstance=function(e){return new MSTMap(e)},t.prototype.finalizeNewInstance=function(e,t){mobx._interceptReads(t,e.unbox),mobx.intercept(t,this.willChange),mobx.observe(t,this.didChange)},t.prototype.describe=function(){return"Map<string, "+this._subType.describe()+">"},t.prototype.getChildren=function(e){return mobx.values(e.storedValue)},t.prototype.getChi