UNPKG

mobx-state-tree

Version:

Opinionated, transactional, MobX powered state container

2 lines • 74.6 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("mobx")):"function"==typeof define&&define.amd?define(["exports","mobx"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).mobxStateTree={},e.mobx)}(this,(function(e,t){"use strict";let n="warn";function i(e){n=e}function s(){return n}var r;function o(e){return he(e).type}function a(e,t){return he(e).onPatch(t)}function c(e,t){he(e).applyPatches(Pe(t))}function h(e,t){return he(e).applySnapshot(t)}function l(e,t=!0){const n=he(e);return t?n.snapshot:n.type.getSnapshot(n,!1)}function u(e){return he(e).root.storedValue}function p(e){return he(e).path}function d(e){return he(e).identifier}function f(e,t){const n=fe(he(e),t,!1);if(void 0!==n)try{return n.value}catch(e){return}}function g(e){return he(e).observableIsAlive}function y(e){let t;return t=ce(e)?o(e):e,{name:t.name,properties:Object.assign({},t.properties)}}!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(r||(r={}));class b{get subpath(){return this._subpath}get subpathUponDeath(){return this._subpathUponDeath}get pathUponDeath(){return this._pathUponDeath}get value(){return this.type.getValue(this)}get state(){return this._state}set state(e){const t=this.isAlive;this._state=e;const n=this.isAlive;this.aliveAtom&&t!==n&&this.aliveAtom.reportChanged()}fireInternalHook(e){this._hookSubscribers&&this._hookSubscribers.emit(e,this,e)}registerHook(e,t){return this._hookSubscribers||(this._hookSubscribers=new De),this._hookSubscribers.register(e,t)}get parent(){return this._parent}constructor(e,t,n,i){this.type=e,this.environment=i,this._subpathUponDeath=void 0,this._pathUponDeath=void 0,this.storedValue=void 0,this.aliveAtom=void 0,this._state=ae.INITIALIZING,this._hookSubscribers=void 0,this.pathAtom=void 0,this.environment=i,this.baseSetParent(t,n)}getReconciliationType(){return this.type}baseSetParent(e,t){this._parent=e,this._subpath=t,this._escapedSubpath=void 0,this.pathAtom&&this.pathAtom.reportChanged()}get path(){return this.getEscapedPath(!0)}getEscapedPath(e){return e&&(this.pathAtom||(this.pathAtom=t.createAtom("path")),this.pathAtom.reportObserved()),this.parent?(void 0===this._escapedSubpath&&(this._escapedSubpath=this._subpath?Me(this._subpath):""),this.parent.getEscapedPath(e)+"/"+this._escapedSubpath):""}get isRoot(){return null===this.parent}get isAlive(){return this.state!==ae.DEAD}get isDetaching(){return this.state===ae.DETACHING}get observableIsAlive(){return this.aliveAtom||(this.aliveAtom=t.createAtom("alive")),this.aliveAtom.reportObserved(),this.isAlive}baseFinalizeCreation(e){if(this.state===ae.CREATED){if(this.parent){if(this.parent.state!==ae.FINALIZED)return;this.fireHook(r.afterAttach)}this.state=ae.FINALIZED,e&&e()}}baseFinalizeDeath(){this._hookSubscribers&&this._hookSubscribers.clearAll(),this._subpathUponDeath=this._subpath,this._pathUponDeath=this.getEscapedPath(!1),this.baseSetParent(null,""),this.state=ae.DEAD}baseAboutToDie(){this.fireHook(r.beforeDestroy)}}class v extends b{constructor(e,t,n,i,s){super(e,t,n,i);try{this.storedValue=e.createNewInstance(s)}catch(e){throw this.state=ae.DEAD,e}this.state=ae.CREATED,this.finalizeCreation()}get root(){if(!this.parent)throw new _e("This scalar node is not part of a tree");return this.parent.root}setParent(e,t){const n=this.parent!==e,i=this.subpath!==t;(n||i)&&(this.environment=void 0,this.baseSetParent(this.parent,t))}get snapshot(){return this.getSnapshot()}getSnapshot(){return this.type.getSnapshot(this)}toString(){const e=(this.isAlive?this.path:this.pathUponDeath)||"<root>";return`${this.type.name}@${e}${this.isAlive?"":" [dead]"}`}die(){this.isAlive&&this.state!==ae.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}finalizeCreation(){this.baseFinalizeCreation()}aboutToDie(){this.baseAboutToDie()}finalizeDeath(){this.baseFinalizeDeath()}fireHook(e){this.fireInternalHook(e)}}v.prototype.die=t.action(v.prototype.die);let m=1;var w,_;!function(e){e[e.UNINITIALIZED=0]="UNINITIALIZED",e[e.CREATING=1]="CREATING",e[e.CREATED=2]="CREATED"}(w||(w={})),function(e){e.Dispose="dispose",e.Patch="patch",e.Snapshot="snapshot"}(_||(_={}));const S={fireImmediately:!0,onError(e){throw e}};class A extends b{applyPatches(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)}applySnapshot(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)}constructor(e,n,i,s,r){super(e,n,i,s),this.nodeId=++m,this.identifierCache=void 0,this.isProtectionEnabled=!0,this.middlewares=void 0,this.hasSnapshotPostProcessor=!1,this._applyPatches=void 0,this._applySnapshot=void 0,this._autoUnbox=!0,this._isRunningAction=!1,this._hasSnapshotReaction=!1,this._endOfActionCallbacks=void 0,this._observableInstanceState=w.UNINITIALIZED,this._cachedInitialSnapshot=void 0,this._cachedInitialSnapshotCreated=!1,this._snapshotUponDeath=void 0,this._internalEvents=void 0;const o={node:this};if(this._snapshotSource=o,this._snapshotComputed=t.computed(()=>{const e=o.node;if(!e)return o.snapshotUponDeath;const n=e.getSnapshot();return e.state===ae.INITIALIZING&&e._cachedInitialSnapshotCreated&&t.compareShallow(n,e._cachedInitialSnapshot)?e._cachedInitialSnapshot:n},{keepAlive:!0}),this.unbox=this.unbox.bind(this),this._initialSnapshot=r,this.identifierAttribute=e.identifierAttribute,n||(this.identifierCache=new se),this._childNodes=e.initializeChildNodes(this,this._initialSnapshot),this.identifier=null,this.unnormalizedIdentifier=null,this.identifierAttribute&&this._initialSnapshot){let e=this._initialSnapshot[this.identifierAttribute];if(void 0===e){const t=this._childNodes[this.identifierAttribute];t&&(e=t.value)}if("string"!=typeof e&&"number"!=typeof e&&"bigint"!=typeof e)throw new _e(`Instance identifier '${this.identifierAttribute}' for type '${this.type.name}' must be a string, a number or a bigint`);this.identifier=qt(e),this.unnormalizedIdentifier=e}n?n.root.identifierCache.addNodeToCache(this):this.identifierCache.addNodeToCache(this)}createObservableInstanceIfNeeded(e=!0){this._observableInstanceState===w.UNINITIALIZED&&this.createObservableInstance(e)}createObservableInstance(e=!0){this._observableInstanceState=w.CREATING;const t=[];let n=this.parent;for(;n&&n._observableInstanceState===w.UNINITIALIZED;)t.unshift(n),n=n.parent;for(const e of t)e.createObservableInstanceIfNeeded(!1);const i=this.type;try{this.storedValue=i.createNewInstance(this._childNodes),this.preboot(),this._isRunningAction=!0,i.finalizeNewInstance(this,this.storedValue)}catch(e){throw this.state=ae.DEAD,e}finally{this._isRunningAction=!1}if(this._observableInstanceState=w.CREATED,this._snapshotComputed.trackAndCompute(),this._childNodes=me,this.state=ae.CREATED,e){this.fireHook(r.afterCreate),this.finalizeCreation();for(const e of t.reverse())e.fireHook(r.afterCreate),e.finalizeCreation()}}get root(){const e=this.parent;return e?e.root:this}enqueueEndOfAction(e){const t=this.root;t._endOfActionCallbacks||(t._endOfActionCallbacks=[]),t._endOfActionCallbacks.push(e)}flushEndOfActionCallbacks(){const e=this.root;for(;e._endOfActionCallbacks&&e._endOfActionCallbacks.length>0;){const t=e._endOfActionCallbacks;e._endOfActionCallbacks=void 0,t.forEach(e=>{e()})}}clearParent(){if(!this.parent)return;this.fireHook(r.beforeDetach);const e=this.state;this.state=ae.DETACHING;const t=this.root,n=t.environment,i=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=n,this.identifierCache=i}finally{this.state=e}}setParent(e,t){const n=e!==this.parent,i=t!==this.subpath;(n||i)&&(n?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(r.afterAttach)):i&&this.baseSetParent(this.parent,t))}fireHook(e){this.fireInternalHook(e);const n=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof n&&(t._allowStateChangesInsideComputed?t._allowStateChangesInsideComputed(()=>{n.apply(this.storedValue)}):n.apply(this.storedValue))}get snapshot(){return this.hasSnapshotPostProcessor&&this.createObservableInstanceIfNeeded(),this._snapshotComputed.get()}getSnapshot(){return this.isAlive?this._observableInstanceState===w.CREATED?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath}_getActualSnapshot(){return this.type.getSnapshot(this)}_getCachedInitialSnapshot(){if(!this._cachedInitialSnapshotCreated){const e=this.type,t=this._childNodes,n=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,n),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot}isRunningAction(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()}assertAlive(e){const t=s();if(!this.isAlive&&"ignore"!==t){const i=this._getAssertAliveError(e);switch(t){case"error":throw new _e(i);case"warn":n=i,console.warn(new Error("[mobx-state-tree] "+n))}}var n}_getAssertAliveError(e){const t=this.getEscapedPath(!1)||this.pathUponDeath||"",n=e.subpath&&Me(e.subpath)||"";let i=e.actionContext||R();i&&"action"!==i.type&&i.parentActionEvent&&(i=i.parentActionEvent);let s="";if(i&&null!=i.name){s=`${i&&i.context&&p(i.context)||t}.${i.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: '${s}'). Either detach nodes first, or don't use objects after removing / replacing them in the tree.`}getChildNode(e){this.assertAlive({subpath:e}),this._autoUnbox=!1;try{return this._observableInstanceState===w.CREATED?this.type.getChildNode(this,e):this._childNodes[e]}finally{this._autoUnbox=!0}}getChildren(){this.assertAlive(me),this._autoUnbox=!1;try{return this._observableInstanceState===w.CREATED?this.type.getChildren(this):ye(this._childNodes)}finally{this._autoUnbox=!0}}getChildType(e){return this.type.getChildType(e)}get isProtected(){return this.root.isProtectionEnabled}assertWritable(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw new _e(`Cannot modify '${this}', the object is protected and can only be modified by using an action.`)}removeChild(e){this.type.removeChild(this,e)}unbox(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e}toString(){const e=(this.isAlive?this.path:this.pathUponDeath)||"<root>",t=this.identifier?`(id: ${this.identifier})`:"";return`${this.type.name}@${e}${t}${this.isAlive?"":" [dead]"}`}finalizeCreation(){this.baseFinalizeCreation(()=>{for(let e of this.getChildren())e.finalizeCreation();this.fireInternalHook(r.afterCreationFinalization)})}detach(){if(!this.isAlive)throw new _e("Error while detaching, node is not alive.");this.clearParent()}preboot(){const e=this;this._applyPatches=L(this.storedValue,"@APPLY_PATCHES",t=>{t.forEach(t=>{if(!t.path)return void e.type.applySnapshot(e,t.value);const n=Ue(t.path);ge(e,n.slice(0,-1),!0,!$e(t.path,"/")).applyPatchLocally(n[n.length-1],t)})}),this._applySnapshot=L(this.storedValue,"@APPLY_SNAPSHOT",t=>{if(t!==e.snapshot)return e.type.applySnapshot(e,t)}),Ve(this.storedValue,"$treenode",this),Ve(this.storedValue,"toJSON",ue)}die(){this.isAlive&&this.state!==ae.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}aboutToDie(){this._observableInstanceState!==w.UNINITIALIZED&&(this.getChildren().forEach(e=>{e.aboutToDie()}),this.baseAboutToDie(),this._internalEventsEmit(_.Dispose),this._internalEventsClear(_.Dispose))}finalizeDeath(){this.getChildren().forEach(e=>{e.finalizeDeath()}),this.root.identifierCache.notifyDied(this);const e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath(),this._snapshotSource.snapshotUponDeath=e,this._snapshotSource.node=void 0,this._snapshotComputed.trackAndCompute()}onSnapshot(e){return this._addSnapshotReaction(),this._internalEventsRegister(_.Snapshot,e)}emitSnapshot(e){this._internalEventsEmit(_.Snapshot,e)}onPatch(e){return this._internalEventsRegister(_.Patch,e)}hasPatchSubscribers(){return!!this._internalEventsHasSubscribers(_.Patch)||!!this.parent&&this.parent.hasPatchSubscribers()}emitPatch(e,t){if(this._internalEventsHasSubscribers(_.Patch)){const n=function(e,...t){for(let n=0;n<t.length;n++){const i=t[n];for(let t in i)e[t]=i[t]}return e}({},e,{path:t.path.substr(this.path.length)+(void 0!==e.path?"/"+e.path:"")}),[i,s]=function(e){if(!("oldValue"in e))throw new _e("Patches without `oldValue` field cannot be inversed");return[ze(e),Fe(e)]}(n);this._internalEventsEmit(_.Patch,i,s)}this.parent&&this.parent.emitPatch(e,t)}hasDisposer(e){return this._internalEventsHas(_.Dispose,e)}addDisposer(e){if(this.hasDisposer(e))throw new _e("cannot add a disposer when it is already registered for execution");this._internalEventsRegister(_.Dispose,e,!0)}removeDisposer(e){if(!this._internalEventsHas(_.Dispose,e))throw new _e("cannot remove a disposer which was never registered for execution");this._internalEventsUnregister(_.Dispose,e)}removeMiddleware(e){if(this.middlewares){const t=this.middlewares.indexOf(e);t>=0&&this.middlewares.splice(t,1)}}addMiddleWare(e,t=!0){const n={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(n):this.middlewares=[n],()=>{this.removeMiddleware(n)}}applyPatchLocally(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)}_addSnapshotReaction(){if(!this._hasSnapshotReaction){let e=t.untracked(()=>this.snapshot);const n=t.reaction(()=>this.snapshot,t=>{t!==e&&(e=t,this.emitSnapshot(t))},S);this.addDisposer(n),this._hasSnapshotReaction=!0}}_internalEventsHasSubscribers(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)}_internalEventsRegister(e,t,n=!1){return this._internalEvents||(this._internalEvents=new De),this._internalEvents.register(e,t,n)}_internalEventsHas(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)}_internalEventsUnregister(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)}_internalEventsEmit(e,...t){this._internalEvents&&this._internalEvents.emit(e,...t)}_internalEventsClear(e){this._internalEvents&&this._internalEvents.clear(e)}_internalEventsClearAll(){this._internalEvents&&this._internalEvents.clearAll()}}var I;A.prototype.createObservableInstance=t.action(A.prototype.createObservableInstance),A.prototype.detach=t.action(A.prototype.detach),A.prototype.die=t.action(A.prototype.die),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",e[e.Lazy=1048576]="Lazy",e[e.Finite=2097152]="Finite",e[e.Float=4194304]="Float",e[e.BigInt=8388608]="BigInt"}(I||(I={}));class P{constructor(e){this.isType=!0,this.name=e}create(e,t){return te(this,e),this.instantiate(null,"",t,e).value}getSnapshot(e,t){throw new _e("unimplemented method")}isAssignableFrom(e){return e===this}validate(e,t){if(le(e)){const n=o(e);return this.isAssignableFrom(n)?Q():X(t,e)}return this.isValidSnapshot(e,t)}is(e){return 0===this.validate(e,[{path:"",type:this}]).length}get Type(){throw new _e("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`")}get TypeWithoutSTN(){throw new _e("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`")}get SnapshotType(){throw new _e("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`")}get CreationType(){throw new _e("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`")}}P.prototype.create=t.action(P.prototype.create);class T extends P{constructor(e){super(e)}create(e=this.getDefaultSnapshot(),t){return super.create(e,t)}getValue(e){return e.createObservableInstanceIfNeeded(),e.storedValue}isMatchingSnapshotId(e,t){return!e.identifierAttribute||e.identifier===qt(t[e.identifierAttribute])}tryToReconcileNode(e,t){return!e.isDetaching&&(e.snapshot===t||(!(!ce(t)||he(t)!==e)||!(e.type!==this||!Ce(t)||ce(t)||!this.isMatchingSnapshotId(e,t))&&(e.applySnapshot(t),!0)))}reconcile(e,t,n,i){if(this.tryToReconcileNode(e,t))return e.setParent(n,i),e;if(e.die(),ce(t)&&this.isAssignableFrom(o(t))){const e=he(t);return e.setParent(n,i),e}return this.instantiate(n,i,void 0,t)}getSubTypes(){return null}}T.prototype.create=t.action(T.prototype.create);class C extends P{createNewInstance(e){return e}getValue(e){return e.storedValue}getSnapshot(e){return e.storedValue}reconcile(e,t,n,i){if(!e.isDetaching&&e.type===this&&e.storedValue===t)return e;const s=this.instantiate(n,i,void 0,t);return e.die(),s}getSubTypes(){return null}}function E(e,t,n){const i=t.getReconciliationType(),s=function e(t){const n=t.getSubTypes();if(!n||Array.isArray(n)||"cannotDetermine"===n||!function(e){const t=I.Optional|I.Late,n=I.Refinement|I.SnapshotProcessor|I.Union;return(e.flags&t)>0&&0==(e.flags&n)}(t))return t;return e(n)}(e);return t instanceof A&&i===s&&i instanceof T&&Ce(n)&&!ce(n)&&i.isMatchingSnapshotId(t,n)}function N(e){return"object"==typeof e&&e&&!0===e.isType}const V=new Map;class O{constructor(e,t){this.hooks=e,this.call=t,this.flowsPending=0,this.running=!0,e&&e.onStart(t)}finish(e){this.running&&(this.running=!1,this.hooks&&this.hooks.onFinish(this.call,e))}incFlowsPending(){this.flowsPending++}decFlowsPending(){this.flowsPending--}get hasFlowsPending(){return this.flowsPending>0}}function D(e){return{$MST_UNSERIALIZABLE:!0,type:e}}function x(e,n){t.runInAction(()=>{Pe(n).forEach(t=>function(e,t){const n=f(e,t.path||"");if(!n)throw new _e("Invalid action path: "+(t.path||""));const i=he(n);if("@APPLY_PATCHES"===t.name)return c.call(null,n,t.args[0]);if("@APPLY_SNAPSHOT"===t.name)return h.call(null,n,t.args[0]);if("function"!=typeof n[t.name])throw new _e(`Action '${t.name}' does not exist in '${i.path}'`);return n[t.name].apply(n,t.args?t.args.map(e=>{return(t=e)&&"object"==typeof t&&"$MST_DATE"in t?new Date(t.$MST_DATE):t;var t}):[])}(e,t))})}function $(e,t,n=!1){return H(e,(function(i,s){if("action"===i.type&&i.id===i.rootId){const r=he(i.context),a={name:i.name,path:de(he(e),r),args:i.args.map((e,t)=>function(e,t,n,i){if(i instanceof Date)return{$MST_DATE:i.getTime()};if(Ee(i))return i;if(ce(i))return D(`[MSTNode: ${o(i).name}]`);if("function"==typeof i)return D("[function]");if("object"==typeof i&&!Te(i)&&!Ie(i))return D(`[object ${i&&i.constructor&&i.constructor.name||"Complex Object"}]`);try{return JSON.stringify(i),i}catch(e){return D(""+e)}}(0,i.name,0,e))};if(n){const e=s(i);return t(a),e}return t(a),s(i)}return s(i)}))}let j,k=1;function R(){return j}function z(){return k++}function F(e,n){const i=he(e.context);"action"===e.type&&i.assertAlive({actionContext:e});const s=i._isRunningAction;i._isRunningAction=!0;const o=j,a=!o;j=e;try{return function(e,n,i,s){function o(n,i){const r=()=>{let t,r;try{t=i.apply(null,n.args)}catch(e){r=e}if(s||!n.parentActionEvent)try{e.root.flushEndOfActionCallbacks()}catch(e){r||(r=e)}if(r)throw r;return t};return n.name?t.action(n.name,r)():t.action(r)()}const a=new U(e,i);if(a.isEmpty)return o(n,i);let c=null;return function e(t){const n=a.getNextMiddleware(),h=n&&n.handler;if(!h)return o(t,i);if(!n.includeHooks&&r[t.name])return e(t);let l=!1;return h(t,(function(t,n){c=e(t),n&&(c=n(c))}),(function(e){l=!0,c=e})),!l||!s&&t.parentActionEvent?c:o(t,()=>c)}(n)}(i,e,n,a)}finally{j=o,i._isRunningAction=s}}function M(e){if(e)return"action"===e.type?e:e.parentActionEvent}function L(e,t,n){const i=function(){const i=z(),s=j,r=M(s);return F({type:"action",name:t,id:i,args:xe(arguments),context:e,tree:u(e),rootId:s?s.rootId:i,parentId:s?s.id:0,allParentIds:s?[...s.allParentIds,s.id]:[],parentEvent:s,parentActionEvent:r},n)};return i._isMSTAction=!0,i._isFlowAction=n._isFlowAction,i}function H(e,t,n=!0){return he(e).addMiddleWare(t,n)}class U{constructor(e,t){this.arrayIndex=0,this.inArrayIndex=0,this.middlewares=[],t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);let n=e;for(;n;)n.middlewares&&this.middlewares.push(n.middlewares),n=n.parent}get isEmpty(){return this.middlewares.length<=0}getNextMiddleware(){const e=this.middlewares[this.arrayIndex];if(!e)return;const t=e[this.inArrayIndex++];return t||(this.arrayIndex++,this.inArrayIndex=0,this.getNextMiddleware())}}function B(){let e=R();for(;e&&"action"!==e.type;)e=e.parentActionEvent;return e}function G(e,t,n){const i="number"==typeof t?t:t.id;let s=n?e:e.parentActionEvent;for(;s;){if(s.id===i)return!0;s=s.parentActionEvent}return!1}let W=Object.assign({},{enabled:!1,indent:2,maxStringLength:100,maxArrayLength:10,maxPropertyCount:30,maxDepth:5});function Z(){return Object.assign({},W)}function Y(e,t){try{return JSON.stringify(e,null,t)}catch(e){return`<Unserializable: ${e}>`}}function J(e){if("function"==typeof e)return`<function${e.name?" "+e.name:""}>`;if(ce(e))return`<${e}>`;const t=Z();if(!t.enabled)return`\`${Y(e)}\``;return`\`${Y(function e(t,n,i){if("string"==typeof t)return t.length>i.maxStringLength?`${t.slice(0,i.maxStringLength)}… (${t.length-i.maxStringLength} more characters)`:t;if(Array.isArray(t)){if(n>=i.maxDepth)return"[…]";const s=t.slice(0,i.maxArrayLength).map(t=>e(t,n+1,i));return t.length>i.maxArrayLength&&s.push(`… ${t.length-i.maxArrayLength} more items`),s}if(Te(t)){if(n>=i.maxDepth)return"{…}";const s={},r=Object.keys(t);return r.slice(0,i.maxPropertyCount).forEach(r=>{s[r]=e(t[r],n+1,i)}),r.length>i.maxPropertyCount&&(s["…"]=r.length-i.maxPropertyCount+" more keys"),s}return t}(e,0,t),t.indent||void 0)}\``}function q(e){const{value:t}=e,n=e.context[e.context.length-1].type,i=e.context.map(({path:e})=>e).filter(e=>e.length>0).join("/"),s=i.length>0?`at path "/${i}" `:"",r=ce(t)?`value of type ${he(t).type.name}:`:Ee(t)?"value":"snapshot",o=n&&ce(t)&&n.is(he(t).snapshot),a=Z();return`${s}${r} ${J(t)} is not assignable ${n?`to type: \`${n.name}\``:""}`+(e.message?` (${e.message})`:"")+(n?At(n)||Ee(t)?".":`, expected an instance of \`${n.name}\` or a snapshot like \`${c=n,a.enabled?function(e,t){if(t<=0)return e;try{const n=" ".repeat(t);let i="",s=0,r=null,o=!1;const a=()=>{i=i.replace(/[ \t]+$/,""),i+="\n"+n.repeat(Math.max(0,s))};for(let t=0;t<e.length;t++){const n=e[t];if(r)i+=n,o?o=!1:"\\"===n?o=!0:n===r&&(r=null);else switch(n){case'"':case"'":r=n,i+=n;break;case"{":for(s++,i+="{",a();" "===e[t+1];)t++;break;case"}":s--,a(),i+="}";break;case";":for(i+=";",a();" "===e[t+1];)t++;break;default:i+=n}}return i}catch(t){return e}}(c.describe(),a.indent):c.describe()}\` instead.`+(o?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".");var c}function K(e,t,n){return e.concat([{path:t,type:n}])}function Q(){return ve}function X(e,t,n){return[{context:e,value:t,message:n}]}function ee(e){return e.reduce((e,t)=>e.concat(t),[])}function te(e,t){"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK&&ne(e,t)}function ne(e,t){const n=e.validate(t,[{path:"",type:e}]);if(n.length>0)throw new _e(function(e,t,n){if(0===n.length)return;const i=J(t);return`Error while converting ${Z().enabled?i:(s=i,s.length<280?s:`${s.substring(0,272)}......${s.substring(s.length-8)}`)} to \`${e.name}\`:\n\n    `+n.map(q).join("\n    ");var s}(e,t,n))}let ie=0;class se{constructor(){this.cacheId=ie++,this.cache=t.observable.map(),this.lastCacheModificationPerId=t.observable.map()}updateLastCacheModificationPerId(e){const t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)}getLastCacheModificationPerId(e){const t=this.lastCacheModificationPerId.get(e)||0;return`${this.cacheId}-${t}`}addNodeToCache(e,n=!0){if(e.identifierAttribute){const i=e.identifier;this.cache.has(i)||this.cache.set(i,t.observable.array([],we));const s=this.cache.get(i);if(-1!==s.indexOf(e))throw new _e("Already registered");s.push(e),n&&this.updateLastCacheModificationPerId(i)}}mergeCache(e){t.values(e.identifierCache.cache).forEach(e=>e.forEach(e=>{this.addNodeToCache(e)}))}notifyDied(e){if(e.identifierAttribute){const t=e.identifier,n=this.cache.get(t);n&&(n.remove(e),n.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}}splitCache(e){const t=new se;if(0===this.cache.size)return t;const n=e=>{e instanceof A&&(this.notifyDied(e),t.addNodeToCache(e,!1),e.getChildren().forEach(n))};return n(e),t}has(e,t){const n=this.cache.get(t);return!!n&&n.some(t=>e.isAssignableFrom(t.type))}resolve(e,t){const n=this.cache.get(t);if(!n)return null;const i=n.filter(t=>e.isAssignableFrom(t.type));switch(i.length){case 0:return null;case 1:return i[0];default:throw new _e(`Cannot resolve a reference to type '${e.name}' with id: '${t}' unambigously, there are multiple candidates: ${i.map(e=>e.path).join(", ")}`)}}}function re(e,t,n,i,s){const r=le(s);if(r){if(r.parent)throw new _e(`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 '${r.path}'`);return t&&r.setParent(t,n),r}return new A(e,t,n,i,s)}function oe(e,t,n,i,s){return new v(e,t,n,i,s)}var ae;function ce(e){return!(!e||!e.$treenode)}function he(e){if(!ce(e))throw new _e(`Value ${e} is no MST Node`);return e.$treenode}function le(e){return e&&e.$treenode||null}function ue(){return he(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"}(ae||(ae={}));const pe=e=>"..";function de(e,t){if(e.root!==t.root)throw new _e(`Cannot calculate relative path: objects '${e}' and '${t}' are not part of the same object tree`);const n=Ue(e.path),i=Ue(t.path);let s=0;for(;s<n.length&&n[s]===i[s];s++);return n.slice(s).map(pe).join("/")+He(i.slice(s))}function fe(e,t,n=!0){return ge(e,Ue(t),n)}function ge(e,t,n=!0,i=!0){let s=e;try{for(let e=0;e<t.length;e++){const n=t[e];if(i&&".."===n){if(s=s.parent,s)continue}else{if(i&&"."===n)continue;if(s){if(s instanceof v){const e=s.value;ce(e)&&(s=he(e))}if(s instanceof A){if(s.getChildType(n)&&(s=s.getChildNode(n),s))continue}}}throw new _e(`Could not resolve '${n}' in path '${He(t.slice(0,e))||"/"}' while resolving '${He(t)}'`)}}catch(e){if(!n)return;throw e}return s}function ye(e){if(!e)return ve;const t=Object.keys(e);if(!t.length)return ve;const n=new Array(t.length);return t.forEach((t,i)=>{n[i]=e[t]}),n}const be=Object.toString(),ve=Object.freeze([]),me=Object.freeze({}),we={deep:!1};Object.freeze(we);class _e extends Error{constructor(e="Illegal state"){super("[mobx-state-tree] "+e)}}function Se(e){return e}const Ae=Number.isInteger;function Ie(e){return Array.isArray(e)||t.isObservableArray(e)}function Pe(e){return e?Ie(e)?e:[e]:ve}function Te(e){var t;if(null===e||"object"!=typeof e)return!1;const n=Object.getPrototypeOf(e);return null==n||(null===(t=n.constructor)||void 0===t?void 0:t.toString())===be}function Ce(e){return!(null===e||"object"!=typeof e||e instanceof Date||e instanceof RegExp)}function Ee(e,t=!0){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e||t&&e instanceof Date}function Ne(e){return"function"!=typeof e}function Ve(e,n,i){!function(e,n,i){t.isObservableObject(e)?t.defineProperty(e,n,i):Object.defineProperty(e,n,i)}(e,n,{enumerable:!1,writable:!1,configurable:!0,value:i})}class Oe{constructor(){this.handlers=[]}get hasSubscribers(){return this.handlers.length>0}register(e,t=!1){return t?this.handlers.unshift(e):this.handlers.push(e),()=>{this.unregister(e)}}has(e){return this.handlers.indexOf(e)>=0}unregister(e){const t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}clear(){this.handlers.length=0}emit(...e){this.handlers.slice().forEach(t=>t(...e))}}class De{hasSubscribers(e){const t=this.eventHandlers&&this.eventHandlers[e];return!!t&&t.hasSubscribers}register(e,t,n=!1){this.eventHandlers||(this.eventHandlers={});let i=this.eventHandlers[e];return i||(i=this.eventHandlers[e]=new Oe),i.register(t,n)}has(e,t){const n=this.eventHandlers&&this.eventHandlers[e];return!!n&&n.has(t)}unregister(e,t){const n=this.eventHandlers&&this.eventHandlers[e];n&&n.unregister(t)}clear(e){this.eventHandlers&&delete this.eventHandlers[e]}clearAll(){this.eventHandlers=void 0}emit(e,...t){const n=this.eventHandlers&&this.eventHandlers[e];n&&n.emit(...t)}}function xe(e){const t=new Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function $e(e,t){return 0===e.indexOf(t)}const je=function(e,t){};function ke(e){"function"==typeof queueMicrotask?queueMicrotask(e):"function"==typeof setImmediate?setImmediate(e):setTimeout(e,1)}function Re(e){return function(e,t){const n=function(){const i=z(),s=R();if(!s)throw new _e("a mst flow must always have a parent context");const r=M(s);if(!r)throw new _e("a mst flow must always have a parent action context");const o={name:e,id:i,tree:s.tree,context:s.context,parentId:s.id,allParentIds:[...s.allParentIds,s.id],rootId:s.rootId,parentEvent:s,parentActionEvent:r},a=arguments;function c(e,t,i){return e.$mst_middleware=n.$mst_middleware,F(Object.assign(Object.assign({},o),{type:t,args:[i]}),e)}return new Promise((function(e,i){let s;const r=function(){s=t.apply(null,arguments),h(void 0)};function h(e){let t;try{const n=c(e=>{t=s.next(e)},"flow_resume",e);n instanceof Error&&(t=s.throw(n))}catch(e){return void ke(()=>{c(t=>{i(e)},"flow_throw",e)})}u(t)}function l(e){let t;try{c(e=>{t=s.throw(e)},"flow_resume_error",e)}catch(e){return void ke(()=>{c(t=>{i(e)},"flow_throw",e)})}u(t)}function u(t){if(!t.done){if(!t.value||"function"!=typeof t.value.then)throw new _e("Only promises can be yielded to `async`, got: "+t);return t.value.then(h,l)}ke(()=>{c(t=>{e(t)},"flow_return",t.value)})}r.$mst_middleware=n.$mst_middleware,F(Object.assign(Object.assign({},o),{type:"flow_spawn",args:xe(a)}),r)}))};return n._isFlowAction=!0,n}(e.name,e)}function ze(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 Fe(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 Me(e){return!0==("number"==typeof e)?""+e:-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Le(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function He(e){if(0===e.length)return"";const t=e=>e.map(Me).join("/");return"."===e[0]||".."===e[0]?t(e):"/"+t(e)}function Ue(e){const t=e.split("/").map(Le);if(!(""===e||"."===e||".."===e||$e(e,"/")||$e(e,"./")||$e(e,"../")))throw new _e(`a json path must be either rooted, empty or relative, but got '${e}'`);return""===t[0]&&t.shift(),t}je.ids={};const Be=Symbol("$preProcessorFailed");class Ge extends P{get flags(){return this._subtype.flags|I.SnapshotProcessor}constructor(e,t,n){super(n||e.name),this._subtype=e,this._processors=t}describe(){return`snapshotProcessor(${this._subtype.describe()})`}preProcessSnapshot(e){return this._processors.preProcessor?this._processors.preProcessor.call(null,e):e}preProcessSnapshotSafe(e){try{return this.preProcessSnapshot(e)}catch(e){return Be}}postProcessSnapshot(e,t){return this._processors.postProcessor?this._processors.postProcessor.call(null,e,t.storedValue):e}_fixNode(e){!function(e,t,...n){for(const i of n)e[i]=t[i].bind(t)}(e.type,this,"create"),e instanceof A&&(e.hasSnapshotPostProcessor=!!this._processors.postProcessor);const t=e.getSnapshot;e.getSnapshot=()=>this.postProcessSnapshot(t.call(e),e),e instanceof A&&e.state!==ae.INITIALIZING&&e._snapshotComputed.trackAndCompute(),Nt(this._subtype)||(e.getReconciliationType=()=>this)}instantiate(e,t,n,i){const s=ce(i)?i:this.preProcessSnapshot(i),r=this._subtype.instantiate(e,t,n,s);return this._fixNode(r),r}reconcile(e,t,n,i){const s=this._subtype.reconcile(e,ce(t)?t:this.preProcessSnapshot(t),n,i);return s!==e&&this._fixNode(s),s}getSnapshot(e,t=!0){const n=this._subtype.getSnapshot(e);return t?this.postProcessSnapshot(n,e):n}isValidSnapshot(e,t){const n=this.preProcessSnapshotSafe(e);return n===Be?X(t,e,"Failed to preprocess value"):this._subtype.validate(n,t)}getSubTypes(){return this._subtype}is(e){const t=N(e)?this._subtype:ce(e)?e:this.preProcessSnapshotSafe(e);return t!==Be&&0===this._subtype.validate(t,[{path:"",type:this._subtype}]).length}isAssignableFrom(e){return this._subtype.isAssignableFrom(e)}isMatchingSnapshotId(e,t){if(!(this._subtype instanceof T))return!1;const n=this.preProcessSnapshot(t);return this._subtype.isMatchingSnapshotId(e,n)}}const We="Map.put can only be used to store complex values that have an identifier type attribute";var Ze;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.YES=1]="YES",e[e.NO=2]="NO"}(Ze||(Ze={}));class Ye extends t.ObservableMap{constructor(e,t){super(e,e=>e,t)}get(e){return super.get(""+e)}has(e){return super.has(""+e)}delete(e){return super.delete(""+e)}set(e,t){return super.set(""+e,t)}put(e){if(!e)throw new _e("Map.put cannot be used to set empty values");if(ce(e)){const t=he(e);if(null===t.identifier)throw new _e(We);return this.set(t.identifier,e),e}if(Ce(e)){const t=he(this),n=t.type;if(n.identifierMode!==Ze.YES)throw new _e(We);const i=e[n.mapIdentifierAttribute];if(!Kt(i)){const i=this.put(n.getChildType().create(e,t.environment));return this.put(l(i))}const s=qt(i);return this.set(s,e),this.get(s)}throw new _e("Map.put can only be used to store complex values")}}class Je extends T{constructor(e,t,n=[]){super(e),this._subType=t,this.identifierMode=Ze.UNKNOWN,this.mapIdentifierAttribute=void 0,this.flags=I.Map,this.hookInitializers=[],this._determineIdentifierMode(),this.hookInitializers=n}hooks(e){const t=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new Je(this.name,this._subType,t)}instantiate(e,t,n,i){return this._determineIdentifierMode(),re(this,e,t,n,i)}_determineIdentifierMode(){if(this.identifierMode!==Ze.UNKNOWN)return;const e=[];if(function e(t,n){const i=t.getSubTypes();if("cannotDetermine"===i)return!1;if(i){const t=Pe(i);for(const i of t)if(!e(i,n))return!1}return t instanceof ct&&n.push(t),!0}(this._subType,e)){const t=e.reduce((e,t)=>{if(!t.identifierAttribute)return e;if(e&&e!==t.identifierAttribute)throw new _e(`The objects in a map should all have the same identifier attribute, expected '${e}', but child of type '${t.name}' declared attribute '${t.identifierAttribute}' as identifier`);return t.identifierAttribute},void 0);t?(this.identifierMode=Ze.YES,this.mapIdentifierAttribute=t):this.identifierMode=Ze.NO}}initializeChildNodes(e,t={}){const n=e.type._subType,i={};return Object.keys(t).forEach(s=>{i[s]=n.instantiate(e,s,void 0,t[s])}),i}createNewInstance(e){return new Ye(e,this.name)}finalizeNewInstance(e,n){t._interceptReads(n,e.unbox);e.type.hookInitializers.forEach(e=>{const t=e(n);Object.keys(t).forEach(e=>{const i=t[e],s=L(n,e,i);Ve(n,e,s)})}),t.intercept(n,this.willChange),t.observe(n,this.didChange)}describe(){return this.name}getChildren(e){return t.values(e.storedValue)}getChildNode(e,t){const n=e.storedValue.get(""+t);if(!n)throw new _e("Not a child "+t);return n}willChange(e){const t=he(e.object),n=e.name;t.assertWritable({subpath:n});const i=t.type,s=i._subType;switch(e.type){case"update":{const{newValue:r}=e;if(r===e.object.get(n))return null;te(s,r),e.newValue=s.reconcile(t.getChildNode(n),e.newValue,t,n),i.processIdentifier(n,e.newValue)}break;case"add":te(s,e.newValue),e.newValue=s.instantiate(t,n,void 0,e.newValue),i.processIdentifier(n,e.newValue)}return e}processIdentifier(e,t){if(this.identifierMode===Ze.YES&&t instanceof A){const n=t.identifier;if(n!==e)throw new _e(`A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '${n}', but expected: '${e}'`)}}getSnapshot(e){const t={};return e.getChildren().forEach(e=>{t[e.subpath]=e.snapshot}),t}processInitialSnapshot(e){const t={};return Object.keys(e).forEach(n=>{t[n]=e[n].getSnapshot()}),t}didChange(e){const t=he(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:Me(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:Me(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":const n=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:Me(e.name),oldValue:n},t)}}applyPatchLocally(e,t,n){const i=e.storedValue;switch(n.op){case"add":case"replace":i.set(t,n.value);break;case"remove":i.delete(t)}}applySnapshot(e,t){if(!Te(t))return void te(this,t);const n=e.storedValue,i=this.getChildType();Array.from(n.keys()).forEach(s=>{if(!Object.prototype.hasOwnProperty.call(t,s))return void n.delete(s);const r=e.getChildNode(s),o=t[s];r.snapshot!==o&&(E(i,r,o)?r.applySnapshot(o):n.set(s,o))});for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&!n.has(e)&&n.set(e,t[e])}getChildType(){return this._subType}isValidSnapshot(e,t){return Te(e)?ee(Object.keys(e).map(n=>this._subType.validate(e[n],K(t,n,this._subType)))):X(t,e,"Value is not a plain object")}getDefaultSnapshot(){return me}removeChild(e,t){e.storedValue.delete(t)}}Je.prototype.applySnapshot=t.action(Je.prototype.applySnapshot);class qe extends T{constructor(e,t,n=[]){super(e),this._subType=t,this.flags=I.Array,this.hookInitializers=[],this.hookInitializers=n}hooks(e){const t=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new qe(this.name,this._subType,t)}instantiate(e,t,n,i){return re(this,e,t,n,i)}initializeChildNodes(e,t=[]){const n=e.type._subType,i={};return t.forEach((t,s)=>{const r=""+s;i[r]=n.instantiate(e,r,void 0,t)}),i}createNewInstance(e){const n=Object.assign(Object.assign({},we),{name:this.name});return t.observable.array(ye(e),n)}finalizeNewInstance(e,n){t._getAdministration(n).dehancer=e.unbox;e.type.hookInitializers.forEach(e=>{const t=e(n);Object.keys(t).forEach(e=>{const i=t[e],s=L(n,e,i);Ve(n,e,s)})}),t.intercept(n,this.willChange),t.observe(n,this.didChange)}describe(){return this.name}getChildren(e){return e.storedValue.slice()}getChildNode(e,t){const n=Number(t);if(n<e.storedValue.length)return e.storedValue[n];throw new _e("Not a child: "+t)}willChange(e){const t=he(e.object);t.assertWritable({subpath:""+e.index});const n=t.type._subType,i=t.getChildren();switch(e.type){case"update":{if(e.newValue===e.object[e.index])return null;const s=Qe(t,n,[i[e.index]],[e.newValue],[e.index]);if(!s)return null;e.newValue=s[0]}break;case"splice":{const{index:s,removedCount:r,added:o}=e,a=Qe(t,n,i.slice(s,s+r),o,o.map((e,t)=>s+t));if(!a)return null;e.added=a;for(let e=s+r;e<i.length;e++)i[e].setParent(t,""+(e+o.length-r))}}return e}getSnapshot(e){return e.getChildren().map(e=>e.snapshot)}processInitialSnapshot(e){const t=[];return Object.keys(e).forEach(n=>{t.push(e[n].getSnapshot())}),t}didChange(e){const t=he(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:""+e.index,value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"splice":if(e.removedCount&&e.addedCount===e.object.length)return void t.emitPatch({op:"replace",value:t.snapshot,oldValue:e.removed.map(e=>e.snapshot)},t);for(let n=e.removedCount-1;n>=0;n--)t.emitPatch({op:"remove",path:""+(e.index+n),oldValue:e.removed[n].snapshot},t);for(let n=0;n<e.addedCount;n++)t.emitPatch({op:"add",path:""+(e.index+n),value:e.added[n].snapshot,oldValue:void 0},t);return}}applyPatchLocally(e,t,n){const i=e.storedValue,s="-"===t?i.length:Number(t);switch(n.op){case"replace":i[s]=n.value;break;case"add":i.splice(s,0,n.value);break;case"remove":i.splice(s,1)}}applySnapshot(e,t){if(!Ie(t))return void te(this,t);const n=e.storedValue,i=e.getChildren(),s=i.length,r=t.length,o=this.getChildType(),a=function(e,t,n){let i=0;for(;i<n&&e[i].snapshot===t[i];)i++;return i}(i,t,Math.min(s,r));if(a===s&&a===r)return;if(s!==r||e.hasPatchSubscribers()||function(e,t,n){let i;for(let s=n;s<e.length;s++){const r=e[s];if(r.snapshot!==t[s]&&Ke(r,t[s])&&(i||(i=new Set(e.slice(n).map(e=>e.identifier))),i.has(qt(t[s][r.identifierAttribute]))))return!0}return!1}(i,t,a))return void n.replace(t);if(function(e,t,n,i){for(let s=i;s<t.length;s++){const i=t[s];if(i.snapshot!==n[s]){if(!E(e,i,n[s]))return!1;if(!i.identifierAttribute||null===i.identifier)return!1}}return!0}(o,i,t,a))return void function(e,t,n){for(let i=n;i<e.length;i++){const n=e[i];n.snapshot!==t[i]&&n.applySnapshot(t[i])}}(i,t,a);const c=[];for(let e=a;e<s;e++)i[e].snapshot!==t[e]&&c.push(e);for(const e of c)n[e]=t[e]}getChildType(){return this._subType}isValidSnapshot(e,t){return Ie(e)?ee(e.map((e,n)=>this._subType.validate(e,K(t,""+n,this._subType)))):X(t,e,"Value is not an array")}getDefaultSnapshot(){return ve}removeChild(e,t){e.storedValue.splice(Number(t),1)}}function Ke(e,t){return e instanceof A&&null!==e.identifier&&!!e.identifierAttribute&&Te(t)&&e.getReconciliationType()===e.type&&!e.type.isMatchingSnapshotId(e,t)}function Qe(e,t,n,i,s){let r=!0;for(let a=0;;a++){const c=a<=i.length-1,h=n[a];let l=c?i[a]:void 0;const u=""+s[a];if(((o=l)instanceof v||o instanceof A)&&(l=l.storedValue),!h&&!c)break;if(c)if(h)if(et(h,l))n[a]=Xe(t,e,u,l,h);else{let i=void 0;for(let e=a;e<n.length;e++)if(et(n[e],l)){i=n.splice(e,1)[0];break}r=!1;const s=Xe(t,e,u,l,i);n.splice(a,0,s)}else{if(ce(l)&&he(l).parent===e)throw new _e(`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 '${e.path}/${u}', but it lives already at '${he(l).path}'`);r=!1;const i=Xe(t,e,u,l);n.splice(a,0,i)}else r=!1,n.splice(a,1),h instanceof A&&h.createObservableInstanceIfNeeded(),h.die(),a--}var o;return r?null:n}function Xe(e,t,n,i,s){te(e,i);const r=function(){if(ce(i)){const e=he(i);if(e.assertAlive(me),null!==e.parent&&e.parent===t)return e.setParent(t,n),e}return s?e.reconcile(s,i,t,n):e.instantiate(t,n,void 0,i)}();return s&&s!==r&&(s instanceof A&&s.createObservableInstanceIfNeeded(),s.die()),r}function et(e,t){if(!e.isAlive)return!1;if(ce(t)){const n=he(t);return n.isAlive&&n===e}if(e.snapshot===t)return!0;if(!(e instanceof A))return!1;if(Ke(e,t))return!1;const n=e.getReconciliationType();return null!==e.identifier&&e.identifierAttribute&&Te(t)&&n.is(t)&&n.isMatchingSnapshotId(e,t)}qe.prototype.applySnapshot=t.action(qe.prototype.applySnapshot),"function"==typeof SuppressedError&&SuppressedError;const tt=new WeakMap;let nt=!1;function it(e,t,n){if(!nt)return;const i=function(e){let t=tt.get(e);return t||(t=new Map,tt.set(e,t)),t}(e),s=i.get(t);if(void 0!==s&&s!==n)throw new _e(`'${t}' already exists as ${s} and cannot be declared as ${n}`);i.set(t,n)}const st=e=>(tt.delete(e),e);function rt(){return he(this).toString()}const ot={name:"AnonymousModel",properties:{},initializers:ve};function at(e){const t=Object.keys(e),n=new Set;return t.forEach(e=>{if(n.has(e))throw new _e(e+" is declared twice in the model. Model should not contain the same keys");n.add(e)}),t.reduce((t,n)=>{if(n in r)throw new _e(`Hook '${n}' was defined as property. Hooks should be defined as part of the actions`);const i=Object.getOwnPropertyDescriptor(e,n);if("get"in i)throw new _e("Getters are not supported as properties. Please use views instead");const s=i.value;if(null==s)throw new _e("The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?");if(Ee(s))t[n]=Ot(function(e){switch(typeof e){case"string":return ut;case"number":return pt;case"boolean":return vt;case"bigint":return bt;case"object":if(e instanceof Date)return St}throw new _e("Cannot determine primitive type from value "+e)}(s),s);else if(s instanceof Je)t[n]=Ot(s,{});else if(s instanceof qe)t[n]=Ot(s,[]);else if(!N(s))throw new _e(`Invalid type definition for property '${n}', cannot infer a type from a value like '${s}' (${typeof s})`);return t},Object.assign({},e))}class ct extends T{constructor(e){super(e.name||ot.name),this.flags=I.Object,this.named=e=>this.cloneAndEnhance({name:e}),this.props=e=>this.cloneAndEnhance({properties:e}),this.preProcessSnapshot=e=>{const t=this.preProcessor;return t?this.cloneAndEnhance({preProcessor:n=>t(e(n))}):this.cloneAndEnhance({preProcessor:e})},this.postProcessSnapshot=e=>{const t=this.postProcessor;return t?this.cloneAndEnhance({postProcessor:n=>e(t(n))}):this.cloneAndEnhance({postProcessor:e})},Object.assign(this,ot,e),this.properties=at(this.properties),this.properties,this.propertyNames=Object.keys(this.properties),this.identifierAttribute=this._getIdentifierAttribute()}_getIdentifierAttribute(){let e=void 0;return this.forAllProps((t,n)=>{if(n.flags&I.Identifier){if(e)throw new _e(`Cannot define property '${t}' as object identifier, property '${e}' is already defined as identifier property`);e=t}}),e}cloneAndEnhance(e){return new ct({name:e.name||this.name,properties:Object.assign({},this.properties,e.properties),initializers:this.initializers.concat(e.initializers||[]),preProcessor:e.preProcessor||this.preProcessor,postProcessor:e.postProcessor||this.postProcessor})}actions(e){return this.cloneAndEnhance({initializers:[t=>(this.instantiateActions(t,e(t)),t)]})}instantiateActions(e,t){if(!Te(t))throw new _e("actions initializer should return a plain object containing actions");Object.getOwnPropertyNames(t).forEach(n=>{if(n in this.properties)throw new _e(`'${n}' is a property and cannot be declared as an action`);if(it(e,n,"an action"),"preProcessSnapshot"===n)throw new _e("Cannot define action 'preProcessSnapshot', it should be defined using 'type.preProcessSnapshot(fn)' instead");if("postProcessSnapshot"===n)throw new _e("Cannot define action 'postProcessSnapshot', it should be defined using 'type.postProcessSnapshot(fn)' instead");let i=t[n],s=e[n];if(n in r&&s){let e=i;i=function(){s.apply(null,arguments),e.apply(null,arguments)}}const o=i.$mst_middleware;let a=i.bind(t);a._isFlowAction=i._isFlowAction||!1,a.$mst_middleware=o;const c=L(e,n,a);t[n]=c,Ve(e,n,c)})}volatile(e){if("function"!=typeof e)throw new _e(`You passed an ${typeof e} to volatile state as an argument, when function is expected`);return this.cloneAndEnhance({initializers:[t=>(this.instantiateVolatileState(t,e(t)),t)]})}instantiateVolatileState(e,n){if(!Te(n))throw new _e("volatile state initializer should return a plain object containing state");Object.getOwnPropertyNames(n).forEach(i=>{if(i in this.properties)throw new _e(`'${i}' is a property and cannot be declared as volatile state`);it(e,i,"volatile state"),t.set(e,i,n[i])})}extend(e){return this.cloneAndEnhance({initializers:[t=>{const n=e(t),{actions:i,views:s,state:r}=n,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}(n,["actions","views","state"]);for(let e in o)throw new _e(`The \`extend\` function should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '${e}'`);return r&&this.instantiateVolatileState(t,r),s&&this.instantiateViews(t,s),i&&this.instantiateActions(t,i),t}]})}views(e){return this.cloneAndEnhance({initializers:[t=>(this.instantiateViews(t,e(t)),t)]})}instantiateViews(e,n){if(!Te(n))throw new _e("views initializer should return a plain object containing views");Object.getOwnPropertyNames(n).forEach(i=>{if(i in this.properties)throw new _e(`'${i}' is a property and cannot be declared as a view`);it(e,i,"a view");const s=Object.getOwnPropertyDescriptor(n,i);if("get"in s)t.defineProperty(e,i,s),t.makeObservable(e,{[i]:t.computed});else{if("function"!=typeof s.value)throw new _e("A view member should either be a function or getter based property");Ve(e,i,s.value)}})}instantiate(e,t,n,i){return re(this,e,t,n,ce(i)?i:this.applySnapshotPreProcessor(i))}initializeChildNodes(e,t={}){const n=e.type,i={};return n.forAllProps((n,s)=>{i[n]=s.instantiate(e,n,void 0,t[n])}),i}createNewInstance(e){const n=Object.assign(Object.assign({},we),{name:this.name});return t.observable.object(e,me,n)}finalizeNewInstance(e,n){Ve(n,"toString",rt),this.forAllProps(i=>{t._interceptReads(n,i,e.unbox)}),this.initializers.reduce((e,t)=>t(e),n),tt.delete(n),t.intercept(n,this.willChange),t.observe(n,this.didChange)}willChange(e){const t=e,n=he(t.object),i=t.name;n.assertWritable({subpath:i});const s=n.type.properties[i];return s&&(te(s,t.newValue),t.newValue=s.reconcile(n.getChildNode(i),t.newValue,n,i)),t}didChange(e){const t=e,n=he(t.object);if(!n.type.properties[t.name])return;const i=t.oldValue?t.oldValue.snapshot:void 0;n.emitPatch({op:"replace",path:Me(t.name),value:t.newValue.snapshot,oldValue:i},n)}getChildren(e){const t=[];return this.forAllProps(n=>{t.push(this.getChildNode(e,n))}),t}getChildNode(e,n){var i;if(!(n in this.properties))throw new _e("Not a value property: "+n);const s=t._getAdministration(e.storedValue,n),r=null===(i=s.raw)||void 0===i?void 0:i.call(s);if(!r)throw new _e("Node not available for property "+n);return r}getSnapshot(e,n=!0){const i={};return this.forAllProps((n,s)=>{var r,o;const a=t.getAtom(e.storedValue,n);a.reportObserved();const c=null===(o=(r=a).raw)||void 0===o?void 0:o.call(r);if(!c)throw new _e("Node not available for property "+n);i[n]=c.snapshot}),n?this.applySnapshotPostProcessor(i):i}processInitialSnapshot(e){const t={};return Object.keys(e).forEach(n=>{t[n]=e[n].getSnapshot()}),this.applySnapshotPostProcessor(t)}applyPatchLocally(e,t,n){if("replace"!==n.op&&"add"!==n.op)throw new _e("object does not support operation "+n.op);e.storedValue[t]=n.value}applySnapshot(e,t){const n=this.applySnapshotPreProcessor(t),i=!Te(n);(Te(t)&&!i||(te(this,t),!i))&&this.forAllProps((t,i)=>{const s=e.getChildNode(t),r=n[t];s.snapshot!==r&&(E(i,s,r)?s.applySnapshot(r):e.storedValue[t]=r)})}applySnapshotPreProcessor(e){const t=this.preProcessor;return t?t.call(null,e):e}applySnapshotPostProcessor(e){const t=this.postProcessor;return t?t.call(null,e):e}getChildType(e){return this.properties[e]}isValidSnapshot(e,t){let n=this.applySnapshotPreProcessor(e);return Te(n)?ee(this.propertyNames.map(e=>this.properties[e].validate(n[e],K(t,e,this.properties[e])))):X(t,n,"Value is not a plain object")}forAllProps(e){this.propertyNames.forEach(t=>e(t,this.properties[t]))}describe(){return"{ "+this.propertyNames.map(e=>e+": "+this.properties[e].describe()).join("; ")+" }"}getDefaultSnapshot(){return me}removeChild(e,t){e.storedValue[t]=void 0}}function ht(e){return N(e)&&(e.flags&I.Object)>0}ct.prototype.applySnapshot=t.action(ct.prototype.applySnapshot);class lt extends C{constructor(e,t,n,i=Se){super(e),this.flags=t,this.checker=n,this.initializer=i,this.flags=t}describe(){return this.name}instantiate(e,t,n,i){return oe(this,e,t,n,i)}createNewInstance(e){return this.initializer(e)}isValidSnapshot(e,t){if(Ee(e)&&this.checker(e))return Q();return X(t,e,"Value is not a "+("Date"===this.name?"Date or a unix milliseconds timestamp":this.name))}}const ut=new lt("string",I.String,e=>"string"==typeof e),pt=new lt("number",I.Number,e=>"number"==typeof e),dt=new lt("integer",I.Integer,e=>Ae(e)),ft=new lt("float",I.Float,e=>{return t=e,Number(t)===t&&t%1!=0;var t}),gt=new lt("finite",I.Finite,e=>{return t=e,Number.isFinite(t);var t}),yt=new lt("bigint",I.BigInt,e=>{if("bigint"==typeof e)return!0;if("string"==typeof e||"number"==typeof e)try{return BigInt(e),!0}catch(e){}return!1},e=>"bigint"==typeof e?e:BigInt(e));yt.getSnapshot=function(e){return String(e.storedValue)};const bt=yt,vt=new lt("boolean",I.Boolean,e=>"boolean"==typeof e),mt=new lt("null",I.Null,e=>null===e),wt=new lt("undefined",I.Undefined,e=>void 0===e),_t=new lt("Date",I.Date,e=>"number"==typeof e||e instanceof Date,e=>e instanceof Date?e:new Date(e));_t.getSnapshot=function(e){return e.storedValue.getTime()};const St=_t;function At(e){return N(e)&&(e.flags&(I.String|I.Number|I.Integer|I.Boolean|I.Date|I.BigInt))>0}class It extends C{constructor(e){super(JSON.stringify(e)),this.flags=I.Literal,this.value=e}instantiate(e,t,n,i){return oe(this,e,t,n,i)}describe(){return JSON.stringify(this.value)}isValidSnapshot(e,t){return Ee(e)&&e===this.value?Q():X(t,e,"Value is not a literal "+JSON.stringify(this.value))}}function Pt(e){return new It(e)}class Tt extends P{get flags(){return this._subtype.flags|I.Refinement}constructor(e,t,n,i){super(e),this._subtype=t,this._predicate=n,this._message=i}describe(){return this.name}instantiate(e,t,n,i){return this._subtype.instantiate(e,t,n,i)}isAssignableFrom(e){return this._subtype.isAssignableFrom(e)}isValidSnapshot(e,t){const n=this._subtype.validate(e,t);if(n.length>0)return n;const i=ce(e)?he(e).snapshot:e;return this._predicate(i)?Q():X(t,e,this._message(e))}reconcile(e,t,n,i){return this._subtype.reconcile(e,t,n,i)}getSubTypes(){return this._subtype}}class Ct extends P{get flags(){let e=I.Union;return this._types.forEach(t=>{e|=t.flags}),e}constructor(e,t,n){super(e),this._types=t,this._eager=!0,n=Object.assign({eager:!0,dispatcher:void 0},n),this._dispatcher=n.dispatcher,n.eager||(this._eager=!1)}isAssignableFrom(e){return this._types.some(t=>t.isAssignableFrom(e))}describe(){return"("+this._types.map(e=>e.describe()).join(" | ")+")"}instantiate(e,t,n,i){const s=this.determineType(i,void 0);if(!s)throw new _e("No matching type for union "+this.describe());return s.instantiate(e,t,n,i)}reconcile(e,t,n,i){const s=this.determineType(t,e.getReconciliationType());if(!s)throw new _e("No matching type for union "+this.describe());return s.reconcile(e,t,n,i)}determineType(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter(e=>e!==t).find(t=>t.is(e)):this._types.find(t=>t.is(e))}isValidSnapshot(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);const n=[];let i=0;for(let s=0;s<this._types.length;s++){const r=this._types[s].validate(e,t);if(0===r.length){if(this._eager)return Q();i++}else n.push(r)}return 1===i?Q():X(t,e,"No type is applicable for the union").concat(ee(n))}getSubTypes(){return this._types}}function Et(e,...t){const n=N(e)?void 0:e,i=N(e)?[e,...t]:t,s="("+i.map(e=>e.name).join(" | ")+")";return new Ct(s,i,n)}function Nt(e){return N(e)&&(e.flags&I.Union)>0}class Vt extends P{get flags(){return this._subtype.flags|I.Optional}constructor(e,t,n){super(e.name),this._subtype=e,this._defaultValue=t,this.optionalValues=n}describe(){return this._subtype.describe()+"?"}instantiate(e,t,n,i){if(this.optionalValues.indexOf(i)>=0){const i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,n,i)}return this._subtype.instantiate(e,t,n,i)}reconcile(e,t,n,i){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),n,i)}getDefaultInstanceOrSnapshot(){const e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&te(this,e),e}isValidSnapshot(e,t){return this.optionalValues.indexOf(e)>=0?Q():this._subtype.validate(e,t)}isAssignableFrom(e){return this._subtype.isAssignableFrom(e)}getSubTypes(){return this._subtype}}function Ot(e,t,n){return function(e,t){if("function"!=typeof t&&ce(t))throw new _e("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}(0,t),new Vt(e,t,n||Dt)}const Dt=[void 0];const xt=Ot(wt,void 0),$t=Ot(mt,null);function jt(e){return Et(e,xt)}class kt extends P{get flags(){return(this._subType?this._subType.flags:0)|I.Late}getSubType(e){if(!this._subType){let t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw new _e("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType}constructor(e,t){super(e),this._definition=t}instantiate(e,t,n,i){return this.getSubType(!0).instantiate(e,t,n,i)}reconcile(e,t,n,i){return this.getSubType(!0).reconcile(e,t,n,i)}describe(){const e=this.getSubType(!1);return e?e.name:"<uknown late type>"}isValidSnapshot(e,t){const n=this.getSubType(!1);return n?n.validate(e,t):Q()}isAssignableFrom(e){const t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)}getSubTypes(){const e=this.getSubType(!1);return e||"cannotDetermine"}}class Rt extends C{constructor(e,n){super(e),this.options=n,this.flags=I.Lazy,this.loadedType=null,this.pendingNodeList=t.observable.array(),t.when(()=>this.pendingNodeList.length>0&&this.pendingNodeList.some(e=>e.isAlive&&this.options.shouldLoadPredicate(e.parent?e.parent.value:null)),()=>{this.options.loadType().then(t.action(e=>{this.loadedType=e,this.pendingNodeList.forEach(e=>{e.parent&&this.loadedType&&e.parent.applyPatches([{op:"replace",path:"/"+e.subpath,value:e.snapshot}])})}))})}describe(){return`<lazy ${this.name}>`}instantiate(e,n,i,s){if(this.loadedType)return this.loadedType.instantiate(e,n,i,s);const r=oe(this,e,n,i,s);return this.pendingNodeList.push(r),t.when(()=>!r.isAlive,()=>this.pendingNodeList.splice(this.pendingNodeList.indexOf(r),1)),r}isValidSnapshot(e,t){return this.loadedType?this.loadedType.validate(e,t):Ne(e)?Q():X(t,e,"Value is not serializable and cannot be lazy")}reconcile(e,t,n,i){return this.loadedType?(e.die(),this.loadedType.instantiate(n,i,n.environment,t)):super.reconcile(e,t,n,i)}}class zt extends C{constructor(e){super(e?`frozen(${e.name})`:"frozen"),this.subType=e,this.flags=I.Frozen}describe(){return"<any immutable value>"}instantiate(e,t,n,i){return oe(this,e,t,n,i)}isValidSnapshot(e,t){return Ne(e)?this.subType?this.subType.validate(e,t):Q():X(t,e,"Value is not serializable and cannot be frozen")}}const Ft=new zt;class Mt{constructor(e,t){if(this.targetType=t,this.resolvedReference=void 0,Kt(e))this.identifier=e;else{if(!ce(e))throw new _e(`Can only store references to tree nodes or identifiers, got: '${e}'`);{const t=he(e);if(!t.identifierAttribute)throw new _e("Can only store references with a defined identifier attribute.");const n=t.unnormalizedIdentifier;if(null==n)throw new _e("Can only store references to tree nodes with a defined identifier.");this.identifier=n}}}updateResolvedReference(e){const t=qt(this.identifier),n=e.root,i=n.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==i){const{targetType:s}=this,r=n.identifierCache.resolve(s,t);if(!r)throw new Lt(`[mobx-state-tree] Failed to resolve reference '${this.identifier}' to type '${this.targetType.name}' (from node: ${e.path})`);this.resolvedReference={node:r,lastCacheModification:i}}}get resolvedValue(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value}}class Lt extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Lt.prototype)}}class Ht extends C{constructor(e,t){super(`reference(${e.name})`),this.targetType=e,this.onInvalidated=t,this.flags=I.Reference}describe(){return this.name}isAssignableFrom(e){return this.targetType.isAssignableFrom(e)}isValidSnapshot(e,t){return Kt(e)?Q():X(t,e,"Value is not a valid identifier, which is a string, number or a bigint")}fireInvalidated(e,t,n,i){const s=t.parent;if(!s||!s.isAlive)return;const r=s.storedValue;r&&this.onInvalidated({cause:e,parent:r,invalidTarget:i?i.storedValue:void 0,invalidId:n,replaceRef(e){c(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef(){ht(s.type)?this.replaceRef(void 0):c(t.root.storedValue,{op:"remove",path:t.path})}})}addTargetNodeWatcher(e,t){const n=this.getValue(e);if(!n)return;const i=he(n),s=(n,s)=>{const o=function(e){switch(e){case r.beforeDestroy:return"destroy";case r.beforeDetach:return"detach";default:return}}(s);o&&this.fireInvalidated(o,e,t,i)},o=i.registerHook(r.beforeDetach,s),a=i.registerHook(r.beforeDestroy,s);return()=>{o(),a()}}watchTargetNodeForInvalidations(e,t,n){if(!this.onInvalidated)return;let i;e.registerHook(r.beforeDestroy,()=>{i&&i()});const s=()=>{const n=()=>{e.isAlive&&this.getSnapshot(e)===t&&o(!1)};R()?e.root.enqueueEndOfAction(n):ke(n)},o=r=>{i&&i();const o=e.parent,a=o&&o.storedValue;if(o&&o.isAlive&&a){let o;o=n?!!n.get(t,a):e.root.identifierCache.has(this.targetType,qt(t)),o?i=this.addTargetNodeWatcher(e,t):r?s():this.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===ae.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(r.afterCreationFinalization,()=>{e.parent&&e.parent.createObservableInstanceIfNeeded()}),e.registerHook(r.afterAttach,()=>{o(!1)}))}}class Ut extends Ht{constructor(e,t){super(e,t)}getValue(e){if(!e.isAlive)return;return e.storedValue.resolvedValue}getSnapshot(e){return e.storedValue.identifier}instantiate(e,t,n,i){const s=ce(i)?d(i):i,r=new Mt(i,this.targetType),o=oe(this,e,t,n,r);return r.node=o,this.watchTargetNodeForInvalidations(o,s,void 0),o}reconcile(e,t,n,i){if(!e.isDetaching&&e.type===this){const s=ce(t),r=e.storedValue;if(!s&&r.identifier===t||s&&r.resolvedValue===t)return e.setParent(n,i),e}const s=this.instantiate(n,i,void 0,t);return e.die(),s}}class Bt extends Ht{constructor(e,t,n){super(e,n),this.options=t}getValue(e){if(!e.isAlive)return;return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)}getSnapshot(e){return e.storedValue}instantiate(e,t,n,i){const s=ce(i)?this.options.set(i,e?e.storedValue:null):i,r=oe(this,e,t,n,s);return this.watchTargetNodeForInvalidations(r,s,this.options),r}reconcile(e,t,n,i){const s=ce(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===s)return e.setParent(n,i),e;const r=this.instantiate(n,i,void 0,s);return e.die(),r}}function Gt(e,t){const n=t||void 0,i=t?t.onInvalidated:void 0;return n&&(n.get||n.set)?new Bt(e,{get:n.get,set:n.set},i):new Ut(e,i)}class Wt extends C{constructor(e,t){super(e),this.validType=t,this.flags=I.Identifier}instantiate(e,t,n,i){if(!(e&&e.type instanceof ct))throw new _e("Identifier types can only be instantiated as direct child of a model type");return oe(this,e,t,n,i)}reconcile(e,t,n,i){if(e.storedValue!==t)throw new _e(`Tried to change identifier from '${e.storedValue}' to '${t}'. Changing identifiers is not allowed.`);return e.setParent(n,i),e}isValidSnapshot(e,t){return typeof e!==this.validType?X(t,e,`Value is not a valid ${this.describe()}, expected a ${this.validType}`):Q()}}const Zt=new class extends Wt{constructor(){super("identifier","string"),this.flags=I.Identifier}describe(){return"identifier"}},Yt=new class extends Wt{constructor(){super("identifierNumber","number")}getSnapshot(e){return e.storedValue}describe(){return"identifierNumber"}};const Jt=new class extends C{constructor(){super("identifierBigint"),this.flags=I.Identifier}createNewInstance(e){return"bigint"==typeof e?e:BigInt(e)}instantiate(e,t,n,i){if(!(e&&e.type instanceof ct))throw new _e("Identifier types can only be instantiated as direct child of a model type");return oe(this,e,t,n,i)}reconcile(e,t,n,i){const s=e.storedValue,r="bigint"==typeof t?t:BigInt(t);if(s!==r)throw new _e(`Tried to change identifier from '${s}' to '${r}'. Changing identifiers is not allowed.`);return e.setParent(n,i),e}isValidSnapshot(e,t){if("bigint"==typeof e)return Q();if("string"==typeof e||"number"==typeof e)try{return BigInt(e),Q()}catch(n){const i=n instanceof Error?n.message:String(n);return X(t,e,`Value is not a valid ${this.describe()}: ${i}`)}return X(t,e,`Value is not a valid ${this.describe()}, expected a bigint, a string or a number`)}getSnapshot(e){return String(e.storedValue)}describe(){return"identifierBigint"}};function qt(e){return""+e}function Kt(e){return"string"==typeof e||"number"==typeof e||"bigint"==typeof e}class Qt extends C{constructor(e){super(e.name),this.options=e,this.flags=I.Custom}describe(){return this.name}isValidSnapshot(e,t){if(this.options.isTargetType(e))return Q();const n=this.options.getValidationMessage(e);return n?X(t,e,`Invalid value for type '${this.name}': ${n}`):Q()}getSnapshot(e){return this.options.toSnapshot(e.storedValue)}instantiate(e,t,n,i){return oe(this,e,t,n,this.options.isTargetType(i)?i:this.options.fromSnapshot(i,e&&e.root.environment))}reconcile(e,t,n,i){const s=!this.options.isTargetType(t);if(!e.isDetaching){if(e.type===this&&(s?t===e.snapshot:t===e.storedValue))return e.setParent(n,i),e}const r=s?this.options.fromSnapshot(t,n.root.environment):t,o=this.instantiate(n,i,void 0,r);return e.die(),o}}const Xt={enumeration:function(e,t){const n=Et(...("string"==typeof e?t:e).map(e=>Pt(e)));return"string"==typeof e&&(n.name=e),n},model:function(...e){const t="string"==typeof e[0]?e.shift():"AnonymousModel",n=e.shift()||{};return new ct({name:t,properties:n})},compose:function(...e){const t="string"==typeof e[0],n=t?e[0]:"AnonymousModel";return t&&e.shift(),e.reduce((e,t)=>e.cloneAndEnhance({name:e.name+"_"+t.name,properties:t.properties,initializers:[st,...t.initializers],preProcessor:n=>t.applySnapshotPreProcessor(e.applySnapshotPreProcessor(n)),postProcessor:n=>t.applySnapshotPostProcessor(e.applySnapshotPostProcessor(n))})).named(n)},custom:function(e){return new Qt(e)},reference:Gt,safeReference:function(e,t){const n=Gt(e,Object.assign(Object.assign({},t),{onInvalidated(e){t&&t.onInvalidated&&t.onInvalidated(e),e.removeRef()}}));return t&&!1===t.acceptsUndefined?n:jt(n)},union:Et,optional:Ot,literal:Pt,maybe:jt,maybeNull:function(e){return Et(e,$t)},refinement:function(...e){const t="string"==typeof e[0]?e.shift():N(e[0])?e[0].name:null,n=e[0],i=e[1],s=e[2]?e[2]:e=>"Value does not respect the refinement predicate";return new Tt(t,n,i,s)},string:ut,boolean:vt,number:pt,integer:dt,float:ft,finite:gt,bigint:bt,Date:St,map:function(e){return new Je(`Map<string, ${e.name}>`,e)},array:function(e){return new qe(e.name+"[]",e)},frozen:function(e){return 0===arguments.length?Ft:N(e)?new zt(e):Ot(Ft,e)},identifier:Zt,identifierNumber:Yt,identifierBigint:Jt,late:function(e,t){const n="string"==typeof e?e:`late(${e.toString()})`;return new kt(n,"string"==typeof e?t:e)},lazy:function(e,t){return new Rt(e,t)},undefined:wt,null:mt,snapshotProcessor:function(e,t,n){return new Ge(e,t,n)}};e.addDisposer=function(e,t){return he(e).addDisposer(t),t},e.addMiddleware=H,e.applyAction=x,e.applyPatch=c,e.applySnapshot=h,e.cast=function(e){return e},e.castFlowReturn=function(e){return e},e.castToReferenceSnapshot=function(e){return e},e.castToSnapshot=function(e){return e},e.clone=function(e,t=!0){const n=he(e);return n.type.create(n.snapshot,!0===t?n.root.environment:!1===t?void 0:t)},e.createActionTrackingMiddleware=function(e){return function(t,n,i){switch(t.type){case"action":if(e.filter&&!0!==e.filter(t))return n(t);{const i=e.onStart(t);e.onResume(t,i),V.set(t.id,{call:t,context:i,async:!1});try{const s=n(t);return e.onSuspend(t,i),!1===V.get(t.id).async&&(V.delete(t.id),e.onSuccess(t,i,s)),s}catch(n){throw V.delete(t.id),e.onFail(t,i,n),n}}case"flow_spawn":return V.get(t.rootId).async=!0,n(t);case"flow_resume":case"flow_resume_error":{const i=V.get(t.rootId);e.onResume(t,i.context);try{return n(t)}finally{e.onSuspend(t,i.context)}}case"flow_throw":{const i=V.get(t.rootId);return V.delete(t.rootId),e.onFail(t,i.context,t.args[0]),n(t)}case"flow_return":{const i=V.get(t.rootId);return V.delete(t.rootId),e.onSuccess(t,i.context,t.args[0]),n(t)}}}},e.createActionTrackingMiddleware2=function(e){const t=new Map;return function(n,i){const s=n.parentActionEvent?t.get(n.parentActionEvent.id):void 0;if("action"===n.type){const r=Object.assign(Object.assign({},n),{env:s&&s.call.env,parentCall:s&&s.call}),o=!e.filter||e.filter(r),a=new O(o?e:void 0,r);let c;t.set(n.id,a);try{c=i(n)}catch(e){throw t.delete(n.id),a.finish(e),e}return a.hasFlowsPending||(t.delete(n.id),a.finish()),c}if(!s)return i(n);switch(n.type){case"flow_spawn":return s.incFlowsPending(),i(n);case"flow_resume":case"flow_resume_error":return i(n);case"flow_throw":{const e=n.args[0];try{return i(n)}finally{s.decFlowsPending(),s.hasFlowsPending||(t.delete(n.parentActionEvent.id),s.finish(e))}}case"flow_return":try{return i(n)}finally{s.decFlowsPending(),s.hasFlowsPending||(t.delete(n.parentActionEvent.id),s.finish())}}}},e.decorate=function(e,t,n=!0){const i={handler:e,includeHooks:n};return t.$mst_middleware=t.$mst_middleware||[],t.$mst_middleware.push(i),t},e.destroy=function(e){const t=he(e);t.isRoot?t.die():t.parent.removeChild(t.subpath)},e.detach=function(e){return he(e).detach(),e},e.escapeJsonPath=Me,e.flow=Re,e.getChildType=function(e,t){return he(e).getChildType(t)},e.getEnv=function(e){const t=he(e),n=t.root.environment;if(!n)throw new _e(`Failed to find the environment of ${t} ${t.path}`);return n},e.getErrorFormatting=Z,e.getIdentifier=d,e.getLivelinessChecking=s,e.getMemberRedeclarationChecking=function(){return nt},e.getMembers=function(e){const n=he(e).type,i=Object.assign(Object.assign({},y(n)),{actions:[],volatile:[],views:[],flowActions:[]});return Object.getOwnPropertyNames(e).forEach(n=>{if(n in i.properties)return;const s=Object.getOwnPropertyDescriptor(e,n);s.get?t.isComputedProp(e,n)?i.views.push(n):i.volatile.push(n):(!0===s.value._isFlowAction&&i.flowActions.push(n),!0===s.value._isMSTAction?i.actions.push(n):t.isObservableProp(e,n)?i.volatile.push(n):i.views.push(n))}),i},e.getNodeId=function(e){return he(e).nodeId},e.getParent=function(e,t=1){let n=t,i=he(e).parent;for(;i;){if(0==--n)return i.storedValue;i=i.parent}throw new _e(`Failed to find the parent of ${he(e)} at depth ${t}`)},e.getParentOfType=function(e,t){let n=he(e).parent;for(;n;){if(t.is(n.storedValue))return n.storedValue;n=n.parent}throw new _e(`Failed to find the parent of ${he(e)} of a given type`)},e.getPath=p,e.getPathParts=function(e){return Ue(he(e).path)},e.getPropertyMembers=y,e.getRelativePath=function(e,t){return de(he(e),he(t))},e.getRoot=u,e.getRunningActionContext=B,e.getSnapshot=l,e.getType=o,e.hasEnv=function(e){return!!he(e).root.environment},e.hasParent=function(e,t=1){let n=he(e).parent;for(;n;){if(0==--t)return!0;n=n.parent}return!1},e.hasParentOfType=function(e,t){let n=he(e).parent;for(;n;){if(t.is(n.storedValue))return!0;n=n.parent}return!1},e.isActionContextChildOf=function(e,t){return G(e,t,!1)},e.isActionContextThisOrChildOf=function(e,t){return G(e,t,!0)},e.isAlive=g,e.isArrayType=function(e){return N(e)&&(e.flags&I.Array)>0},e.isFrozenType=function(e){return N(e)&&(e.flags&I.Frozen)>0},e.isIdentifierType=function(e){return N(e)&&(e.flags&I.Identifier)>0},e.isLateType=function(e){return N(e)&&(e.flags&I.Late)>0},e.isLiteralType=function(e){return N(e)&&(e.flags&I.Literal)>0},e.isMapType=function(e){return N(e)&&(e.flags&I.Map)>0},e.isModelType=ht,e.isOptionalType=function(e){return N(e)&&(e.flags&I.Optional)>0},e.isPrimitiveType=At,e.isProtected=function(e){return he(e).isProtected},e.isReferenceType=function(e){return N(e)&&(e.flags&I.Reference)>0},e.isRefinementType=function(e){return N(e)&&(e.flags&I.Refinement)>0},e.isRoot=function(e){return he(e).isRoot},e.isStateTreeNode=ce,e.isType=N,e.isUnionType=Nt,e.isValidReference=function(e,t=!0){try{const n=e();if(null==n)return!1;if(ce(n))return!t||g(n);throw new _e("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof Lt)return!1;throw e}},e.joinJsonPath=He,e.onAction=$,e.onPatch=a,e.onSnapshot=function(e,t){return he(e).onSnapshot(t)},e.process=function(e){return je(),Re(e)},e.protect=function(e){const t=he(e);if(!t.isRoot)throw new _e("`protect` can only be invoked on root nodes");t.isProtectionEnabled=!0},e.recordActions=function(e,t){const n=[],i=e=>{(!t||t(e,B()))&&n.push(e)};let s;const r={actions:n,get recording(){return!!s},stop(){s&&(s(),s=void 0)},resume(){s||(s=$(e,i))},replay(e){x(e,n)}};return r.resume(),r},e.recordPatches=function(e,t){const n={patches:[],inversePatches:[]},i={};let s;const r={get recording(){return!!s},get patches(){return i.patches||(i.patches=n.patches.slice()),i.patches},get reversedInversePatches(){return i.reversedInversePatches||(i.reversedInversePatches=n.inversePatches.slice().reverse()),i.reversedInversePatches},get inversePatches(){return i.inversePatches||(i.inversePatches=n.inversePatches.slice()),i.inversePatches},stop(){s&&(s(),s=void 0)},resume(){s||(s=a(e,(e,s)=>{t&&!t(e,s,B())||(n.patches.push(e),n.inversePatches.push(s),i.patches=void 0,i.inversePatches=void 0,i.reversedInversePatches=void 0)}))},replay(t){c(t||e,n.patches)},undo(t){c(t||e,n.inversePatches.slice().reverse())}};return r.resume(),r},e.resolveIdentifier=function(e,t,n){const i=he(t).root.identifierCache.resolve(e,qt(n));return null==i?void 0:i.value},e.resolvePath=function(e,t){const n=fe(he(e),t);return n?n.value:void 0},e.setErrorFormatting=function(e){W=Object.assign(Object.assign({},W),e)},e.setLivelinessChecking=i,e.setLivelynessChecking=function(e){i(e)},e.setMemberRedeclarationChecking=function(e){nt=e},e.splitJsonPath=Ue,e.t=Xt,e.toGenerator=function*(e){return yield e},e.toGeneratorFunction=function(e){return function*(...t){return yield e(...t)}},e.tryReference=function(e,t=!0){try{const n=e();if(null==n)return;if(ce(n))return t?g(n)?n:void 0:n;throw new _e("The reference to be checked is not one of node, null or undefined")}catch(e){if(e instanceof Lt)return;throw e}},e.tryResolve=f,e.typecheck=ne,e.types=Xt,e.unescapeJsonPath=Le,e.unprotect=function(e){const t=he(e);if(!t.isRoot)throw new _e("`unprotect` can only be invoked on root nodes");t.isProtectionEnabled=!1},e.walk=function e(t,n){const i=he(t);i.getChildren().forEach(t=>{const i=t instanceof A?t.value:t.storedValue;ce(i)&&e(i,n)}),n(i.storedValue)},Object.defineProperty(e,"__esModule",{value:!0})}));