diff --git a/dist/JSpider.cjs.min.js b/dist/JSpider.cjs.min.js index 235946d..756372b 100644 --- a/dist/JSpider.cjs.min.js +++ b/dist/JSpider.cjs.min.js @@ -202,7 +202,7 @@ * limitations under the License. */ -"use strict";function e(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;ne.length)&&(t=e.length);for(var r=0,n=new Array(t);r=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=e[Symbol.iterator]()).next.bind(r)}var R=Symbol("mobx-stored-annotations");function U(e){return Object.assign((function(t,r){M(t,r,e)}),e)}function M(e,t,r){x(e,R)||m(e,R,C({},e[R])),function(e){return"override"===e.annotationType_}(r)||(e[R][t]=r)}var F=Symbol("mobx administration"),z=function(){function e(e){void 0===e&&(e="Atom"),this.name_=void 0,this.isPendingUnobservation_=!1,this.isBeingObserved_=!1,this.observers_=new Set,this.diffValue_=0,this.lastAccessedBy_=0,this.lowestObserverState_=Ue.NOT_TRACKING_,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return at(this)},t.reportChanged=function(){it(),st(this),ot()},t.toString=function(){return this.name_},e}(),L=w("Atom",z);function $(e,t,r){void 0===t&&(t=h),void 0===r&&(r=h);var n,i=new z(e);return t!==h&&St("onBO",i,t,n),r!==h&&Pt(i,r),i}var H={identity:function(e,t){return e===t},structural:function(e,t){return Fr(e,t)},default:function(e,t){return Object.is(e,t)},shallow:function(e,t){return Fr(e,t,1)}};function B(e,t,r){return Vt(e)?e:Array.isArray(e)?we.array(e,{name:r}):y(e)?we.object(e,void 0,{name:r}):O(e)?we.map(e,{name:r}):j(e)?we.set(e,{name:r}):"function"!=typeof e||_t(e)||kt(e)?e:g(e)?It(e):gt(r,e)}function G(e){return e}function K(e,t){return{annotationType_:e,options_:t,make_:q,extend_:W}}function q(e,t,r,n){var i;if(null==(i=this.options_)?void 0:i.bound)return null===this.extend_(e,t,r,!1)?0:1;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if(_t(r.value))return 1;var a=Y(e,this,t,r,!1);return o(n,t,a),2}function W(e,t,r,n){var i=Y(e,this,t,r);return e.defineProperty_(t,i,n)}function Y(e,t,r,n,i){var o,a,s,u,c,l;void 0===i&&(i=et.safeDescriptors),l=n,t.annotationType_,l.value;var f,p=n.value;(null==(o=t.options_)?void 0:o.bound)&&(p=p.bind(null!=(f=e.proxy_)?f:e.target_));return{value:Ie(null!=(a=null==(s=t.options_)?void 0:s.name)?a:r.toString(),p,null!=(u=null==(c=t.options_)?void 0:c.autoAction)&&u),configurable:!i||e.isPlainObject_,enumerable:!1,writable:!i}}function Q(e,t){return{annotationType_:e,options_:t,make_:X,extend_:Z}}function X(e,t,r,n){var i;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if((null==(i=this.options_)?void 0:i.bound)&&!kt(e.target_[t])&&null===this.extend_(e,t,r,!1))return 0;if(kt(r.value))return 1;var a=J(e,this,t,r,!1,!1);return o(n,t,a),2}function Z(e,t,r,n){var i,o=J(e,this,t,r,null==(i=this.options_)?void 0:i.bound);return e.defineProperty_(t,o,n)}function J(e,t,r,n,i,o){var a;void 0===o&&(o=et.safeDescriptors),a=n,t.annotationType_,a.value;var s,u=n.value;i&&(u=u.bind(null!=(s=e.proxy_)?s:e.target_));return{value:It(u),configurable:!o||e.isPlainObject_,enumerable:!1,writable:!o}}function ee(e,t){return{annotationType_:e,options_:t,make_:te,extend_:re}}function te(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function re(e,t,r,n){var i;return i=r,this.annotationType_,i.get,e.defineComputedProperty_(t,C({},this.options_,{get:r.get,set:r.set}),n)}function ne(e,t){return{annotationType_:e,options_:t,make_:ie,extend_:oe}}function ie(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function oe(e,t,r,n){var i,o;return this.annotationType_,e.defineObservableProperty_(t,r.value,null!=(i=null==(o=this.options_)?void 0:o.enhancer)?i:B,n)}var ae=se();function se(e){return{annotationType_:"true",options_:e,make_:ue,extend_:ce}}function ue(e,t,r,n){var i,a,s,u;if(r.get)return Pe.make_(e,t,r,n);if(r.set){var c=Ie(t.toString(),r.set);return n===e.target_?null===e.defineProperty_(t,{configurable:!et.safeDescriptors||e.isPlainObject_,set:c})?0:2:(o(n,t,{configurable:!0,set:c}),2)}if(n!==e.target_&&"function"==typeof r.value)return g(r.value)?((null==(u=this.options_)?void 0:u.autoBind)?It.bound:It).make_(e,t,r,n):((null==(s=this.options_)?void 0:s.autoBind)?gt.bound:gt).make_(e,t,r,n);var l,f=!1===(null==(i=this.options_)?void 0:i.deep)?we.ref:we;"function"==typeof r.value&&(null==(a=this.options_)?void 0:a.autoBind)&&(r.value=r.value.bind(null!=(l=e.proxy_)?l:e.target_));return f.make_(e,t,r,n)}function ce(e,t,r,n){var i,o,a;if(r.get)return Pe.extend_(e,t,r,n);if(r.set)return e.defineProperty_(t,{configurable:!et.safeDescriptors||e.isPlainObject_,set:Ie(t.toString(),r.set)},n);"function"==typeof r.value&&(null==(i=this.options_)?void 0:i.autoBind)&&(r.value=r.value.bind(null!=(a=e.proxy_)?a:e.target_));return(!1===(null==(o=this.options_)?void 0:o.deep)?we.ref:we).extend_(e,t,r,n)}var le={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function fe(e){return e||le}Object.freeze(le);var pe=ne("observable"),he=ne("observable.ref",{enhancer:G}),be=ne("observable.shallow",{enhancer:function(e,t,r){return null==e||Sr(e)||lr(e)||vr(e)||mr(e)?e:Array.isArray(e)?we.array(e,{name:r,deep:!1}):y(e)?we.object(e,void 0,{name:r,deep:!1}):O(e)?we.map(e,{name:r,deep:!1}):j(e)?we.set(e,{name:r,deep:!1}):void 0}}),de=ne("observable.struct",{enhancer:function(e,t){return Fr(e,t)?t:e}}),ve=U(pe);function ye(e){return!0===e.deep?B:!1===e.deep?G:(t=e.defaultDecorator)&&null!=(r=null==(n=t.options_)?void 0:n.enhancer)?r:B;var t,r,n}function ge(e,t,r){if(!d(t))return Vt(e)?e:y(e)?we.object(e,t,r):Array.isArray(e)?we.array(e,t):O(e)?we.map(e,t):j(e)?we.set(e,t):"object"==typeof e&&null!==e?e:we.box(e,t);M(e,t,pe)}Object.assign(ge,ve);var me,_e,we=n(ge,{box:function(e,t){var r=fe(t);return new Ve(e,ye(r),r.name,!0,r.equals)},array:function(e,t){var r=fe(t);return(!1===et.useProxies||!1===r.proxy?Nr:tr)(e,ye(r),r.name)},map:function(e,t){var r=fe(t);return new dr(e,ye(r),r.name)},set:function(e,t){var r=fe(t);return new gr(e,ye(r),r.name)},object:function(e,t,r){return function(e,t,r,n){var i=E(t),o=Or(e,n)[F];it();try{S(i).forEach((function(e){o.extend_(e,i[e],!r||(!(e in r)||r[e]))}))}finally{ot()}return e}(!1===et.useProxies||!1===(null==r?void 0:r.proxy)?Or({},r):function(e,t){var r,n;return f(),e=Or(e,t),null!=(n=(r=e[F]).proxy_)?n:r.proxy_=new Proxy(e,Bt)}({},r),e,t)},ref:U(he),shallow:U(be),deep:ve,struct:U(de)}),Oe=ee("computed"),je=ee("computed.struct",{equals:H.structural}),Pe=function(e,t){if(d(t))return M(e,t,Oe);if(y(e))return U(ee("computed",e));var r=y(t)?t:{};return r.get=e,r.name||(r.name=e.name||""),new Fe(r)};Object.assign(Pe,Oe),Pe.struct=U(je);var Se,Ae=0,xe=1,Ee=null!=(me=null==(_e=i((function(){}),"name"))?void 0:_e.configurable)&&me,Te={value:"action",configurable:!0,writable:!1,enumerable:!1};function Ie(e,t,r,n){function i(){return Ce(e,r,t,n||this,arguments)}return void 0===r&&(r=!1),i.isMobxAction=!0,Ee&&(Te.value=e,Object.defineProperty(i,"name",Te)),i}function Ce(t,r,n,i,o){var a=function(e,t,r,n){var i=!1,o=0,a=et.trackingDerivation,s=!t||!a;it();var u=et.allowStateChanges;s&&(qe(),u=ke(!0));var c=Ye(!0),l={runAsAction_:s,prevDerivation_:a,prevAllowStateChanges_:u,prevAllowStateReads_:c,notifySpy_:i,startTime_:o,actionId_:xe++,parentActionId_:Ae};return Ae=l.actionId_,l}(0,r);try{return n.apply(i,o)}catch(e){throw a.error_=e,e}finally{!function(t){Ae!==t.actionId_&&e(30);Ae=t.parentActionId_,void 0!==t.error_&&(et.suppressReactionErrors=!0);De(t.prevAllowStateChanges_),Qe(t.prevAllowStateReads_),ot(),t.runAsAction_&&We(t.prevDerivation_);et.suppressReactionErrors=!1}(a)}}function ke(e){var t=et.allowStateChanges;return et.allowStateChanges=e,t}function De(e){et.allowStateChanges=e}Se=Symbol.toPrimitive;var Ne,Ve=function(e){function t(t,r,n,i,o){var a;return void 0===n&&(n="ObservableValue"),void 0===o&&(o=H.default),(a=e.call(this,n)||this).enhancer=void 0,a.name_=void 0,a.equals=void 0,a.hasUnreportedChange_=!1,a.interceptors_=void 0,a.changeListeners_=void 0,a.value_=void 0,a.dehancer=void 0,a.enhancer=r,a.name_=n,a.equals=o,a.value_=r(t,void 0,n),a}k(t,e);var r=t.prototype;return r.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.set=function(e){this.value_,(e=this.prepareNewValue_(e))!==et.UNCHANGED&&this.setNewValue_(e)},r.prepareNewValue_=function(e){if(Gt(this)){var t=qt(this,{object:this,type:Zt,newValue:e});if(!t)return et.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value_,this.name_),this.equals(this.value_,e)?et.UNCHANGED:e},r.setNewValue_=function(e){var t=this.value_;this.value_=e,this.reportChanged(),Wt(this)&&Qt(this,{type:Zt,object:this,newValue:e,oldValue:t})},r.get=function(){return this.reportObserved(),this.dehanceValue(this.value_)},r.intercept_=function(e){return Kt(this,e)},r.observe_=function(e,t){return t&&e({observableKind:"value",debugObjectName:this.name_,object:this,type:Zt,newValue:this.value_,oldValue:void 0}),Yt(this,e)},r.raw=function(){return this.value_},r.toJSON=function(){return this.get()},r.toString=function(){return this.name_+"["+this.value_+"]"},r.valueOf=function(){return A(this.get())},r[Se]=function(){return this.valueOf()},t}(z),Re=w("ObservableValue",Ve);Ne=Symbol.toPrimitive;var Ue,Me,Fe=function(){function t(t){this.dependenciesState_=Ue.NOT_TRACKING_,this.observing_=[],this.newObserving_=null,this.isBeingObserved_=!1,this.isPendingUnobservation_=!1,this.observers_=new Set,this.diffValue_=0,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=Ue.UP_TO_DATE_,this.unboundDepsCount_=0,this.value_=new Le(null),this.name_=void 0,this.triggeredBy_=void 0,this.isComputing_=!1,this.isRunningSetter_=!1,this.derivation=void 0,this.setter_=void 0,this.isTracing_=Me.NONE,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,t.get||e(31),this.derivation=t.get,this.name_=t.name||"ComputedValue",t.set&&(this.setter_=Ie("ComputedValue-setter",t.set)),this.equals_=t.equals||(t.compareStructural||t.struct?H.structural:H.default),this.scope_=t.context,this.requiresReaction_=!!t.requiresReaction,this.keepAlive_=!!t.keepAlive}var r=t.prototype;return r.onBecomeStale_=function(){!function(e){if(e.lowestObserverState_!==Ue.UP_TO_DATE_)return;e.lowestObserverState_=Ue.POSSIBLY_STALE_,e.observers_.forEach((function(e){e.dependenciesState_===Ue.UP_TO_DATE_&&(e.dependenciesState_=Ue.POSSIBLY_STALE_,e.onBecomeStale_())}))}(this)},r.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},r.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},r.get=function(){if(this.isComputing_&&e(32,this.name_,this.derivation),0!==et.inBatch||0!==this.observers_.size||this.keepAlive_){if(at(this),He(this)){var t=et.trackingContext;this.keepAlive_&&!t&&(et.trackingContext=this),this.trackAndCompute()&&function(e){if(e.lowestObserverState_===Ue.STALE_)return;e.lowestObserverState_=Ue.STALE_,e.observers_.forEach((function(t){t.dependenciesState_===Ue.POSSIBLY_STALE_?t.dependenciesState_=Ue.STALE_:t.dependenciesState_===Ue.UP_TO_DATE_&&(e.lowestObserverState_=Ue.UP_TO_DATE_)}))}(this),et.trackingContext=t}}else He(this)&&(this.warnAboutUntrackedRead_(),it(),this.value_=this.computeValue_(!1),ot());var r=this.value_;if($e(r))throw r.cause;return r},r.set=function(t){if(this.setter_){this.isRunningSetter_&&e(33,this.name_),this.isRunningSetter_=!0;try{this.setter_.call(this.scope_,t)}finally{this.isRunningSetter_=!1}}else e(34,this.name_)},r.trackAndCompute=function(){var e=this.value_,t=this.dependenciesState_===Ue.NOT_TRACKING_,r=this.computeValue_(!0),n=t||$e(e)||$e(r)||!this.equals_(e,r);return n&&(this.value_=r),n},r.computeValue_=function(e){this.isComputing_=!0;var t,r=ke(!1);if(e)t=Be(this,this.derivation,this.scope_);else if(!0===et.disableErrorBoundaries)t=this.derivation.call(this.scope_);else try{t=this.derivation.call(this.scope_)}catch(e){t=new Le(e)}return De(r),this.isComputing_=!1,t},r.suspend_=function(){this.keepAlive_||(Ge(this),this.value_=void 0)},r.observe_=function(e,t){var r=this,n=!0,i=void 0;return function(e,t){var r,n;void 0===t&&(t=u);var i,o=null!=(r=null==(n=t)?void 0:n.name)?r:"Autorun";if(t.scheduler||t.delay){var a=Ot(t),s=!1;i=new ut(o,(function(){s||(s=!0,a((function(){s=!1,i.isDisposed_||i.track(c)})))}),t.onError,t.requiresObservable)}else i=new ut(o,(function(){this.track(c)}),t.onError,t.requiresObservable);function c(){e(i)}return i.schedule_(),i.getDisposer_()}((function(){var o=r.get();if(!n||t){var a=qe();e({observableKind:"computed",debugObjectName:r.name_,type:Zt,object:r,newValue:o,oldValue:i}),We(a)}n=!1,i=o}))},r.warnAboutUntrackedRead_=function(){},r.toString=function(){return this.name_+"["+this.derivation.toString()+"]"},r.valueOf=function(){return A(this.get())},r[Ne]=function(){return this.valueOf()},t}(),ze=w("ComputedValue",Fe);!function(e){e[e.NOT_TRACKING_=-1]="NOT_TRACKING_",e[e.UP_TO_DATE_=0]="UP_TO_DATE_",e[e.POSSIBLY_STALE_=1]="POSSIBLY_STALE_",e[e.STALE_=2]="STALE_"}(Ue||(Ue={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(Me||(Me={}));var Le=function(e){this.cause=void 0,this.cause=e};function $e(e){return e instanceof Le}function He(e){switch(e.dependenciesState_){case Ue.UP_TO_DATE_:return!1;case Ue.NOT_TRACKING_:case Ue.STALE_:return!0;case Ue.POSSIBLY_STALE_:for(var t=Ye(!0),r=qe(),n=e.observing_,i=n.length,o=0;on&&(n=s.dependenciesState_)}r.length=i,e.newObserving_=null,o=t.length;for(;o--;){var u=t[o];0===u.diffValue_&&rt(u,e),u.diffValue_=0}for(;i--;){var c=r[i];1===c.diffValue_&&(c.diffValue_=0,tt(c,e))}n!==Ue.UP_TO_DATE_&&(e.dependenciesState_=n,e.onBecomeStale_())}(e),Qe(n),i}function Ge(e){var t=e.observing_;e.observing_=[];for(var r=t.length;r--;)rt(t[r],e);e.dependenciesState_=Ue.NOT_TRACKING_}function Ke(e){var t=qe();try{return e()}finally{We(t)}}function qe(){var e=et.trackingDerivation;return et.trackingDerivation=null,e}function We(e){et.trackingDerivation=e}function Ye(e){var t=et.allowStateReads;return et.allowStateReads=e,t}function Qe(e){et.allowStateReads=e}function Xe(e){if(e.dependenciesState_!==Ue.UP_TO_DATE_){e.dependenciesState_=Ue.UP_TO_DATE_;for(var t=e.observing_,r=t.length;r--;)t[r].lowestObserverState_=Ue.UP_TO_DATE_}}var Ze=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},Je=!0,et=function(){var t=r();return t.__mobxInstanceCount>0&&!t.__mobxGlobals&&(Je=!1),t.__mobxGlobals&&t.__mobxGlobals.version!==(new Ze).version&&(Je=!1),Je?t.__mobxGlobals?(t.__mobxInstanceCount+=1,t.__mobxGlobals.UNCHANGED||(t.__mobxGlobals.UNCHANGED={}),t.__mobxGlobals):(t.__mobxInstanceCount=1,t.__mobxGlobals=new Ze):(setTimeout((function(){e(35)}),1),new Ze)}();function tt(e,t){e.observers_.add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function rt(e,t){e.observers_.delete(t),0===e.observers_.size&&nt(e)}function nt(e){!1===e.isPendingUnobservation_&&(e.isPendingUnobservation_=!0,et.pendingUnobservations.push(e))}function it(){et.inBatch++}function ot(){if(0==--et.inBatch){ct();for(var e=et.pendingUnobservations,t=0;t0&&nt(e),!1)}function st(e){e.lowestObserverState_!==Ue.STALE_&&(e.lowestObserverState_=Ue.STALE_,e.observers_.forEach((function(e){e.dependenciesState_===Ue.UP_TO_DATE_&&e.onBecomeStale_(),e.dependenciesState_=Ue.STALE_})))}var ut=function(){function t(e,t,r,n){void 0===e&&(e="Reaction"),void 0===n&&(n=!1),this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=Ue.NOT_TRACKING_,this.diffValue_=0,this.runId_=0,this.unboundDepsCount_=0,this.isDisposed_=!1,this.isScheduled_=!1,this.isTrackPending_=!1,this.isRunning_=!1,this.isTracing_=Me.NONE,this.name_=e,this.onInvalidate_=t,this.errorHandler_=r,this.requiresObservable_=n}var r=t.prototype;return r.onBecomeStale_=function(){this.schedule_()},r.schedule_=function(){this.isScheduled_||(this.isScheduled_=!0,et.pendingReactions.push(this),ct())},r.isScheduled=function(){return this.isScheduled_},r.runReaction_=function(){if(!this.isDisposed_){it(),this.isScheduled_=!1;var e=et.trackingContext;if(et.trackingContext=this,He(this)){this.isTrackPending_=!0;try{this.onInvalidate_()}catch(e){this.reportExceptionInDerivation_(e)}}et.trackingContext=e,ot()}},r.track=function(e){if(!this.isDisposed_){it(),this.isRunning_=!0;var t=et.trackingContext;et.trackingContext=this;var r=Be(this,e,void 0);et.trackingContext=t,this.isRunning_=!1,this.isTrackPending_=!1,this.isDisposed_&&Ge(this),$e(r)&&this.reportExceptionInDerivation_(r.cause),ot()}},r.reportExceptionInDerivation_=function(e){var t=this;if(this.errorHandler_)this.errorHandler_(e,this);else{if(et.disableErrorBoundaries)throw e;var r="[mobx] uncaught error in '"+this+"'";et.suppressReactionErrors||console.error(r,e),et.globalReactionErrorHandlers.forEach((function(r){return r(e,t)}))}},r.dispose=function(){this.isDisposed_||(this.isDisposed_=!0,this.isRunning_||(it(),Ge(this),ot()))},r.getDisposer_=function(){var e=this.dispose.bind(this);return e[F]=this,e},r.toString=function(){return"Reaction["+this.name_+"]"},r.trace=function(t){void 0===t&&(t=!1),function(){e("trace() is not available in production builds");for(var t=!1,r=arguments.length,n=new Array(r),i=0;i0||et.isRunningReactions||function(e){e()}(lt)}function lt(){et.isRunningReactions=!0;for(var e=et.pendingReactions,t=0;e.length>0;){100==++t&&(console.error("[mobx] cycle in reaction: "+e[0]),e.splice(0));for(var r=e.splice(0),n=0,i=r.length;n",t,e):b(r)?Ie(t,r,e):d(r)?M(t,r,e?bt:pt):d(t)?U(K(e?"autoAction":"action",{name:t,autoAction:e})):void 0}}var yt=vt(!1);Object.assign(yt,pt);var gt=vt(!0);function mt(e){return Ce(e.name,!1,e,this,void 0)}function _t(e){return b(e)&&!0===e.isMobxAction}Object.assign(gt,bt),yt.bound=U(ht),gt.bound=U(dt);var wt=function(e){return e()};function Ot(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:wt}function jt(e,t,r){var n;void 0===r&&(r=u);var i,o,a,s=null!=(n=r.name)?n:"Reaction",c=yt(s,r.onError?(i=r.onError,o=t,function(){try{return o.apply(this,arguments)}catch(e){i.call(this,e)}}):t),l=!r.scheduler&&!r.delay,f=Ot(r),p=!0,h=!1,b=void 0,d=r.compareStructural?H.structural:r.equals||H.default,v=new ut(s,(function(){p||l?y():h||(h=!0,f(y))}),r.onError,r.requiresObservable);function y(){if(h=!1,!v.isDisposed_){var t=!1;v.track((function(){var r=function(e,t){var r=ke(e);try{return t()}finally{De(r)}}(!1,(function(){return e(v)}));t=p||!d(a,r),b=a,a=r})),(p&&r.fireImmediately||!p&&t)&&c(a,b,v),p=!1}}return v.schedule_(),v.getDisposer_()}function Pt(e,t,r){return St("onBUO",e,t,r)}function St(e,t,r,n){var i="function"==typeof n?Vr(t,r):Vr(t),o=b(n)?n:r,a=e+"L";return i[a]?i[a].add(o):i[a]=new Set([o]),function(){var e=i[a];e&&(e.delete(o),0===e.size&&delete i[a])}}var At=0;function xt(){this.message="FLOW_CANCELLED"}xt.prototype=Object.create(Error.prototype);var Et=Q("flow"),Tt=Q("flow.bound",{bound:!0}),It=Object.assign((function(e,t){if(d(t))return M(e,t,Et);var r=e,n=r.name||"",i=function(){var e,t=this,i=arguments,o=++At,a=yt(n+" - runid: "+o+" - init",r).apply(t,i),s=void 0,u=new Promise((function(t,r){var i=0;function u(e){var t;s=void 0;try{t=yt(n+" - runid: "+o+" - yield "+i++,a.next).call(a,e)}catch(e){return r(e)}l(t)}function c(e){var t;s=void 0;try{t=yt(n+" - runid: "+o+" - yield "+i++,a.throw).call(a,e)}catch(e){return r(e)}l(t)}function l(e){if(!b(null==e?void 0:e.then))return e.done?t(e.value):(s=Promise.resolve(e.value)).then(u,c);e.then(l,r)}e=r,u(void 0)}));return u.cancel=yt(n+" - runid: "+o+" - cancel",(function(){try{s&&Ct(s);var t=a.return(void 0),r=Promise.resolve(t.value);r.then(h,h),Ct(r),e(new xt)}catch(t){e(t)}})),u};return i.isMobXFlow=!0,i}),Et);function Ct(e){b(e.cancel)&&e.cancel()}function kt(e){return!0===(null==e?void 0:e.isMobXFlow)}function Dt(e,t,r){var n;return vr(e)||lr(e)||Re(e)?n=Rr(e):Sr(e)&&(n=Rr(e,t)),n.dehancer="function"==typeof t?t:r,function(){n.dehancer=void 0}}function Nt(e,t,r){return b(r)?function(e,t,r){return Rr(e,t).intercept_(r)}(e,t,r):function(e,t){return Rr(e).intercept_(t)}(e,t)}function Vt(e){return function(e,t){return!!e&&(void 0!==t?!!Sr(e)&&e[F].values_.has(t):Sr(e)||!!e[F]||L(e)||ft(e)||ze(e))}(e)}function Rt(t){return Sr(t)?t[F].keys_():vr(t)||mr(t)?Array.from(t.keys()):lr(t)?t.map((function(e,t){return t})):void e(5)}function Ut(t){return Sr(t)?Rt(t).map((function(e){return t[e]})):vr(t)?Rt(t).map((function(e){return t.get(e)})):mr(t)?Array.from(t.values()):lr(t)?t.slice():void e(6)}function Mt(t,r,n){if(2!==arguments.length||mr(t))Sr(t)?t[F].set_(r,n):vr(t)?t.set(r,n):mr(t)?t.add(r):lr(t)?("number"!=typeof r&&(r=parseInt(r,10)),r<0&&e("Invalid index: '"+r+"'"),it(),r>=t.length&&(t.length=r+1),t[r]=n,ot()):e(8);else{it();var i=r;try{for(var o in i)Mt(t,o,i[o])}finally{ot()}}}function Ft(t,r,n){if(Sr(t))return t[F].defineProperty_(r,n);e(39)}function zt(e,t,r,n){return b(r)?function(e,t,r,n){return Rr(e,t).observe_(r,n)}(e,t,r,n):function(e,t,r){return Rr(e).observe_(t,r)}(e,t,r)}function Lt(e){switch(e.length){case 0:return et.trackingDerivation;case 1:return Vr(e[0]);case 2:return Vr(e[0],e[1])}}function $t(e,t){void 0===t&&(t=void 0),it();try{return e.apply(t)}finally{ot()}}function Ht(e){return e[F]}It.bound=U(Tt);var Bt={has:function(e,t){return Ht(e).has_(t)},get:function(e,t){return Ht(e).get_(t)},set:function(e,t,r){var n;return!!d(t)&&(null==(n=Ht(e).set_(t,r,!0))||n)},deleteProperty:function(e,t){var r;return!!d(t)&&(null==(r=Ht(e).delete_(t,!0))||r)},defineProperty:function(e,t,r){var n;return null==(n=Ht(e).defineProperty_(t,r))||n},ownKeys:function(e){return Ht(e).ownKeys_()},preventExtensions:function(t){e(13)}};function Gt(e){return void 0!==e.interceptors_&&e.interceptors_.length>0}function Kt(e,t){var r=e.interceptors_||(e.interceptors_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function qt(t,r){var n=qe();try{for(var i=[].concat(t.interceptors_||[]),o=0,a=i.length;o0}function Yt(e,t){var r=e.changeListeners_||(e.changeListeners_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function Qt(e,t){var r=qe(),n=e.changeListeners_;if(n){for(var i=0,o=(n=n.slice()).length;i0?e.map(this.dehancer):e},r.intercept_=function(e){return Kt(this,e)},r.observe_=function(e,t){return void 0===t&&(t=!1),t&&e({observableKind:"array",object:this.proxy_,debugObjectName:this.atom_.name_,type:"splice",index:0,added:this.values_.slice(),addedCount:this.values_.length,removed:[],removedCount:0}),Yt(this,e)},r.getArrayLength_=function(){return this.atom_.reportObserved(),this.values_.length},r.setArrayLength_=function(t){("number"!=typeof t||t<0)&&e("Out of range: "+t);var r=this.values_.length;if(t!==r)if(t>r){for(var n=new Array(t-r),i=0;i0&&Dr(t+r+1)},r.spliceWithArray_=function(e,t,r){var n=this;this.atom_;var i=this.values_.length;if(void 0===e?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=1===arguments.length?i-e:null==t?0:Math.max(0,Math.min(t,i-e)),void 0===r&&(r=s),Gt(this)){var o=qt(this,{object:this.proxy_,type:"splice",index:e,removedCount:t,added:r});if(!o)return s;t=o.removedCount,r=o.added}if(r=0===r.length?r:r.map((function(e){return n.enhancer_(e,void 0)})),this.legacyMode_){var a=r.length-t;this.updateArrayLength_(i,a)}var u=this.spliceItemsIntoValues_(e,t,r);return 0===t&&0===r.length||this.notifyArraySplice_(e,r,u),this.dehanceValues_(u)},r.spliceItemsIntoValues_=function(e,t,r){var n;if(r.length<1e4)return(n=this.values_).splice.apply(n,[e,t].concat(r));var i=this.values_.slice(e,e+t),o=this.values_.slice(e+t);this.values_.length=e+r.length-t;for(var a=0;a2?r-2:0),i=2;i-1&&(this.splice(r,1),!0)}};function nr(e,t){"function"==typeof Array.prototype[e]&&(rr[e]=t(e))}function ir(e){return function(){var t=this[F];t.atom_.reportObserved();var r=t.dehanceValues_(t.values_);return r[e].apply(r,arguments)}}function or(e){return function(t,r){var n=this,i=this[F];return i.atom_.reportObserved(),i.dehanceValues_(i.values_)[e]((function(e,i){return t.call(r,e,i,n)}))}}function ar(e){return function(){var t=this,r=this[F];r.atom_.reportObserved();var n=r.dehanceValues_(r.values_),i=arguments[0];return arguments[0]=function(e,r,n){return i(e,r,n,t)},n[e].apply(n,arguments)}}nr("concat",ir),nr("flat",ir),nr("includes",ir),nr("indexOf",ir),nr("join",ir),nr("lastIndexOf",ir),nr("slice",ir),nr("toString",ir),nr("toLocaleString",ir),nr("every",or),nr("filter",or),nr("find",or),nr("findIndex",or),nr("flatMap",or),nr("forEach",or),nr("map",or),nr("some",or),nr("reduce",ar),nr("reduceRight",ar);var sr,ur,cr=w("ObservableArrayAdministration",er);function lr(e){return v(e)&&cr(e[F])}var fr={},pr="add";sr=Symbol.iterator,ur=Symbol.toStringTag;var hr,br,dr=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableMap"),this.enhancer_=void 0,this.name_=void 0,this[F]=fr,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=r,this.name_=n,b(Map)||e(18),this.keysAtom_=$("ObservableMap.keys()"),this.data_=new Map,this.hasMap_=new Map,this.merge(t)}var r=t.prototype;return r.has_=function(e){return this.data_.has(e)},r.has=function(e){var t=this;if(!et.trackingDerivation)return this.has_(e);var r=this.hasMap_.get(e);if(!r){var n=r=new Ve(this.has_(e),G,"ObservableMap.key?",!1);this.hasMap_.set(e,n),Pt(n,(function(){return t.hasMap_.delete(e)}))}return r.get()},r.set=function(e,t){var r=this.has_(e);if(Gt(this)){var n=qt(this,{type:r?Zt:pr,object:this,newValue:t,name:e});if(!n)return this;t=n.newValue}return r?this.updateValue_(e,t):this.addValue_(e,t),this},r.delete=function(e){var t=this;if((this.keysAtom_,Gt(this))&&!qt(this,{type:"delete",object:this,name:e}))return!1;if(this.has_(e)){var r=Wt(this),n=r?{observableKind:"map",debugObjectName:this.name_,type:"delete",object:this,oldValue:this.data_.get(e).value_,name:e}:null;return $t((function(){t.keysAtom_.reportChanged(),t.updateHasMapEntry_(e,!1),t.data_.get(e).setNewValue_(void 0),t.data_.delete(e)})),r&&Qt(this,n),!0}return!1},r.updateHasMapEntry_=function(e,t){var r=this.hasMap_.get(e);r&&r.setNewValue_(t)},r.updateValue_=function(e,t){var r=this.data_.get(e);if((t=r.prepareNewValue_(t))!==et.UNCHANGED){var n=Wt(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:Zt,object:this,oldValue:r.value_,name:e,newValue:t}:null;r.setNewValue_(t),n&&Qt(this,i)}},r.addValue_=function(e,t){var r=this;this.keysAtom_,$t((function(){var n=new Ve(t,r.enhancer_,"ObservableMap.key",!1);r.data_.set(e,n),t=n.value_,r.updateHasMapEntry_(e,!0),r.keysAtom_.reportChanged()}));var n=Wt(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:pr,object:this,name:e,newValue:t}:null;n&&Qt(this,i)},r.get=function(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)},r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.keys=function(){return this.keysAtom_.reportObserved(),this.data_.keys()},r.values=function(){var e=this,t=this.keys();return $r({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:e.get(i)}}})},r.entries=function(){var e=this,t=this.keys();return $r({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:[i,e.get(i)]}}})},r[sr]=function(){return this.entries()},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value,o=i[0],a=i[1];e.call(t,a,o,this)}},r.merge=function(t){var r=this;return vr(t)&&(t=new Map(t)),$t((function(){y(t)?function(e){var t=Object.keys(e);if(!P)return t;var r=Object.getOwnPropertySymbols(e);return r.length?[].concat(t,r.filter((function(t){return a.propertyIsEnumerable.call(e,t)}))):t}(t).forEach((function(e){return r.set(e,t[e])})):Array.isArray(t)?t.forEach((function(e){var t=e[0],n=e[1];return r.set(t,n)})):O(t)?(t.constructor!==Map&&e(19,t),t.forEach((function(e,t){return r.set(t,e)}))):null!=t&&e(20,t)})),this},r.clear=function(){var e=this;$t((function(){Ke((function(){for(var t,r=V(e.keys());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.replace=function(t){var r=this;return $t((function(){for(var n,i=function(t){if(O(t)||vr(t))return t;if(Array.isArray(t))return new Map(t);if(y(t)){var r=new Map;for(var n in t)r.set(n,t[n]);return r}return e(21,t)}(t),o=new Map,a=!1,s=V(r.data_.keys());!(n=s()).done;){var u=n.value;if(!i.has(u))if(r.delete(u))a=!0;else{var c=r.data_.get(u);o.set(u,c)}}for(var l,f=V(i.entries());!(l=f()).done;){var p=l.value,h=p[0],b=p[1],d=r.data_.has(h);if(r.set(h,b),r.data_.has(h)){var v=r.data_.get(h);o.set(h,v),d||(a=!0)}}if(!a)if(r.data_.size!==o.size)r.keysAtom_.reportChanged();else for(var g=r.data_.keys(),m=o.keys(),_=g.next(),w=m.next();!_.done;){if(_.value!==w.value){r.keysAtom_.reportChanged();break}_=g.next(),w=m.next()}r.data_=o})),this},r.toString=function(){return"[object ObservableMap]"},r.toJSON=function(){return Array.from(this)},r.observe_=function(e,t){return Yt(this,e)},r.intercept_=function(e){return Kt(this,e)},I(t,[{key:"size",get:function(){return this.keysAtom_.reportObserved(),this.data_.size}},{key:ur,get:function(){return"Map"}}]),t}(),vr=w("ObservableMap",dr);var yr={};hr=Symbol.iterator,br=Symbol.toStringTag;var gr=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableSet"),this.name_=void 0,this[F]=yr,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,b(Set)||e(22),this.atom_=$(this.name_),this.enhancer_=function(e,t){return r(e,t,n)},t&&this.replace(t)}var r=t.prototype;return r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.clear=function(){var e=this;$t((function(){Ke((function(){for(var t,r=V(e.data_.values());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value;e.call(t,i,i,this)}},r.add=function(e){var t=this;if((this.atom_,Gt(this))&&!qt(this,{type:pr,object:this,newValue:e}))return this;if(!this.has(e)){$t((function(){t.data_.add(t.enhancer_(e,void 0)),t.atom_.reportChanged()}));var r=Wt(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:pr,object:this,newValue:e}:null;r&&Qt(this,n)}return this},r.delete=function(e){var t=this;if(Gt(this)&&!qt(this,{type:"delete",object:this,oldValue:e}))return!1;if(this.has(e)){var r=Wt(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:"delete",object:this,oldValue:e}:null;return $t((function(){t.atom_.reportChanged(),t.data_.delete(e)})),r&&Qt(this,n),!0}return!1},r.has=function(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))},r.entries=function(){var e=0,t=Array.from(this.keys()),r=Array.from(this.values());return $r({next:function(){var n=e;return e+=1,nTr){for(var t=Tr;t=0&&r++}e=Lr(e),t=Lr(t);var s="[object Array]"===a;if(!s){if("object"!=typeof e||"object"!=typeof t)return!1;var u=e.constructor,c=t.constructor;if(u!==c&&!(b(u)&&u instanceof u&&b(c)&&c instanceof c)&&"constructor"in e&&"constructor"in t)return!1}if(0===r)return!1;r<0&&(r=-1),i=i||[];for(var l=(n=n||[]).length;l--;)if(n[l]===e)return i[l]===t;if(n.push(e),i.push(t),s){if((l=e.length)!==t.length)return!1;for(;l--;)if(!zr(e[l],t[l],r-1,n,i))return!1}else{var f,p=Object.keys(e);if(l=p.length,Object.keys(t).length!==l)return!1;for(;l--;)if(!x(t,f=p[l])||!zr(e[f],t[f],r-1,n,i))return!1}return n.pop(),i.pop(),!0}function Lr(e){return lr(e)?e.slice():O(e)||vr(e)||j(e)||mr(e)?Array.from(e.entries()):e}function $r(e){return e[Symbol.iterator]=Hr,e}function Hr(){return this}["Symbol","Map","Set","Symbol"].forEach((function(t){void 0===r()[t]&&e("MobX requires global '"+t+"' to be available or polyfilled")})),"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:function(e){return console.warn("[mobx.spy] Is a no-op in production builds"),function(){}},extras:{getDebugName:Ur},$mobx:F});var Br;!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(Br||(Br={})); +"use strict";function e(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;ne.length)&&(t=e.length);for(var r=0,n=new Array(t);r=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=e[Symbol.iterator]()).next.bind(r)}var R=Symbol("mobx-stored-annotations");function U(e){return Object.assign((function(t,r){M(t,r,e)}),e)}function M(e,t,r){x(e,R)||m(e,R,C({},e[R])),function(e){return"override"===e.annotationType_}(r)||(e[R][t]=r)}var z=Symbol("mobx administration"),F=function(){function e(e){void 0===e&&(e="Atom"),this.name_=void 0,this.isPendingUnobservation_=!1,this.isBeingObserved_=!1,this.observers_=new Set,this.diffValue_=0,this.lastAccessedBy_=0,this.lowestObserverState_=Ue.NOT_TRACKING_,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return at(this)},t.reportChanged=function(){it(),st(this),ot()},t.toString=function(){return this.name_},e}(),L=w("Atom",F);function $(e,t,r){void 0===t&&(t=h),void 0===r&&(r=h);var n,i=new F(e);return t!==h&&St("onBO",i,t,n),r!==h&&Pt(i,r),i}var H={identity:function(e,t){return e===t},structural:function(e,t){return zr(e,t)},default:function(e,t){return Object.is(e,t)},shallow:function(e,t){return zr(e,t,1)}};function B(e,t,r){return Vt(e)?e:Array.isArray(e)?we.array(e,{name:r}):y(e)?we.object(e,void 0,{name:r}):O(e)?we.map(e,{name:r}):j(e)?we.set(e,{name:r}):"function"!=typeof e||_t(e)||kt(e)?e:g(e)?It(e):gt(r,e)}function G(e){return e}function K(e,t){return{annotationType_:e,options_:t,make_:q,extend_:W}}function q(e,t,r,n){var i;if(null==(i=this.options_)?void 0:i.bound)return null===this.extend_(e,t,r,!1)?0:1;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if(_t(r.value))return 1;var a=Y(e,this,t,r,!1);return o(n,t,a),2}function W(e,t,r,n){var i=Y(e,this,t,r);return e.defineProperty_(t,i,n)}function Y(e,t,r,n,i){var o,a,s,u,c,l;void 0===i&&(i=et.safeDescriptors),l=n,t.annotationType_,l.value;var f,p=n.value;(null==(o=t.options_)?void 0:o.bound)&&(p=p.bind(null!=(f=e.proxy_)?f:e.target_));return{value:Ie(null!=(a=null==(s=t.options_)?void 0:s.name)?a:r.toString(),p,null!=(u=null==(c=t.options_)?void 0:c.autoAction)&&u),configurable:!i||e.isPlainObject_,enumerable:!1,writable:!i}}function Q(e,t){return{annotationType_:e,options_:t,make_:X,extend_:Z}}function X(e,t,r,n){var i;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if((null==(i=this.options_)?void 0:i.bound)&&!kt(e.target_[t])&&null===this.extend_(e,t,r,!1))return 0;if(kt(r.value))return 1;var a=J(e,this,t,r,!1,!1);return o(n,t,a),2}function Z(e,t,r,n){var i,o=J(e,this,t,r,null==(i=this.options_)?void 0:i.bound);return e.defineProperty_(t,o,n)}function J(e,t,r,n,i,o){var a;void 0===o&&(o=et.safeDescriptors),a=n,t.annotationType_,a.value;var s,u=n.value;i&&(u=u.bind(null!=(s=e.proxy_)?s:e.target_));return{value:It(u),configurable:!o||e.isPlainObject_,enumerable:!1,writable:!o}}function ee(e,t){return{annotationType_:e,options_:t,make_:te,extend_:re}}function te(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function re(e,t,r,n){var i;return i=r,this.annotationType_,i.get,e.defineComputedProperty_(t,C({},this.options_,{get:r.get,set:r.set}),n)}function ne(e,t){return{annotationType_:e,options_:t,make_:ie,extend_:oe}}function ie(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function oe(e,t,r,n){var i,o;return this.annotationType_,e.defineObservableProperty_(t,r.value,null!=(i=null==(o=this.options_)?void 0:o.enhancer)?i:B,n)}var ae=se();function se(e){return{annotationType_:"true",options_:e,make_:ue,extend_:ce}}function ue(e,t,r,n){var i,a,s,u;if(r.get)return Pe.make_(e,t,r,n);if(r.set){var c=Ie(t.toString(),r.set);return n===e.target_?null===e.defineProperty_(t,{configurable:!et.safeDescriptors||e.isPlainObject_,set:c})?0:2:(o(n,t,{configurable:!0,set:c}),2)}if(n!==e.target_&&"function"==typeof r.value)return g(r.value)?((null==(u=this.options_)?void 0:u.autoBind)?It.bound:It).make_(e,t,r,n):((null==(s=this.options_)?void 0:s.autoBind)?gt.bound:gt).make_(e,t,r,n);var l,f=!1===(null==(i=this.options_)?void 0:i.deep)?we.ref:we;"function"==typeof r.value&&(null==(a=this.options_)?void 0:a.autoBind)&&(r.value=r.value.bind(null!=(l=e.proxy_)?l:e.target_));return f.make_(e,t,r,n)}function ce(e,t,r,n){var i,o,a;if(r.get)return Pe.extend_(e,t,r,n);if(r.set)return e.defineProperty_(t,{configurable:!et.safeDescriptors||e.isPlainObject_,set:Ie(t.toString(),r.set)},n);"function"==typeof r.value&&(null==(i=this.options_)?void 0:i.autoBind)&&(r.value=r.value.bind(null!=(a=e.proxy_)?a:e.target_));return(!1===(null==(o=this.options_)?void 0:o.deep)?we.ref:we).extend_(e,t,r,n)}var le={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function fe(e){return e||le}Object.freeze(le);var pe=ne("observable"),he=ne("observable.ref",{enhancer:G}),be=ne("observable.shallow",{enhancer:function(e,t,r){return null==e||Sr(e)||lr(e)||vr(e)||mr(e)?e:Array.isArray(e)?we.array(e,{name:r,deep:!1}):y(e)?we.object(e,void 0,{name:r,deep:!1}):O(e)?we.map(e,{name:r,deep:!1}):j(e)?we.set(e,{name:r,deep:!1}):void 0}}),de=ne("observable.struct",{enhancer:function(e,t){return zr(e,t)?t:e}}),ve=U(pe);function ye(e){return!0===e.deep?B:!1===e.deep?G:(t=e.defaultDecorator)&&null!=(r=null==(n=t.options_)?void 0:n.enhancer)?r:B;var t,r,n}function ge(e,t,r){if(!d(t))return Vt(e)?e:y(e)?we.object(e,t,r):Array.isArray(e)?we.array(e,t):O(e)?we.map(e,t):j(e)?we.set(e,t):"object"==typeof e&&null!==e?e:we.box(e,t);M(e,t,pe)}Object.assign(ge,ve);var me,_e,we=n(ge,{box:function(e,t){var r=fe(t);return new Ve(e,ye(r),r.name,!0,r.equals)},array:function(e,t){var r=fe(t);return(!1===et.useProxies||!1===r.proxy?Nr:tr)(e,ye(r),r.name)},map:function(e,t){var r=fe(t);return new dr(e,ye(r),r.name)},set:function(e,t){var r=fe(t);return new gr(e,ye(r),r.name)},object:function(e,t,r){return function(e,t,r,n){var i=E(t),o=Or(e,n)[z];it();try{S(i).forEach((function(e){o.extend_(e,i[e],!r||(!(e in r)||r[e]))}))}finally{ot()}return e}(!1===et.useProxies||!1===(null==r?void 0:r.proxy)?Or({},r):function(e,t){var r,n;return f(),e=Or(e,t),null!=(n=(r=e[z]).proxy_)?n:r.proxy_=new Proxy(e,Bt)}({},r),e,t)},ref:U(he),shallow:U(be),deep:ve,struct:U(de)}),Oe=ee("computed"),je=ee("computed.struct",{equals:H.structural}),Pe=function(e,t){if(d(t))return M(e,t,Oe);if(y(e))return U(ee("computed",e));var r=y(t)?t:{};return r.get=e,r.name||(r.name=e.name||""),new ze(r)};Object.assign(Pe,Oe),Pe.struct=U(je);var Se,Ae=0,xe=1,Ee=null!=(me=null==(_e=i((function(){}),"name"))?void 0:_e.configurable)&&me,Te={value:"action",configurable:!0,writable:!1,enumerable:!1};function Ie(e,t,r,n){function i(){return Ce(e,r,t,n||this,arguments)}return void 0===r&&(r=!1),i.isMobxAction=!0,Ee&&(Te.value=e,Object.defineProperty(i,"name",Te)),i}function Ce(t,r,n,i,o){var a=function(e,t,r,n){var i=!1,o=0,a=et.trackingDerivation,s=!t||!a;it();var u=et.allowStateChanges;s&&(qe(),u=ke(!0));var c=Ye(!0),l={runAsAction_:s,prevDerivation_:a,prevAllowStateChanges_:u,prevAllowStateReads_:c,notifySpy_:i,startTime_:o,actionId_:xe++,parentActionId_:Ae};return Ae=l.actionId_,l}(0,r);try{return n.apply(i,o)}catch(e){throw a.error_=e,e}finally{!function(t){Ae!==t.actionId_&&e(30);Ae=t.parentActionId_,void 0!==t.error_&&(et.suppressReactionErrors=!0);De(t.prevAllowStateChanges_),Qe(t.prevAllowStateReads_),ot(),t.runAsAction_&&We(t.prevDerivation_);et.suppressReactionErrors=!1}(a)}}function ke(e){var t=et.allowStateChanges;return et.allowStateChanges=e,t}function De(e){et.allowStateChanges=e}Se=Symbol.toPrimitive;var Ne,Ve=function(e){function t(t,r,n,i,o){var a;return void 0===n&&(n="ObservableValue"),void 0===o&&(o=H.default),(a=e.call(this,n)||this).enhancer=void 0,a.name_=void 0,a.equals=void 0,a.hasUnreportedChange_=!1,a.interceptors_=void 0,a.changeListeners_=void 0,a.value_=void 0,a.dehancer=void 0,a.enhancer=r,a.name_=n,a.equals=o,a.value_=r(t,void 0,n),a}k(t,e);var r=t.prototype;return r.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.set=function(e){this.value_,(e=this.prepareNewValue_(e))!==et.UNCHANGED&&this.setNewValue_(e)},r.prepareNewValue_=function(e){if(Gt(this)){var t=qt(this,{object:this,type:Zt,newValue:e});if(!t)return et.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value_,this.name_),this.equals(this.value_,e)?et.UNCHANGED:e},r.setNewValue_=function(e){var t=this.value_;this.value_=e,this.reportChanged(),Wt(this)&&Qt(this,{type:Zt,object:this,newValue:e,oldValue:t})},r.get=function(){return this.reportObserved(),this.dehanceValue(this.value_)},r.intercept_=function(e){return Kt(this,e)},r.observe_=function(e,t){return t&&e({observableKind:"value",debugObjectName:this.name_,object:this,type:Zt,newValue:this.value_,oldValue:void 0}),Yt(this,e)},r.raw=function(){return this.value_},r.toJSON=function(){return this.get()},r.toString=function(){return this.name_+"["+this.value_+"]"},r.valueOf=function(){return A(this.get())},r[Se]=function(){return this.valueOf()},t}(F),Re=w("ObservableValue",Ve);Ne=Symbol.toPrimitive;var Ue,Me,ze=function(){function t(t){this.dependenciesState_=Ue.NOT_TRACKING_,this.observing_=[],this.newObserving_=null,this.isBeingObserved_=!1,this.isPendingUnobservation_=!1,this.observers_=new Set,this.diffValue_=0,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=Ue.UP_TO_DATE_,this.unboundDepsCount_=0,this.value_=new Le(null),this.name_=void 0,this.triggeredBy_=void 0,this.isComputing_=!1,this.isRunningSetter_=!1,this.derivation=void 0,this.setter_=void 0,this.isTracing_=Me.NONE,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,t.get||e(31),this.derivation=t.get,this.name_=t.name||"ComputedValue",t.set&&(this.setter_=Ie("ComputedValue-setter",t.set)),this.equals_=t.equals||(t.compareStructural||t.struct?H.structural:H.default),this.scope_=t.context,this.requiresReaction_=!!t.requiresReaction,this.keepAlive_=!!t.keepAlive}var r=t.prototype;return r.onBecomeStale_=function(){!function(e){if(e.lowestObserverState_!==Ue.UP_TO_DATE_)return;e.lowestObserverState_=Ue.POSSIBLY_STALE_,e.observers_.forEach((function(e){e.dependenciesState_===Ue.UP_TO_DATE_&&(e.dependenciesState_=Ue.POSSIBLY_STALE_,e.onBecomeStale_())}))}(this)},r.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},r.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},r.get=function(){if(this.isComputing_&&e(32,this.name_,this.derivation),0!==et.inBatch||0!==this.observers_.size||this.keepAlive_){if(at(this),He(this)){var t=et.trackingContext;this.keepAlive_&&!t&&(et.trackingContext=this),this.trackAndCompute()&&function(e){if(e.lowestObserverState_===Ue.STALE_)return;e.lowestObserverState_=Ue.STALE_,e.observers_.forEach((function(t){t.dependenciesState_===Ue.POSSIBLY_STALE_?t.dependenciesState_=Ue.STALE_:t.dependenciesState_===Ue.UP_TO_DATE_&&(e.lowestObserverState_=Ue.UP_TO_DATE_)}))}(this),et.trackingContext=t}}else He(this)&&(this.warnAboutUntrackedRead_(),it(),this.value_=this.computeValue_(!1),ot());var r=this.value_;if($e(r))throw r.cause;return r},r.set=function(t){if(this.setter_){this.isRunningSetter_&&e(33,this.name_),this.isRunningSetter_=!0;try{this.setter_.call(this.scope_,t)}finally{this.isRunningSetter_=!1}}else e(34,this.name_)},r.trackAndCompute=function(){var e=this.value_,t=this.dependenciesState_===Ue.NOT_TRACKING_,r=this.computeValue_(!0),n=t||$e(e)||$e(r)||!this.equals_(e,r);return n&&(this.value_=r),n},r.computeValue_=function(e){this.isComputing_=!0;var t,r=ke(!1);if(e)t=Be(this,this.derivation,this.scope_);else if(!0===et.disableErrorBoundaries)t=this.derivation.call(this.scope_);else try{t=this.derivation.call(this.scope_)}catch(e){t=new Le(e)}return De(r),this.isComputing_=!1,t},r.suspend_=function(){this.keepAlive_||(Ge(this),this.value_=void 0)},r.observe_=function(e,t){var r=this,n=!0,i=void 0;return function(e,t){var r,n;void 0===t&&(t=u);var i,o=null!=(r=null==(n=t)?void 0:n.name)?r:"Autorun";if(t.scheduler||t.delay){var a=Ot(t),s=!1;i=new ut(o,(function(){s||(s=!0,a((function(){s=!1,i.isDisposed_||i.track(c)})))}),t.onError,t.requiresObservable)}else i=new ut(o,(function(){this.track(c)}),t.onError,t.requiresObservable);function c(){e(i)}return i.schedule_(),i.getDisposer_()}((function(){var o=r.get();if(!n||t){var a=qe();e({observableKind:"computed",debugObjectName:r.name_,type:Zt,object:r,newValue:o,oldValue:i}),We(a)}n=!1,i=o}))},r.warnAboutUntrackedRead_=function(){},r.toString=function(){return this.name_+"["+this.derivation.toString()+"]"},r.valueOf=function(){return A(this.get())},r[Ne]=function(){return this.valueOf()},t}(),Fe=w("ComputedValue",ze);!function(e){e[e.NOT_TRACKING_=-1]="NOT_TRACKING_",e[e.UP_TO_DATE_=0]="UP_TO_DATE_",e[e.POSSIBLY_STALE_=1]="POSSIBLY_STALE_",e[e.STALE_=2]="STALE_"}(Ue||(Ue={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(Me||(Me={}));var Le=function(e){this.cause=void 0,this.cause=e};function $e(e){return e instanceof Le}function He(e){switch(e.dependenciesState_){case Ue.UP_TO_DATE_:return!1;case Ue.NOT_TRACKING_:case Ue.STALE_:return!0;case Ue.POSSIBLY_STALE_:for(var t=Ye(!0),r=qe(),n=e.observing_,i=n.length,o=0;on&&(n=s.dependenciesState_)}r.length=i,e.newObserving_=null,o=t.length;for(;o--;){var u=t[o];0===u.diffValue_&&rt(u,e),u.diffValue_=0}for(;i--;){var c=r[i];1===c.diffValue_&&(c.diffValue_=0,tt(c,e))}n!==Ue.UP_TO_DATE_&&(e.dependenciesState_=n,e.onBecomeStale_())}(e),Qe(n),i}function Ge(e){var t=e.observing_;e.observing_=[];for(var r=t.length;r--;)rt(t[r],e);e.dependenciesState_=Ue.NOT_TRACKING_}function Ke(e){var t=qe();try{return e()}finally{We(t)}}function qe(){var e=et.trackingDerivation;return et.trackingDerivation=null,e}function We(e){et.trackingDerivation=e}function Ye(e){var t=et.allowStateReads;return et.allowStateReads=e,t}function Qe(e){et.allowStateReads=e}function Xe(e){if(e.dependenciesState_!==Ue.UP_TO_DATE_){e.dependenciesState_=Ue.UP_TO_DATE_;for(var t=e.observing_,r=t.length;r--;)t[r].lowestObserverState_=Ue.UP_TO_DATE_}}var Ze=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},Je=!0,et=function(){var t=r();return t.__mobxInstanceCount>0&&!t.__mobxGlobals&&(Je=!1),t.__mobxGlobals&&t.__mobxGlobals.version!==(new Ze).version&&(Je=!1),Je?t.__mobxGlobals?(t.__mobxInstanceCount+=1,t.__mobxGlobals.UNCHANGED||(t.__mobxGlobals.UNCHANGED={}),t.__mobxGlobals):(t.__mobxInstanceCount=1,t.__mobxGlobals=new Ze):(setTimeout((function(){e(35)}),1),new Ze)}();function tt(e,t){e.observers_.add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function rt(e,t){e.observers_.delete(t),0===e.observers_.size&&nt(e)}function nt(e){!1===e.isPendingUnobservation_&&(e.isPendingUnobservation_=!0,et.pendingUnobservations.push(e))}function it(){et.inBatch++}function ot(){if(0==--et.inBatch){ct();for(var e=et.pendingUnobservations,t=0;t0&&nt(e),!1)}function st(e){e.lowestObserverState_!==Ue.STALE_&&(e.lowestObserverState_=Ue.STALE_,e.observers_.forEach((function(e){e.dependenciesState_===Ue.UP_TO_DATE_&&e.onBecomeStale_(),e.dependenciesState_=Ue.STALE_})))}var ut=function(){function t(e,t,r,n){void 0===e&&(e="Reaction"),void 0===n&&(n=!1),this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=Ue.NOT_TRACKING_,this.diffValue_=0,this.runId_=0,this.unboundDepsCount_=0,this.isDisposed_=!1,this.isScheduled_=!1,this.isTrackPending_=!1,this.isRunning_=!1,this.isTracing_=Me.NONE,this.name_=e,this.onInvalidate_=t,this.errorHandler_=r,this.requiresObservable_=n}var r=t.prototype;return r.onBecomeStale_=function(){this.schedule_()},r.schedule_=function(){this.isScheduled_||(this.isScheduled_=!0,et.pendingReactions.push(this),ct())},r.isScheduled=function(){return this.isScheduled_},r.runReaction_=function(){if(!this.isDisposed_){it(),this.isScheduled_=!1;var e=et.trackingContext;if(et.trackingContext=this,He(this)){this.isTrackPending_=!0;try{this.onInvalidate_()}catch(e){this.reportExceptionInDerivation_(e)}}et.trackingContext=e,ot()}},r.track=function(e){if(!this.isDisposed_){it(),this.isRunning_=!0;var t=et.trackingContext;et.trackingContext=this;var r=Be(this,e,void 0);et.trackingContext=t,this.isRunning_=!1,this.isTrackPending_=!1,this.isDisposed_&&Ge(this),$e(r)&&this.reportExceptionInDerivation_(r.cause),ot()}},r.reportExceptionInDerivation_=function(e){var t=this;if(this.errorHandler_)this.errorHandler_(e,this);else{if(et.disableErrorBoundaries)throw e;var r="[mobx] uncaught error in '"+this+"'";et.suppressReactionErrors||console.error(r,e),et.globalReactionErrorHandlers.forEach((function(r){return r(e,t)}))}},r.dispose=function(){this.isDisposed_||(this.isDisposed_=!0,this.isRunning_||(it(),Ge(this),ot()))},r.getDisposer_=function(){var e=this.dispose.bind(this);return e[z]=this,e},r.toString=function(){return"Reaction["+this.name_+"]"},r.trace=function(t){void 0===t&&(t=!1),function(){e("trace() is not available in production builds");for(var t=!1,r=arguments.length,n=new Array(r),i=0;i0||et.isRunningReactions||function(e){e()}(lt)}function lt(){et.isRunningReactions=!0;for(var e=et.pendingReactions,t=0;e.length>0;){100==++t&&(console.error("[mobx] cycle in reaction: "+e[0]),e.splice(0));for(var r=e.splice(0),n=0,i=r.length;n",t,e):b(r)?Ie(t,r,e):d(r)?M(t,r,e?bt:pt):d(t)?U(K(e?"autoAction":"action",{name:t,autoAction:e})):void 0}}var yt=vt(!1);Object.assign(yt,pt);var gt=vt(!0);function mt(e){return Ce(e.name,!1,e,this,void 0)}function _t(e){return b(e)&&!0===e.isMobxAction}Object.assign(gt,bt),yt.bound=U(ht),gt.bound=U(dt);var wt=function(e){return e()};function Ot(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:wt}function jt(e,t,r){var n;void 0===r&&(r=u);var i,o,a,s=null!=(n=r.name)?n:"Reaction",c=yt(s,r.onError?(i=r.onError,o=t,function(){try{return o.apply(this,arguments)}catch(e){i.call(this,e)}}):t),l=!r.scheduler&&!r.delay,f=Ot(r),p=!0,h=!1,b=void 0,d=r.compareStructural?H.structural:r.equals||H.default,v=new ut(s,(function(){p||l?y():h||(h=!0,f(y))}),r.onError,r.requiresObservable);function y(){if(h=!1,!v.isDisposed_){var t=!1;v.track((function(){var r=function(e,t){var r=ke(e);try{return t()}finally{De(r)}}(!1,(function(){return e(v)}));t=p||!d(a,r),b=a,a=r})),(p&&r.fireImmediately||!p&&t)&&c(a,b,v),p=!1}}return v.schedule_(),v.getDisposer_()}function Pt(e,t,r){return St("onBUO",e,t,r)}function St(e,t,r,n){var i="function"==typeof n?Vr(t,r):Vr(t),o=b(n)?n:r,a=e+"L";return i[a]?i[a].add(o):i[a]=new Set([o]),function(){var e=i[a];e&&(e.delete(o),0===e.size&&delete i[a])}}var At=0;function xt(){this.message="FLOW_CANCELLED"}xt.prototype=Object.create(Error.prototype);var Et=Q("flow"),Tt=Q("flow.bound",{bound:!0}),It=Object.assign((function(e,t){if(d(t))return M(e,t,Et);var r=e,n=r.name||"",i=function(){var e,t=this,i=arguments,o=++At,a=yt(n+" - runid: "+o+" - init",r).apply(t,i),s=void 0,u=new Promise((function(t,r){var i=0;function u(e){var t;s=void 0;try{t=yt(n+" - runid: "+o+" - yield "+i++,a.next).call(a,e)}catch(e){return r(e)}l(t)}function c(e){var t;s=void 0;try{t=yt(n+" - runid: "+o+" - yield "+i++,a.throw).call(a,e)}catch(e){return r(e)}l(t)}function l(e){if(!b(null==e?void 0:e.then))return e.done?t(e.value):(s=Promise.resolve(e.value)).then(u,c);e.then(l,r)}e=r,u(void 0)}));return u.cancel=yt(n+" - runid: "+o+" - cancel",(function(){try{s&&Ct(s);var t=a.return(void 0),r=Promise.resolve(t.value);r.then(h,h),Ct(r),e(new xt)}catch(t){e(t)}})),u};return i.isMobXFlow=!0,i}),Et);function Ct(e){b(e.cancel)&&e.cancel()}function kt(e){return!0===(null==e?void 0:e.isMobXFlow)}function Dt(e,t,r){var n;return vr(e)||lr(e)||Re(e)?n=Rr(e):Sr(e)&&(n=Rr(e,t)),n.dehancer="function"==typeof t?t:r,function(){n.dehancer=void 0}}function Nt(e,t,r){return b(r)?function(e,t,r){return Rr(e,t).intercept_(r)}(e,t,r):function(e,t){return Rr(e).intercept_(t)}(e,t)}function Vt(e){return function(e,t){return!!e&&(void 0!==t?!!Sr(e)&&e[z].values_.has(t):Sr(e)||!!e[z]||L(e)||ft(e)||Fe(e))}(e)}function Rt(t){return Sr(t)?t[z].keys_():vr(t)||mr(t)?Array.from(t.keys()):lr(t)?t.map((function(e,t){return t})):void e(5)}function Ut(t){return Sr(t)?Rt(t).map((function(e){return t[e]})):vr(t)?Rt(t).map((function(e){return t.get(e)})):mr(t)?Array.from(t.values()):lr(t)?t.slice():void e(6)}function Mt(t,r,n){if(2!==arguments.length||mr(t))Sr(t)?t[z].set_(r,n):vr(t)?t.set(r,n):mr(t)?t.add(r):lr(t)?("number"!=typeof r&&(r=parseInt(r,10)),r<0&&e("Invalid index: '"+r+"'"),it(),r>=t.length&&(t.length=r+1),t[r]=n,ot()):e(8);else{it();var i=r;try{for(var o in i)Mt(t,o,i[o])}finally{ot()}}}function zt(t,r,n){if(Sr(t))return t[z].defineProperty_(r,n);e(39)}function Ft(e,t,r,n){return b(r)?function(e,t,r,n){return Rr(e,t).observe_(r,n)}(e,t,r,n):function(e,t,r){return Rr(e).observe_(t,r)}(e,t,r)}function Lt(e){switch(e.length){case 0:return et.trackingDerivation;case 1:return Vr(e[0]);case 2:return Vr(e[0],e[1])}}function $t(e,t){void 0===t&&(t=void 0),it();try{return e.apply(t)}finally{ot()}}function Ht(e){return e[z]}It.bound=U(Tt);var Bt={has:function(e,t){return Ht(e).has_(t)},get:function(e,t){return Ht(e).get_(t)},set:function(e,t,r){var n;return!!d(t)&&(null==(n=Ht(e).set_(t,r,!0))||n)},deleteProperty:function(e,t){var r;return!!d(t)&&(null==(r=Ht(e).delete_(t,!0))||r)},defineProperty:function(e,t,r){var n;return null==(n=Ht(e).defineProperty_(t,r))||n},ownKeys:function(e){return Ht(e).ownKeys_()},preventExtensions:function(t){e(13)}};function Gt(e){return void 0!==e.interceptors_&&e.interceptors_.length>0}function Kt(e,t){var r=e.interceptors_||(e.interceptors_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function qt(t,r){var n=qe();try{for(var i=[].concat(t.interceptors_||[]),o=0,a=i.length;o0}function Yt(e,t){var r=e.changeListeners_||(e.changeListeners_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function Qt(e,t){var r=qe(),n=e.changeListeners_;if(n){for(var i=0,o=(n=n.slice()).length;i0?e.map(this.dehancer):e},r.intercept_=function(e){return Kt(this,e)},r.observe_=function(e,t){return void 0===t&&(t=!1),t&&e({observableKind:"array",object:this.proxy_,debugObjectName:this.atom_.name_,type:"splice",index:0,added:this.values_.slice(),addedCount:this.values_.length,removed:[],removedCount:0}),Yt(this,e)},r.getArrayLength_=function(){return this.atom_.reportObserved(),this.values_.length},r.setArrayLength_=function(t){("number"!=typeof t||t<0)&&e("Out of range: "+t);var r=this.values_.length;if(t!==r)if(t>r){for(var n=new Array(t-r),i=0;i0&&Dr(t+r+1)},r.spliceWithArray_=function(e,t,r){var n=this;this.atom_;var i=this.values_.length;if(void 0===e?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=1===arguments.length?i-e:null==t?0:Math.max(0,Math.min(t,i-e)),void 0===r&&(r=s),Gt(this)){var o=qt(this,{object:this.proxy_,type:"splice",index:e,removedCount:t,added:r});if(!o)return s;t=o.removedCount,r=o.added}if(r=0===r.length?r:r.map((function(e){return n.enhancer_(e,void 0)})),this.legacyMode_){var a=r.length-t;this.updateArrayLength_(i,a)}var u=this.spliceItemsIntoValues_(e,t,r);return 0===t&&0===r.length||this.notifyArraySplice_(e,r,u),this.dehanceValues_(u)},r.spliceItemsIntoValues_=function(e,t,r){var n;if(r.length<1e4)return(n=this.values_).splice.apply(n,[e,t].concat(r));var i=this.values_.slice(e,e+t),o=this.values_.slice(e+t);this.values_.length=e+r.length-t;for(var a=0;a2?r-2:0),i=2;i-1&&(this.splice(r,1),!0)}};function nr(e,t){"function"==typeof Array.prototype[e]&&(rr[e]=t(e))}function ir(e){return function(){var t=this[z];t.atom_.reportObserved();var r=t.dehanceValues_(t.values_);return r[e].apply(r,arguments)}}function or(e){return function(t,r){var n=this,i=this[z];return i.atom_.reportObserved(),i.dehanceValues_(i.values_)[e]((function(e,i){return t.call(r,e,i,n)}))}}function ar(e){return function(){var t=this,r=this[z];r.atom_.reportObserved();var n=r.dehanceValues_(r.values_),i=arguments[0];return arguments[0]=function(e,r,n){return i(e,r,n,t)},n[e].apply(n,arguments)}}nr("concat",ir),nr("flat",ir),nr("includes",ir),nr("indexOf",ir),nr("join",ir),nr("lastIndexOf",ir),nr("slice",ir),nr("toString",ir),nr("toLocaleString",ir),nr("every",or),nr("filter",or),nr("find",or),nr("findIndex",or),nr("flatMap",or),nr("forEach",or),nr("map",or),nr("some",or),nr("reduce",ar),nr("reduceRight",ar);var sr,ur,cr=w("ObservableArrayAdministration",er);function lr(e){return v(e)&&cr(e[z])}var fr={},pr="add";sr=Symbol.iterator,ur=Symbol.toStringTag;var hr,br,dr=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableMap"),this.enhancer_=void 0,this.name_=void 0,this[z]=fr,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=r,this.name_=n,b(Map)||e(18),this.keysAtom_=$("ObservableMap.keys()"),this.data_=new Map,this.hasMap_=new Map,this.merge(t)}var r=t.prototype;return r.has_=function(e){return this.data_.has(e)},r.has=function(e){var t=this;if(!et.trackingDerivation)return this.has_(e);var r=this.hasMap_.get(e);if(!r){var n=r=new Ve(this.has_(e),G,"ObservableMap.key?",!1);this.hasMap_.set(e,n),Pt(n,(function(){return t.hasMap_.delete(e)}))}return r.get()},r.set=function(e,t){var r=this.has_(e);if(Gt(this)){var n=qt(this,{type:r?Zt:pr,object:this,newValue:t,name:e});if(!n)return this;t=n.newValue}return r?this.updateValue_(e,t):this.addValue_(e,t),this},r.delete=function(e){var t=this;if((this.keysAtom_,Gt(this))&&!qt(this,{type:"delete",object:this,name:e}))return!1;if(this.has_(e)){var r=Wt(this),n=r?{observableKind:"map",debugObjectName:this.name_,type:"delete",object:this,oldValue:this.data_.get(e).value_,name:e}:null;return $t((function(){t.keysAtom_.reportChanged(),t.updateHasMapEntry_(e,!1),t.data_.get(e).setNewValue_(void 0),t.data_.delete(e)})),r&&Qt(this,n),!0}return!1},r.updateHasMapEntry_=function(e,t){var r=this.hasMap_.get(e);r&&r.setNewValue_(t)},r.updateValue_=function(e,t){var r=this.data_.get(e);if((t=r.prepareNewValue_(t))!==et.UNCHANGED){var n=Wt(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:Zt,object:this,oldValue:r.value_,name:e,newValue:t}:null;r.setNewValue_(t),n&&Qt(this,i)}},r.addValue_=function(e,t){var r=this;this.keysAtom_,$t((function(){var n=new Ve(t,r.enhancer_,"ObservableMap.key",!1);r.data_.set(e,n),t=n.value_,r.updateHasMapEntry_(e,!0),r.keysAtom_.reportChanged()}));var n=Wt(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:pr,object:this,name:e,newValue:t}:null;n&&Qt(this,i)},r.get=function(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)},r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.keys=function(){return this.keysAtom_.reportObserved(),this.data_.keys()},r.values=function(){var e=this,t=this.keys();return $r({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:e.get(i)}}})},r.entries=function(){var e=this,t=this.keys();return $r({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:[i,e.get(i)]}}})},r[sr]=function(){return this.entries()},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value,o=i[0],a=i[1];e.call(t,a,o,this)}},r.merge=function(t){var r=this;return vr(t)&&(t=new Map(t)),$t((function(){y(t)?function(e){var t=Object.keys(e);if(!P)return t;var r=Object.getOwnPropertySymbols(e);return r.length?[].concat(t,r.filter((function(t){return a.propertyIsEnumerable.call(e,t)}))):t}(t).forEach((function(e){return r.set(e,t[e])})):Array.isArray(t)?t.forEach((function(e){var t=e[0],n=e[1];return r.set(t,n)})):O(t)?(t.constructor!==Map&&e(19,t),t.forEach((function(e,t){return r.set(t,e)}))):null!=t&&e(20,t)})),this},r.clear=function(){var e=this;$t((function(){Ke((function(){for(var t,r=V(e.keys());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.replace=function(t){var r=this;return $t((function(){for(var n,i=function(t){if(O(t)||vr(t))return t;if(Array.isArray(t))return new Map(t);if(y(t)){var r=new Map;for(var n in t)r.set(n,t[n]);return r}return e(21,t)}(t),o=new Map,a=!1,s=V(r.data_.keys());!(n=s()).done;){var u=n.value;if(!i.has(u))if(r.delete(u))a=!0;else{var c=r.data_.get(u);o.set(u,c)}}for(var l,f=V(i.entries());!(l=f()).done;){var p=l.value,h=p[0],b=p[1],d=r.data_.has(h);if(r.set(h,b),r.data_.has(h)){var v=r.data_.get(h);o.set(h,v),d||(a=!0)}}if(!a)if(r.data_.size!==o.size)r.keysAtom_.reportChanged();else for(var g=r.data_.keys(),m=o.keys(),_=g.next(),w=m.next();!_.done;){if(_.value!==w.value){r.keysAtom_.reportChanged();break}_=g.next(),w=m.next()}r.data_=o})),this},r.toString=function(){return"[object ObservableMap]"},r.toJSON=function(){return Array.from(this)},r.observe_=function(e,t){return Yt(this,e)},r.intercept_=function(e){return Kt(this,e)},I(t,[{key:"size",get:function(){return this.keysAtom_.reportObserved(),this.data_.size}},{key:ur,get:function(){return"Map"}}]),t}(),vr=w("ObservableMap",dr);var yr={};hr=Symbol.iterator,br=Symbol.toStringTag;var gr=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableSet"),this.name_=void 0,this[z]=yr,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,b(Set)||e(22),this.atom_=$(this.name_),this.enhancer_=function(e,t){return r(e,t,n)},t&&this.replace(t)}var r=t.prototype;return r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.clear=function(){var e=this;$t((function(){Ke((function(){for(var t,r=V(e.data_.values());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value;e.call(t,i,i,this)}},r.add=function(e){var t=this;if((this.atom_,Gt(this))&&!qt(this,{type:pr,object:this,newValue:e}))return this;if(!this.has(e)){$t((function(){t.data_.add(t.enhancer_(e,void 0)),t.atom_.reportChanged()}));var r=Wt(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:pr,object:this,newValue:e}:null;r&&Qt(this,n)}return this},r.delete=function(e){var t=this;if(Gt(this)&&!qt(this,{type:"delete",object:this,oldValue:e}))return!1;if(this.has(e)){var r=Wt(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:"delete",object:this,oldValue:e}:null;return $t((function(){t.atom_.reportChanged(),t.data_.delete(e)})),r&&Qt(this,n),!0}return!1},r.has=function(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))},r.entries=function(){var e=0,t=Array.from(this.keys()),r=Array.from(this.values());return $r({next:function(){var n=e;return e+=1,nTr){for(var t=Tr;t=0&&r++}e=Lr(e),t=Lr(t);var s="[object Array]"===a;if(!s){if("object"!=typeof e||"object"!=typeof t)return!1;var u=e.constructor,c=t.constructor;if(u!==c&&!(b(u)&&u instanceof u&&b(c)&&c instanceof c)&&"constructor"in e&&"constructor"in t)return!1}if(0===r)return!1;r<0&&(r=-1),i=i||[];for(var l=(n=n||[]).length;l--;)if(n[l]===e)return i[l]===t;if(n.push(e),i.push(t),s){if((l=e.length)!==t.length)return!1;for(;l--;)if(!Fr(e[l],t[l],r-1,n,i))return!1}else{var f,p=Object.keys(e);if(l=p.length,Object.keys(t).length!==l)return!1;for(;l--;)if(!x(t,f=p[l])||!Fr(e[f],t[f],r-1,n,i))return!1}return n.pop(),i.pop(),!0}function Lr(e){return lr(e)?e.slice():O(e)||vr(e)||j(e)||mr(e)?Array.from(e.entries()):e}function $r(e){return e[Symbol.iterator]=Hr,e}function Hr(){return this}["Symbol","Map","Set","Symbol"].forEach((function(t){void 0===r()[t]&&e("MobX requires global '"+t+"' to be available or polyfilled")})),"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:function(e){return console.warn("[mobx.spy] Is a no-op in production builds"),function(){}},extras:{getDebugName:Ur},$mobx:z});var Br;!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(Br||(Br={})); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. @@ -217,7 +217,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ -var Gr=function(e,t){return(Gr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function Kr(e,t){function r(){this.constructor=e}Gr(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var qr=function(){return(qr=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Yr(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function Qr(){for(var e=[],t=0;t";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==En.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeCreation()}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseAboutToDie()}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.fireInternalHook(e)}}),t}(tn);rn.prototype.die=yt(rn.prototype.die);var nn,on,an=1,sn={onError:function(e){throw e}},un=function(e){function t(t,r,n,i,o){var a=e.call(this,t,r,n,i)||this;if(Object.defineProperty(a,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:++an}),Object.defineProperty(a,"identifierAttribute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"unnormalizedIdentifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifierCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"isProtectionEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applyPatches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applySnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_autoUnbox",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"_isRunningAction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_hasSnapshotReaction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_observableInstanceState",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(a,"_childNodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_initialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshotCreated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_snapshotComputed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_snapshotUponDeath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_internalEvents",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),a._snapshotComputed=Pe((function(){return a.getSnapshot()})),a.unbox=a.unbox.bind(a),a._initialSnapshot=o,a.identifierAttribute=t.identifierAttribute,r||(a.identifierCache=new In),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 u=a._childNodes[a.identifierAttribute];u&&(s=u.value)}if("string"!=typeof s&&"number"!=typeof s)throw Hn("Instance identifier '"+a.identifierAttribute+"' for type '"+a.type.name+"' must be a string or a number");a.identifier=to(s),a.unnormalizedIdentifier=s}return r?r.root.identifierCache.addNodeToCache(a):a.identifierCache.addNodeToCache(a),a}return Kr(t,e),Object.defineProperty(t.prototype,"applyPatches",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)}}),Object.defineProperty(t.prototype,"createObservableInstanceIfNeeded",{enumerable:!1,configurable:!0,writable:!0,value:function(){0===this._observableInstanceState&&this.createObservableInstance()}}),Object.defineProperty(t.prototype,"createObservableInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e,t;this._observableInstanceState=1;for(var r=[],n=this.parent;n&&0===n._observableInstanceState;)r.unshift(n),n=n.parent;try{for(var i=Wr(r),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=En.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,this._snapshotComputed.trackAndCompute(),this.isRoot&&this._addSnapshotReaction(),this._childNodes=Ln,this.state=En.CREATED,this.fireHook(Br.afterCreate),this.finalizeCreation()}}),Object.defineProperty(t.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearParent",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.parent){this.fireHook(Br.beforeDetach);var e=this.state;this.state=En.DETACHING;var t=this.root,r=t.environment,n=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=r,this.identifierCache=n}finally{this.state=e}}}}),Object.defineProperty(t.prototype,"setParent",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e!==this.parent,n=t!==this.subpath;(r||n)&&(r?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(Br.afterAttach)):n&&this.baseSetParent(this.parent,t))}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;this.fireInternalHook(e);var r=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof r&&(mt?mt((function(){r.apply(t.storedValue)})):r.apply(this.storedValue))}}),Object.defineProperty(t.prototype,"snapshot",{get:function(){return this._snapshotComputed.get()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath}}),Object.defineProperty(t.prototype,"_getActualSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.type.getSnapshot(this)}}),Object.defineProperty(t.prototype,"_getCachedInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this._cachedInitialSnapshotCreated){var e=this.type,t=this._childNodes,r=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,r),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot}}),Object.defineProperty(t.prototype,"isRunningAction",{enumerable:!1,configurable:!0,writable:!0,value:function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()}}),Object.defineProperty(t.prototype,"assertAlive",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t;if(!this.isAlive){var r=this._getAssertAliveError(e);t=r,console.warn(new Error("[mobx-state-tree] "+t))}}}),Object.defineProperty(t.prototype,"_getAssertAliveError",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",r=e.subpath&&ii(e.subpath)||"",n=e.actionContext||bn;n&&"action"!==n.type&&n.parentActionEvent&&(n=n.parentActionEvent);var i="";n&&null!=n.name&&(i=(n&&n.context&&Nn(n.context).path||t)+"."+n.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: '"+r+"', Action: '"+i+"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value: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}}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.assertAlive(Ln),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):Mn(this._childNodes)}finally{this._autoUnbox=!0}}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.type.getChildType(e)}}),Object.defineProperty(t.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"assertWritable",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw Hn("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.type.removeChild(this,e)}}),Object.defineProperty(t.prototype,"unbox",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e}}),Object.defineProperty(t.prototype,"toString",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this.baseFinalizeCreation((function(){var t,r;try{for(var n=Wr(e.getChildren()),i=n.next();!i.done;i=n.next()){i.value.finalizeCreation()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}e.fireInternalHook(Br.afterCreationFinalization)}))}}),Object.defineProperty(t.prototype,"detach",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this.isAlive)throw Hn("Error while detaching, node is not alive.");this.clearParent()}}),Object.defineProperty(t.prototype,"preboot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this._applyPatches=mn(this.storedValue,"@APPLY_PATCHES",(function(t){t.forEach((function(t){if(t.path){var r=function(e){var t=e.split("/").map(oi);if(!(""===e||"."===e||".."===e||ti(e,"/")||ti(e,"./")||ti(e,"../")))throw Hn("a json path must be either rooted, empty or relative, but got '"+e+"'");""===t[0]&&t.shift();return t}(t.path);Un(e,r.slice(0,-1)).applyPatchLocally(r[r.length-1],t)}else e.type.applySnapshot(e,t.value)}))})),this._applySnapshot=mn(this.storedValue,"@APPLY_SNAPSHOT",(function(t){if(t!==e.snapshot)return e.type.applySnapshot(e,t)})),Xn(this.storedValue,"$treenode",this),Xn(this.storedValue,"toJSON",Rn)}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==En.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){0!==this._observableInstanceState&&(this.getChildren().forEach((function(e){e.aboutToDie()})),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.getChildren().forEach((function(e){e.finalizeDeath()})),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"onSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)}}),Object.defineProperty(t.prototype,"emitSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this._internalEventsEmit("snapshot",e)}}),Object.defineProperty(t.prototype,"onPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._internalEventsRegister("patch",e)}}),Object.defineProperty(t.prototype,"emitPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._internalEventsHasSubscribers("patch")){var r=Yr(function(e){if(!("oldValue"in e))throw Hn("Patches without `oldValue` field cannot be inversed");return[ri(e),ni(e)]}(function(e){for(var t=[],r=1;r=0&&this.middlewares.splice(t,1)}}}),Object.defineProperty(t.prototype,"addMiddleWare",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;void 0===t&&(t=!0);var n={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(n):this.middlewares=[n],function(){r.removeMiddleware(n)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)}}),Object.defineProperty(t.prototype,"_addSnapshotReaction",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;if(!this._hasSnapshotReaction){var t=jt((function(){return e.snapshot}),(function(t){return e.emitSnapshot(t)}),sn);this.addDisposer(t),this._hasSnapshotReaction=!0}}}),Object.defineProperty(t.prototype,"_internalEventsHasSubscribers",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)}}),Object.defineProperty(t.prototype,"_internalEventsRegister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){return void 0===r&&(r=!1),this._internalEvents||(this._internalEvents=new Jn),this._internalEvents.register(e,t,r)}}),Object.defineProperty(t.prototype,"_internalEventsHas",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsUnregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsEmit",{enumerable:!1,configurable:!0,writable:!0,value:function(e){for(var t,r=[],n=1;n0},enumerable:!1,configurable:!0})}();var bn,dn=1;function vn(){return dn++}function yn(e,t){var r=Nn(e.context);"action"===e.type&&r.assertAlive({actionContext:e});var n=r._isRunningAction;r._isRunningAction=!0;var i=bn;bn=e;try{return function(e,t,r){var n=new _n(e,r);if(n.isEmpty)return yt(r).apply(null,t.args);var i=null;function o(e){var t=n.getNextMiddleware(),a=t&&t.handler;if(!a)return yt(r).apply(null,e.args);if(!t.includeHooks&&Br[e.name])return o(e);function s(e,t){i=o(e),t&&(i=t(i))}function u(e){i=e}return a(e,s,u),i}return o(t)}(r,e,t)}finally{bn=i,r._isRunningAction=n}}function gn(e){if(e)return"action"===e.type?e:e.parentActionEvent}function mn(e,t,r){var n=function(){var n=vn(),i=bn,o=gn(i);return yn({type:"action",name:t,id:n,args:ei(arguments),context:e,tree:en(e),rootId:i?i.rootId:n,parentId:i?i.id:0,allParentIds:i?Qr(i.allParentIds,[i.id]):[],parentEvent:i,parentActionEvent:o},r)};return n._isMSTAction=!0,n}var _n=function(){function e(e,t){Object.defineProperty(this,"arrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"inArrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:[]}),t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);for(var r=e;r;)r.middlewares&&this.middlewares.push(r.middlewares),r=r.parent}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return this.middlewares.length<=0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"getNextMiddleware",{enumerable:!1,configurable:!0,writable:!0,value: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 wn(e){return"function"==typeof e?"":Dn(e)?"<"+e+">":"`"+function(e){try{return JSON.stringify(e)}catch(e){return""}}(e)+"`"}function On(e){var t=e.value,r=e.context[e.context.length-1].type,n=e.context.map((function(e){return e.path})).filter((function(e){return e.length>0})).join("/"),i=n.length>0?'at path "/'+n+'" ':"",o=Dn(t)?"value of type "+Nn(t).type.name+":":Qn(t)?"value":"snapshot",a=r&&Dn(t)&&r.is(Nn(t).snapshot);return""+i+o+" "+wn(t)+" is not assignable "+(r?"to type: `"+r.name+"`":"")+(e.message?" ("+e.message+")":"")+(r?function(e){return hn(e)&&(e.flags&(on.String|on.Number|on.Integer|on.Boolean|on.Date))>0}(r)||Qn(t)?".":", expected an instance of `"+r.name+"` or a snapshot like `"+r.describe()+"` instead."+(a?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".")}function jn(e,t,r){return e.concat([{path:t,type:r}])}function Pn(){return zn}function Sn(e,t,r){return[{context:e,value:t,message:r}]}function An(e){return e.reduce((function(e,t){return e.concat(t)}),[])}function xn(e,t){"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK&&function(e,t){var r=e.validate(t,[{path:"",type:e}]);if(r.length>0)throw Hn(function(e,t,r){if(0===r.length)return;return"Error while converting "+(n=wn(t),(n.length<280?n:n.substring(0,272)+"......"+n.substring(n.length-8))+" to `")+e.name+"`:\n\n "+r.map(On).join("\n ");var n}(e,t,r))}(e,t)}var En,Tn=0,In=function(){function t(){Object.defineProperty(this,"cacheId",{enumerable:!0,configurable:!0,writable:!0,value:Tn++}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:we.map()}),Object.defineProperty(this,"lastCacheModificationPerId",{enumerable:!0,configurable:!0,writable:!0,value:we.map()})}return Object.defineProperty(t.prototype,"updateLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)}}),Object.defineProperty(t.prototype,"getLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t}}),Object.defineProperty(t.prototype,"addNodeToCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var r=e.identifier;this.cache.has(r)||this.cache.set(r,we.array([],$n));var n=this.cache.get(r);if(-1!==n.indexOf(e))throw Hn("Already registered");n.push(e),t&&this.updateLastCacheModificationPerId(r)}}}),Object.defineProperty(t.prototype,"mergeCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;Ut(e.identifierCache.cache).forEach((function(e){return e.forEach((function(e){t.addNodeToCache(e)}))}))}}),Object.defineProperty(t.prototype,"notifyDied",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.identifierAttribute){var t=e.identifier,r=this.cache.get(t);r&&(r.remove(e),r.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}}}),Object.defineProperty(t.prototype,"splitCache",{enumerable:!1,configurable:!0,writable:!0,value:function(r){var n,i=this,o=new t,a=r.path;return(n=this.cache,Sr(n)?Rt(n).map((function(e){return[e,n[e]]})):vr(n)?Rt(n).map((function(e){return[e,n.get(e)]})):mr(n)?Array.from(n.entries()):lr(n)?n.map((function(e,t){return[t,e]})):void e(7)).forEach((function(e){for(var t=Yr(e,2),r=t[0],n=t[1],s=!1,u=n.length-1;u>=0;u--)0===n[u].path.indexOf(a)&&(o.addNodeToCache(n[u],!1),n.splice(u,1),s=!0);s&&i.updateLastCacheModificationPerId(r)})),o}}),Object.defineProperty(t.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);return!!r&&r.some((function(t){return e.isAssignableFrom(t.type)}))}}),Object.defineProperty(t.prototype,"resolve",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);if(!r)return null;var n=r.filter((function(t){return e.isAssignableFrom(t.type)}));switch(n.length){case 0:return null;case 1:return n[0];default:throw Hn("Cannot resolve a reference to type '"+e.name+"' with id: '"+t+"' unambigously, there are multiple candidates: "+n.map((function(e){return e.path})).join(", "))}}}),t}();function Cn(e,t,r,n,i){var o=Vn(i);if(o){if(o.parent)throw Hn("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:"")+"/"+r+"', but it lives already at '"+o.path+"'");return t&&o.setParent(t,r),o}return new un(e,t,r,n,i)}function kn(e,t,r,n,i){return new rn(e,t,r,n,i)}function Dn(e){return!(!e||!e.$treenode)}function Nn(e){if(!Dn(e))throw Hn("Value "+e+" is no MST Node");return e.$treenode}function Vn(e){return e&&e.$treenode||null}function Rn(){return Nn(this).snapshot}function Un(e,t,r){void 0===r&&(r=!0);for(var n=e,i=0;i0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"register",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return void 0===t&&(t=!1),t?this.handlers.unshift(e):this.handlers.push(e),function(){r.unregister(e)}}}),Object.defineProperty(e.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.handlers.indexOf(e)>=0}}),Object.defineProperty(e.prototype,"unregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}),Object.defineProperty(e.prototype,"clear",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.handlers.length=0}}),Object.defineProperty(e.prototype,"emit",{enumerable:!1,configurable:!0,writable:!0,value:function(){for(var e=[],t=0;t0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._determineIdentifierMode(),Cn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"_determineIdentifierMode",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.identifierMode===ui.UNKNOWN){var e=[];if(li(this._subType,e)){var t=void 0;e.forEach((function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw Hn("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=ui.YES,this.mapIdentifierAttribute=t):this.identifierMode=ui.NO}}}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t={});var r=e.type._subType,n={};return Object.keys(t).forEach((function(i){n[i]=r.instantiate(e,i,void 0,t[i])})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return new fi(e)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Dt(t,e.unbox),e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=mn(t,e,n);Xn(t,e,i)}))})),Nt(t,this.willChange),zt(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"Map"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Ut(e.storedValue)}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e.storedValue.get(""+t);if(!r)throw Hn("Not a child "+t);return r}}),Object.defineProperty(t.prototype,"willChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Nn(e.object),r=e.name;t.assertWritable({subpath:r});var n=t.type,i=n._subType;switch(e.type){case"update":var o=e.newValue;if(o===e.object.get(r))return null;xn(i,o),e.newValue=i.reconcile(t.getChildNode(r),e.newValue,t,r),n.processIdentifier(r,e.newValue);break;case"add":xn(i,e.newValue),e.newValue=i.instantiate(t,r,void 0,e.newValue),n.processIdentifier(r,e.newValue)}return e}}),Object.defineProperty(t.prototype,"processIdentifier",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.identifierMode===ui.YES&&t instanceof un){var r=t.identifier;if(r!==e)throw Hn("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '"+r+"', but expected: '"+e+"'")}}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return e.getChildren().forEach((function(e){t[e.subpath]=e.snapshot})),t}}),Object.defineProperty(t.prototype,"processInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return Object.keys(e).forEach((function(r){t[r]=e[r].getSnapshot()})),t}}),Object.defineProperty(t.prototype,"didChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Nn(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:ii(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:ii(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":var r=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:ii(e.name),oldValue:r},t)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=e.storedValue;switch(r.op){case"add":case"replace":n.set(t,r.value);break;case"remove":n.delete(t)}}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){xn(this,t);var r=e.storedValue,n={};if(Array.from(r.keys()).forEach((function(e){n[e]=!1})),t)for(var i in t)r.set(i,t[i]),n[""+i]=!0;Object.keys(n).forEach((function(e){!1===n[e]&&r.delete(e)}))}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return Wn(e)?An(Object.keys(e).map((function(n){return r._subType.validate(e[n],jn(t,n,r._subType))}))):Sn(t,e,"Value is not a plain object")}}),Object.defineProperty(t.prototype,"getDefaultSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return Ln}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){e.storedValue.delete(t)}}),t}(fn);pi.prototype.applySnapshot=yt(pi.prototype.applySnapshot);var hi=function(e){function t(t,r,n){void 0===n&&(n=[]);var i=e.call(this,t)||this;return Object.defineProperty(i,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Array}),Object.defineProperty(i,"hookInitializers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),i.hookInitializers=n,i}return Kr(t,e),Object.defineProperty(t.prototype,"hooks",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var r=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return Cn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t=[]);var r=e.type._subType,n={};return t.forEach((function(t,i){var o=""+i;n[o]=r.instantiate(e,o,void 0,t)})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return we.array(Mn(e),$n)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Rr(t).dehancer=e.unbox,e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=mn(t,e,n);Xn(t,e,i)}))})),Nt(t,this.willChange),zt(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType.describe()+"[]"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.slice()}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=Number(t);if(r=0;r--)t.emitPatch({op:"remove",path:""+(e.index+r),oldValue:e.removed[r].snapshot},t);for(r=0;r0)return r;var n=Dn(e)?Nn(e).snapshot:e;return this._predicate(n)?Pn():Sn(t,e,this._message(e))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(ln);var Di=function(e){function t(t,r,n){var i=e.call(this,t)||this;return Object.defineProperty(i,"_types",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"_dispatcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"_eager",{enumerable:!0,configurable:!0,writable:!0,value:!0}),n=qr({eager:!0,dispatcher:void 0},n),i._dispatcher=n.dispatcher,n.eager||(i._eager=!1),i}return Kr(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){var e=on.Union;return this._types.forEach((function(t){e|=t.flags})),e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._types.some((function(t){return t.isAssignableFrom(e)}))}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"("+this._types.map((function(e){return e.describe()})).join(" | ")+")"}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(n,void 0);if(!i)throw Hn("No matching type for union "+this.describe());return i.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(t,e.type);if(!i)throw Hn("No matching type for union "+this.describe());return i.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"determineType",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter((function(e){return e!==t})).find((function(t){return t.is(e)})):this._types.find((function(t){return t.is(e)}))}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);for(var r=[],n=0,i=0;i=0){var i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,r,i)}return this._subtype.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),r,n)}}),Object.defineProperty(t.prototype,"getDefaultInstanceOrSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&xn(this,e),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this.optionalValues.indexOf(e)>=0?Pn():this._subtype.validate(e,t)}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._subtype.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(ln);function Ri(e,t,r){return function(e,t){if("function"!=typeof t&&Dn(t))throw Hn("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}(0,t),new Vi(e,t,r||Ui)}var Ui=[void 0],Mi=Ri(xi,void 0),Fi=Ri(Ai,null);function zi(e){return Ni(e,Mi)}var Li=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"_definition",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n}return Kr(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return(this._subType?this._subType.flags:0)|on.Late},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSubType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(!this._subType){var t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw Hn("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e?e.name:""}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.getSubType(!1);return r?r.validate(e,t):Pn()}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e||"cannotDetermine"}}),t}(ln);var $i=function(e){function t(t){var r=e.call(this,t?"frozen("+t.name+")":"frozen")||this;return Object.defineProperty(r,"subType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Frozen}),r}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return""}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return kn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return function(e){return"function"!=typeof e}(e)?this.subType?this.subType.validate(e,t):Pn():Sn(t,e,"Value is not serializable and cannot be frozen")}}),t}(pn),Hi=new $i;var Bi=function(){function e(e,t){if(Object.defineProperty(this,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolvedReference",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),ro(e))this.identifier=e;else{if(!Dn(e))throw Hn("Can only store references to tree nodes or identifiers, got: '"+e+"'");var r=Nn(e);if(!r.identifierAttribute)throw Hn("Can only store references with a defined identifier attribute.");var n=r.unnormalizedIdentifier;if(null==n)throw Hn("Can only store references to tree nodes with a defined identifier.");this.identifier=n}}return Object.defineProperty(e.prototype,"updateResolvedReference",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=to(this.identifier),r=e.root,n=r.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==n){var i=this.targetType,o=r.identifierCache.resolve(i,t);if(!o)throw new Gi("[mobx-state-tree] Failed to resolve reference '"+this.identifier+"' to type '"+this.targetType.name+"' (from node: "+e.path+")");this.resolvedReference={node:o,lastCacheModification:n}}}}),Object.defineProperty(e.prototype,"resolvedValue",{get:function(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value},enumerable:!1,configurable:!0}),e}(),Gi=function(e){function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return Kr(t,e),t}(Error),Ki=function(e){function t(t,r){var n=e.call(this,"reference("+t.name+")")||this;return Object.defineProperty(n,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"onInvalidated",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Reference}),n}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.targetType.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return ro(e)?Pn():Sn(t,e,"Value is not a valid identifier, which is a string or a number")}}),Object.defineProperty(t.prototype,"fireInvalidated",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=t.parent;if(i&&i.isAlive){var o=i.storedValue;o&&this.onInvalidated({cause:e,parent:o,invalidTarget:n?n.storedValue:void 0,invalidId:r,replaceRef:function(e){Zr(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef:function(){!function(e){return hn(e)&&(e.flags&on.Object)>0}(i.type)?Zr(t.root.storedValue,{op:"remove",path:t.path}):this.replaceRef(void 0)}})}}}),Object.defineProperty(t.prototype,"addTargetNodeWatcher",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this,n=this.getValue(e);if(n){var i=Nn(n),o=function(n,o){var a=function(e){switch(e){case Br.beforeDestroy:return"destroy";case Br.beforeDetach:return"detach";default:return}}(o);a&&r.fireInvalidated(a,e,t,i)},a=i.registerHook(Br.beforeDetach,o),s=i.registerHook(Br.beforeDestroy,o);return function(){a(),s()}}}}),Object.defineProperty(t.prototype,"watchTargetNodeForInvalidations",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=this;if(this.onInvalidated){var i;e.registerHook(Br.beforeDestroy,(function(){i&&i()}));var o=function(o){i&&i();var a=e.parent,s=a&&a.storedValue;if(a&&a.isAlive&&s){(r?!!r.get(t,s):e.root.identifierCache.has(n.targetType,to(t)))?i=n.addTargetNodeWatcher(e,t):o||n.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===En.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(Br.afterCreationFinalization,(function(){e.parent&&e.parent.createObservableInstanceIfNeeded()})),e.registerHook(Br.afterAttach,(function(){o(!1)})))}}}),t}(pn),qi=function(e){function t(t,r){return e.call(this,t,r)||this}return Kr(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return e.storedValue.resolvedValue}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.identifier}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(n)?Nn(n).identifier:n,o=new Bi(n,this.targetType),a=kn(this,e,t,r,o);return o.node=a,this.watchTargetNodeForInvalidations(a,i,void 0),a}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!e.isDetaching&&e.type===this){var i=Dn(t),o=e.storedValue;if(!i&&o.identifier===t||i&&o.resolvedValue===t)return e.setParent(r,n),e}var a=this.instantiate(r,n,void 0,t);return e.die(),a}}),t}(Ki),Wi=function(e){function t(t,r,n){var i=e.call(this,t,n)||this;return Object.defineProperty(i,"options",{enumerable:!0,configurable:!0,writable:!0,value:r}),i}return Kr(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(n)?this.options.set(n,e?e.storedValue:null):n,o=kn(this,e,t,r,i);return this.watchTargetNodeForInvalidations(o,i,this.options),o}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===i)return e.setParent(r,n),e;var o=this.instantiate(r,n,void 0,i);return e.die(),o}}),t}(Ki);function Yi(e,t){var r=t||void 0,n=t?t.onInvalidated:void 0;return r&&(r.get||r.set)?new Wi(e,{get:r.get,set:r.set},n):new qi(e,n)}var Qi=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"validType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Identifier}),n}return Kr(t,e),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!(e&&e.type instanceof _i))throw Hn("Identifier types can only be instantiated as direct child of a model type");return kn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(e.storedValue!==t)throw Hn("Tried to change identifier from '"+e.storedValue+"' to '"+t+"'. Changing identifiers is not allowed.");return e.setParent(r,n),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return typeof e!==this.validType?Sn(t,e,"Value is not a valid "+this.describe()+", expected a "+this.validType):Pn()}}),t}(pn),Xi=function(e){function t(){var t=e.call(this,"identifier","string")||this;return Object.defineProperty(t,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Identifier}),t}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifier"}}),t}(Qi),Zi=function(e){function t(){return e.call(this,"identifierNumber","number")||this}return Kr(t,e),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifierNumber"}}),t}(Qi),Ji=new Xi,eo=new Zi;function to(e){return""+e}function ro(e){return"string"==typeof e||"number"==typeof e}var no,io=function(e){function t(t){var r=e.call(this,t.name)||this;return Object.defineProperty(r,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Custom}),r}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.options.isTargetType(e))return Pn();var r=this.options.getValidationMessage(e);return r?Sn(t,e,"Invalid value for type '"+this.name+"': "+r):Pn()}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.options.toSnapshot(e.storedValue)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return kn(this,e,t,r,this.options.isTargetType(n)?n:this.options.fromSnapshot(n,e&&e.root.environment))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=!this.options.isTargetType(t);if(!e.isDetaching&&(e.type===this&&(i?t===e.snapshot:t===e.storedValue)))return e.setParent(r,n),e;var o=i?this.options.fromSnapshot(t,r.root.environment):t,a=this.instantiate(r,n,void 0,o);return e.die(),a}}),t}(pn),oo={enumeration:function(e,t){var r="string"==typeof e?t:e,n=Ni.apply(void 0,Qr(r.map((function(e){return Ci(""+e)}))));return"string"==typeof e&&(n.name=e),n},model:function(){for(var e=[],t=0;t",e)},array:function(e){return new hi(e.name+"[]",e)},frozen:function(e){return 0===arguments.length?Hi:hn(e)?new $i(e):Ri(Hi,e)},identifier:Ji,identifierNumber:eo,late:function(e,t){var r="string"==typeof e?e:"late("+e.toString()+")";return new Li(r,"string"==typeof e?t:e)},undefined:xi,null:Ai,snapshotProcessor:function(e,t,r){return new si(e,t,r)}},ao=new Uint8Array(16);function so(){if(!no&&!(no="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return no(ao)}var uo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function co(e){return"string"==typeof e&&uo.test(e)}for(var lo=[],fo=0;fo<256;++fo)lo.push((fo+256).toString(16).substr(1));function po(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(lo[e[t+0]]+lo[e[t+1]]+lo[e[t+2]]+lo[e[t+3]]+"-"+lo[e[t+4]]+lo[e[t+5]]+"-"+lo[e[t+6]]+lo[e[t+7]]+"-"+lo[e[t+8]]+lo[e[t+9]]+"-"+lo[e[t+10]]+lo[e[t+11]]+lo[e[t+12]]+lo[e[t+13]]+lo[e[t+14]]+lo[e[t+15]]).toLowerCase();if(!co(r))throw TypeError("Stringified UUID is invalid");return r}function ho(e,t,r){var n=(e=e||{}).random||(e.rng||so)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return po(n)}function bo(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function vo(e,t){return e<>>32-t}var yo=function(e,t,r){function n(e,n,i,o){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}(n)),16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var a=new Uint8Array(16+e.length);if(a.set(n),a.set(e,n.length),(a=r(a))[6]=15&a[6]|t,a[8]=63&a[8]|128,i){o=o||0;for(var s=0;s<16;++s)i[o+s]=a[s];return i}return po(a)}try{n.name=e}catch(e){}return n.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",n.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",n}("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i>>0;m=g,g=y,y=vo(v,30)>>>0,v=d,d=O}r[0]=r[0]+d>>>0,r[1]=r[1]+v>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+g>>>0,r[4]=r[4]+m>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]})); +var Gr=function(e,t){return(Gr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function Kr(e,t){function r(){this.constructor=e}Gr(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var qr=function(){return(qr=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Yr(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function Qr(){for(var e=[],t=0;t";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==En.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeCreation()}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseAboutToDie()}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.fireInternalHook(e)}}),t}(tn);rn.prototype.die=yt(rn.prototype.die);var nn,on,an=1,sn={onError:function(e){throw e}},un=function(e){function t(t,r,n,i,o){var a=e.call(this,t,r,n,i)||this;if(Object.defineProperty(a,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:++an}),Object.defineProperty(a,"identifierAttribute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"unnormalizedIdentifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifierCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"isProtectionEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applyPatches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applySnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_autoUnbox",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"_isRunningAction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_hasSnapshotReaction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_observableInstanceState",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(a,"_childNodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_initialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshotCreated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_snapshotComputed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_snapshotUponDeath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_internalEvents",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),a._snapshotComputed=Pe((function(){return a.getSnapshot()})),a.unbox=a.unbox.bind(a),a._initialSnapshot=o,a.identifierAttribute=t.identifierAttribute,r||(a.identifierCache=new In),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 u=a._childNodes[a.identifierAttribute];u&&(s=u.value)}if("string"!=typeof s&&"number"!=typeof s)throw Hn("Instance identifier '"+a.identifierAttribute+"' for type '"+a.type.name+"' must be a string or a number");a.identifier=to(s),a.unnormalizedIdentifier=s}return r?r.root.identifierCache.addNodeToCache(a):a.identifierCache.addNodeToCache(a),a}return Kr(t,e),Object.defineProperty(t.prototype,"applyPatches",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)}}),Object.defineProperty(t.prototype,"createObservableInstanceIfNeeded",{enumerable:!1,configurable:!0,writable:!0,value:function(){0===this._observableInstanceState&&this.createObservableInstance()}}),Object.defineProperty(t.prototype,"createObservableInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e,t;this._observableInstanceState=1;for(var r=[],n=this.parent;n&&0===n._observableInstanceState;)r.unshift(n),n=n.parent;try{for(var i=Wr(r),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=En.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,this._snapshotComputed.trackAndCompute(),this.isRoot&&this._addSnapshotReaction(),this._childNodes=Ln,this.state=En.CREATED,this.fireHook(Br.afterCreate),this.finalizeCreation()}}),Object.defineProperty(t.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearParent",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.parent){this.fireHook(Br.beforeDetach);var e=this.state;this.state=En.DETACHING;var t=this.root,r=t.environment,n=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=r,this.identifierCache=n}finally{this.state=e}}}}),Object.defineProperty(t.prototype,"setParent",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e!==this.parent,n=t!==this.subpath;(r||n)&&(r?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(Br.afterAttach)):n&&this.baseSetParent(this.parent,t))}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;this.fireInternalHook(e);var r=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof r&&(mt?mt((function(){r.apply(t.storedValue)})):r.apply(this.storedValue))}}),Object.defineProperty(t.prototype,"snapshot",{get:function(){return this._snapshotComputed.get()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath}}),Object.defineProperty(t.prototype,"_getActualSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.type.getSnapshot(this)}}),Object.defineProperty(t.prototype,"_getCachedInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this._cachedInitialSnapshotCreated){var e=this.type,t=this._childNodes,r=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,r),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot}}),Object.defineProperty(t.prototype,"isRunningAction",{enumerable:!1,configurable:!0,writable:!0,value:function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()}}),Object.defineProperty(t.prototype,"assertAlive",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t;if(!this.isAlive){var r=this._getAssertAliveError(e);t=r,console.warn(new Error("[mobx-state-tree] "+t))}}}),Object.defineProperty(t.prototype,"_getAssertAliveError",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",r=e.subpath&&ii(e.subpath)||"",n=e.actionContext||bn;n&&"action"!==n.type&&n.parentActionEvent&&(n=n.parentActionEvent);var i="";n&&null!=n.name&&(i=(n&&n.context&&Nn(n.context).path||t)+"."+n.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: '"+r+"', Action: '"+i+"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value: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}}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.assertAlive(Ln),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):Mn(this._childNodes)}finally{this._autoUnbox=!0}}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.type.getChildType(e)}}),Object.defineProperty(t.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"assertWritable",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw Hn("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.type.removeChild(this,e)}}),Object.defineProperty(t.prototype,"unbox",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e}}),Object.defineProperty(t.prototype,"toString",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this.baseFinalizeCreation((function(){var t,r;try{for(var n=Wr(e.getChildren()),i=n.next();!i.done;i=n.next()){i.value.finalizeCreation()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}e.fireInternalHook(Br.afterCreationFinalization)}))}}),Object.defineProperty(t.prototype,"detach",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this.isAlive)throw Hn("Error while detaching, node is not alive.");this.clearParent()}}),Object.defineProperty(t.prototype,"preboot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this._applyPatches=mn(this.storedValue,"@APPLY_PATCHES",(function(t){t.forEach((function(t){if(t.path){var r=function(e){var t=e.split("/").map(oi);if(!(""===e||"."===e||".."===e||ti(e,"/")||ti(e,"./")||ti(e,"../")))throw Hn("a json path must be either rooted, empty or relative, but got '"+e+"'");""===t[0]&&t.shift();return t}(t.path);Un(e,r.slice(0,-1)).applyPatchLocally(r[r.length-1],t)}else e.type.applySnapshot(e,t.value)}))})),this._applySnapshot=mn(this.storedValue,"@APPLY_SNAPSHOT",(function(t){if(t!==e.snapshot)return e.type.applySnapshot(e,t)})),Xn(this.storedValue,"$treenode",this),Xn(this.storedValue,"toJSON",Rn)}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==En.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){0!==this._observableInstanceState&&(this.getChildren().forEach((function(e){e.aboutToDie()})),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.getChildren().forEach((function(e){e.finalizeDeath()})),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"onSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)}}),Object.defineProperty(t.prototype,"emitSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this._internalEventsEmit("snapshot",e)}}),Object.defineProperty(t.prototype,"onPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._internalEventsRegister("patch",e)}}),Object.defineProperty(t.prototype,"emitPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._internalEventsHasSubscribers("patch")){var r=Yr(function(e){if(!("oldValue"in e))throw Hn("Patches without `oldValue` field cannot be inversed");return[ri(e),ni(e)]}(function(e){for(var t=[],r=1;r=0&&this.middlewares.splice(t,1)}}}),Object.defineProperty(t.prototype,"addMiddleWare",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;void 0===t&&(t=!0);var n={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(n):this.middlewares=[n],function(){r.removeMiddleware(n)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)}}),Object.defineProperty(t.prototype,"_addSnapshotReaction",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;if(!this._hasSnapshotReaction){var t=jt((function(){return e.snapshot}),(function(t){return e.emitSnapshot(t)}),sn);this.addDisposer(t),this._hasSnapshotReaction=!0}}}),Object.defineProperty(t.prototype,"_internalEventsHasSubscribers",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)}}),Object.defineProperty(t.prototype,"_internalEventsRegister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){return void 0===r&&(r=!1),this._internalEvents||(this._internalEvents=new Jn),this._internalEvents.register(e,t,r)}}),Object.defineProperty(t.prototype,"_internalEventsHas",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsUnregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsEmit",{enumerable:!1,configurable:!0,writable:!0,value:function(e){for(var t,r=[],n=1;n0},enumerable:!1,configurable:!0})}();var bn,dn=1;function vn(){return dn++}function yn(e,t){var r=Nn(e.context);"action"===e.type&&r.assertAlive({actionContext:e});var n=r._isRunningAction;r._isRunningAction=!0;var i=bn;bn=e;try{return function(e,t,r){var n=new _n(e,r);if(n.isEmpty)return yt(r).apply(null,t.args);var i=null;function o(e){var t=n.getNextMiddleware(),a=t&&t.handler;if(!a)return yt(r).apply(null,e.args);if(!t.includeHooks&&Br[e.name])return o(e);function s(e,t){i=o(e),t&&(i=t(i))}function u(e){i=e}return a(e,s,u),i}return o(t)}(r,e,t)}finally{bn=i,r._isRunningAction=n}}function gn(e){if(e)return"action"===e.type?e:e.parentActionEvent}function mn(e,t,r){var n=function(){var n=vn(),i=bn,o=gn(i);return yn({type:"action",name:t,id:n,args:ei(arguments),context:e,tree:en(e),rootId:i?i.rootId:n,parentId:i?i.id:0,allParentIds:i?Qr(i.allParentIds,[i.id]):[],parentEvent:i,parentActionEvent:o},r)};return n._isMSTAction=!0,n}var _n=function(){function e(e,t){Object.defineProperty(this,"arrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"inArrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:[]}),t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);for(var r=e;r;)r.middlewares&&this.middlewares.push(r.middlewares),r=r.parent}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return this.middlewares.length<=0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"getNextMiddleware",{enumerable:!1,configurable:!0,writable:!0,value: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 wn(e){return"function"==typeof e?"":Dn(e)?"<"+e+">":"`"+function(e){try{return JSON.stringify(e)}catch(e){return""}}(e)+"`"}function On(e){var t=e.value,r=e.context[e.context.length-1].type,n=e.context.map((function(e){return e.path})).filter((function(e){return e.length>0})).join("/"),i=n.length>0?'at path "/'+n+'" ':"",o=Dn(t)?"value of type "+Nn(t).type.name+":":Qn(t)?"value":"snapshot",a=r&&Dn(t)&&r.is(Nn(t).snapshot);return""+i+o+" "+wn(t)+" is not assignable "+(r?"to type: `"+r.name+"`":"")+(e.message?" ("+e.message+")":"")+(r?function(e){return hn(e)&&(e.flags&(on.String|on.Number|on.Integer|on.Boolean|on.Date))>0}(r)||Qn(t)?".":", expected an instance of `"+r.name+"` or a snapshot like `"+r.describe()+"` instead."+(a?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".")}function jn(e,t,r){return e.concat([{path:t,type:r}])}function Pn(){return Fn}function Sn(e,t,r){return[{context:e,value:t,message:r}]}function An(e){return e.reduce((function(e,t){return e.concat(t)}),[])}function xn(e,t){"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK&&function(e,t){var r=e.validate(t,[{path:"",type:e}]);if(r.length>0)throw Hn(function(e,t,r){if(0===r.length)return;return"Error while converting "+(n=wn(t),(n.length<280?n:n.substring(0,272)+"......"+n.substring(n.length-8))+" to `")+e.name+"`:\n\n "+r.map(On).join("\n ");var n}(e,t,r))}(e,t)}var En,Tn=0,In=function(){function t(){Object.defineProperty(this,"cacheId",{enumerable:!0,configurable:!0,writable:!0,value:Tn++}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:we.map()}),Object.defineProperty(this,"lastCacheModificationPerId",{enumerable:!0,configurable:!0,writable:!0,value:we.map()})}return Object.defineProperty(t.prototype,"updateLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)}}),Object.defineProperty(t.prototype,"getLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t}}),Object.defineProperty(t.prototype,"addNodeToCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var r=e.identifier;this.cache.has(r)||this.cache.set(r,we.array([],$n));var n=this.cache.get(r);if(-1!==n.indexOf(e))throw Hn("Already registered");n.push(e),t&&this.updateLastCacheModificationPerId(r)}}}),Object.defineProperty(t.prototype,"mergeCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;Ut(e.identifierCache.cache).forEach((function(e){return e.forEach((function(e){t.addNodeToCache(e)}))}))}}),Object.defineProperty(t.prototype,"notifyDied",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.identifierAttribute){var t=e.identifier,r=this.cache.get(t);r&&(r.remove(e),r.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}}}),Object.defineProperty(t.prototype,"splitCache",{enumerable:!1,configurable:!0,writable:!0,value:function(r){var n,i=this,o=new t,a=r.path;return(n=this.cache,Sr(n)?Rt(n).map((function(e){return[e,n[e]]})):vr(n)?Rt(n).map((function(e){return[e,n.get(e)]})):mr(n)?Array.from(n.entries()):lr(n)?n.map((function(e,t){return[t,e]})):void e(7)).forEach((function(e){for(var t=Yr(e,2),r=t[0],n=t[1],s=!1,u=n.length-1;u>=0;u--)0===n[u].path.indexOf(a)&&(o.addNodeToCache(n[u],!1),n.splice(u,1),s=!0);s&&i.updateLastCacheModificationPerId(r)})),o}}),Object.defineProperty(t.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);return!!r&&r.some((function(t){return e.isAssignableFrom(t.type)}))}}),Object.defineProperty(t.prototype,"resolve",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);if(!r)return null;var n=r.filter((function(t){return e.isAssignableFrom(t.type)}));switch(n.length){case 0:return null;case 1:return n[0];default:throw Hn("Cannot resolve a reference to type '"+e.name+"' with id: '"+t+"' unambigously, there are multiple candidates: "+n.map((function(e){return e.path})).join(", "))}}}),t}();function Cn(e,t,r,n,i){var o=Vn(i);if(o){if(o.parent)throw Hn("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:"")+"/"+r+"', but it lives already at '"+o.path+"'");return t&&o.setParent(t,r),o}return new un(e,t,r,n,i)}function kn(e,t,r,n,i){return new rn(e,t,r,n,i)}function Dn(e){return!(!e||!e.$treenode)}function Nn(e){if(!Dn(e))throw Hn("Value "+e+" is no MST Node");return e.$treenode}function Vn(e){return e&&e.$treenode||null}function Rn(){return Nn(this).snapshot}function Un(e,t,r){void 0===r&&(r=!0);for(var n=e,i=0;i0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"register",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return void 0===t&&(t=!1),t?this.handlers.unshift(e):this.handlers.push(e),function(){r.unregister(e)}}}),Object.defineProperty(e.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.handlers.indexOf(e)>=0}}),Object.defineProperty(e.prototype,"unregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}),Object.defineProperty(e.prototype,"clear",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.handlers.length=0}}),Object.defineProperty(e.prototype,"emit",{enumerable:!1,configurable:!0,writable:!0,value:function(){for(var e=[],t=0;t0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._determineIdentifierMode(),Cn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"_determineIdentifierMode",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.identifierMode===ui.UNKNOWN){var e=[];if(li(this._subType,e)){var t=void 0;e.forEach((function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw Hn("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=ui.YES,this.mapIdentifierAttribute=t):this.identifierMode=ui.NO}}}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t={});var r=e.type._subType,n={};return Object.keys(t).forEach((function(i){n[i]=r.instantiate(e,i,void 0,t[i])})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return new fi(e)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Dt(t,e.unbox),e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=mn(t,e,n);Xn(t,e,i)}))})),Nt(t,this.willChange),Ft(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"Map"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Ut(e.storedValue)}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e.storedValue.get(""+t);if(!r)throw Hn("Not a child "+t);return r}}),Object.defineProperty(t.prototype,"willChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Nn(e.object),r=e.name;t.assertWritable({subpath:r});var n=t.type,i=n._subType;switch(e.type){case"update":var o=e.newValue;if(o===e.object.get(r))return null;xn(i,o),e.newValue=i.reconcile(t.getChildNode(r),e.newValue,t,r),n.processIdentifier(r,e.newValue);break;case"add":xn(i,e.newValue),e.newValue=i.instantiate(t,r,void 0,e.newValue),n.processIdentifier(r,e.newValue)}return e}}),Object.defineProperty(t.prototype,"processIdentifier",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.identifierMode===ui.YES&&t instanceof un){var r=t.identifier;if(r!==e)throw Hn("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '"+r+"', but expected: '"+e+"'")}}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return e.getChildren().forEach((function(e){t[e.subpath]=e.snapshot})),t}}),Object.defineProperty(t.prototype,"processInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return Object.keys(e).forEach((function(r){t[r]=e[r].getSnapshot()})),t}}),Object.defineProperty(t.prototype,"didChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Nn(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:ii(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:ii(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":var r=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:ii(e.name),oldValue:r},t)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=e.storedValue;switch(r.op){case"add":case"replace":n.set(t,r.value);break;case"remove":n.delete(t)}}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){xn(this,t);var r=e.storedValue,n={};if(Array.from(r.keys()).forEach((function(e){n[e]=!1})),t)for(var i in t)r.set(i,t[i]),n[""+i]=!0;Object.keys(n).forEach((function(e){!1===n[e]&&r.delete(e)}))}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return Wn(e)?An(Object.keys(e).map((function(n){return r._subType.validate(e[n],jn(t,n,r._subType))}))):Sn(t,e,"Value is not a plain object")}}),Object.defineProperty(t.prototype,"getDefaultSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return Ln}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){e.storedValue.delete(t)}}),t}(fn);pi.prototype.applySnapshot=yt(pi.prototype.applySnapshot);var hi=function(e){function t(t,r,n){void 0===n&&(n=[]);var i=e.call(this,t)||this;return Object.defineProperty(i,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Array}),Object.defineProperty(i,"hookInitializers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),i.hookInitializers=n,i}return Kr(t,e),Object.defineProperty(t.prototype,"hooks",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var r=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return Cn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t=[]);var r=e.type._subType,n={};return t.forEach((function(t,i){var o=""+i;n[o]=r.instantiate(e,o,void 0,t)})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return we.array(Mn(e),$n)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Rr(t).dehancer=e.unbox,e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=mn(t,e,n);Xn(t,e,i)}))})),Nt(t,this.willChange),Ft(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType.describe()+"[]"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.slice()}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=Number(t);if(r=0;r--)t.emitPatch({op:"remove",path:""+(e.index+r),oldValue:e.removed[r].snapshot},t);for(r=0;r0)return r;var n=Dn(e)?Nn(e).snapshot:e;return this._predicate(n)?Pn():Sn(t,e,this._message(e))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(ln);var Di=function(e){function t(t,r,n){var i=e.call(this,t)||this;return Object.defineProperty(i,"_types",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"_dispatcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"_eager",{enumerable:!0,configurable:!0,writable:!0,value:!0}),n=qr({eager:!0,dispatcher:void 0},n),i._dispatcher=n.dispatcher,n.eager||(i._eager=!1),i}return Kr(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){var e=on.Union;return this._types.forEach((function(t){e|=t.flags})),e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._types.some((function(t){return t.isAssignableFrom(e)}))}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"("+this._types.map((function(e){return e.describe()})).join(" | ")+")"}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(n,void 0);if(!i)throw Hn("No matching type for union "+this.describe());return i.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(t,e.type);if(!i)throw Hn("No matching type for union "+this.describe());return i.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"determineType",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter((function(e){return e!==t})).find((function(t){return t.is(e)})):this._types.find((function(t){return t.is(e)}))}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);for(var r=[],n=0,i=0;i=0){var i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,r,i)}return this._subtype.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),r,n)}}),Object.defineProperty(t.prototype,"getDefaultInstanceOrSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&xn(this,e),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this.optionalValues.indexOf(e)>=0?Pn():this._subtype.validate(e,t)}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._subtype.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(ln);function Ri(e,t,r){return function(e,t){if("function"!=typeof t&&Dn(t))throw Hn("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}(0,t),new Vi(e,t,r||Ui)}var Ui=[void 0],Mi=Ri(xi,void 0),zi=Ri(Ai,null);function Fi(e){return Ni(e,Mi)}var Li=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"_definition",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n}return Kr(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return(this._subType?this._subType.flags:0)|on.Late},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSubType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(!this._subType){var t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw Hn("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e?e.name:""}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.getSubType(!1);return r?r.validate(e,t):Pn()}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e||"cannotDetermine"}}),t}(ln);var $i=function(e){function t(t){var r=e.call(this,t?"frozen("+t.name+")":"frozen")||this;return Object.defineProperty(r,"subType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Frozen}),r}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return""}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return kn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return function(e){return"function"!=typeof e}(e)?this.subType?this.subType.validate(e,t):Pn():Sn(t,e,"Value is not serializable and cannot be frozen")}}),t}(pn),Hi=new $i;var Bi=function(){function e(e,t){if(Object.defineProperty(this,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolvedReference",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),ro(e))this.identifier=e;else{if(!Dn(e))throw Hn("Can only store references to tree nodes or identifiers, got: '"+e+"'");var r=Nn(e);if(!r.identifierAttribute)throw Hn("Can only store references with a defined identifier attribute.");var n=r.unnormalizedIdentifier;if(null==n)throw Hn("Can only store references to tree nodes with a defined identifier.");this.identifier=n}}return Object.defineProperty(e.prototype,"updateResolvedReference",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=to(this.identifier),r=e.root,n=r.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==n){var i=this.targetType,o=r.identifierCache.resolve(i,t);if(!o)throw new Gi("[mobx-state-tree] Failed to resolve reference '"+this.identifier+"' to type '"+this.targetType.name+"' (from node: "+e.path+")");this.resolvedReference={node:o,lastCacheModification:n}}}}),Object.defineProperty(e.prototype,"resolvedValue",{get:function(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value},enumerable:!1,configurable:!0}),e}(),Gi=function(e){function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return Kr(t,e),t}(Error),Ki=function(e){function t(t,r){var n=e.call(this,"reference("+t.name+")")||this;return Object.defineProperty(n,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"onInvalidated",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Reference}),n}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.targetType.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return ro(e)?Pn():Sn(t,e,"Value is not a valid identifier, which is a string or a number")}}),Object.defineProperty(t.prototype,"fireInvalidated",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=t.parent;if(i&&i.isAlive){var o=i.storedValue;o&&this.onInvalidated({cause:e,parent:o,invalidTarget:n?n.storedValue:void 0,invalidId:r,replaceRef:function(e){Zr(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef:function(){!function(e){return hn(e)&&(e.flags&on.Object)>0}(i.type)?Zr(t.root.storedValue,{op:"remove",path:t.path}):this.replaceRef(void 0)}})}}}),Object.defineProperty(t.prototype,"addTargetNodeWatcher",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this,n=this.getValue(e);if(n){var i=Nn(n),o=function(n,o){var a=function(e){switch(e){case Br.beforeDestroy:return"destroy";case Br.beforeDetach:return"detach";default:return}}(o);a&&r.fireInvalidated(a,e,t,i)},a=i.registerHook(Br.beforeDetach,o),s=i.registerHook(Br.beforeDestroy,o);return function(){a(),s()}}}}),Object.defineProperty(t.prototype,"watchTargetNodeForInvalidations",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=this;if(this.onInvalidated){var i;e.registerHook(Br.beforeDestroy,(function(){i&&i()}));var o=function(o){i&&i();var a=e.parent,s=a&&a.storedValue;if(a&&a.isAlive&&s){(r?!!r.get(t,s):e.root.identifierCache.has(n.targetType,to(t)))?i=n.addTargetNodeWatcher(e,t):o||n.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===En.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(Br.afterCreationFinalization,(function(){e.parent&&e.parent.createObservableInstanceIfNeeded()})),e.registerHook(Br.afterAttach,(function(){o(!1)})))}}}),t}(pn),qi=function(e){function t(t,r){return e.call(this,t,r)||this}return Kr(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return e.storedValue.resolvedValue}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.identifier}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(n)?Nn(n).identifier:n,o=new Bi(n,this.targetType),a=kn(this,e,t,r,o);return o.node=a,this.watchTargetNodeForInvalidations(a,i,void 0),a}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!e.isDetaching&&e.type===this){var i=Dn(t),o=e.storedValue;if(!i&&o.identifier===t||i&&o.resolvedValue===t)return e.setParent(r,n),e}var a=this.instantiate(r,n,void 0,t);return e.die(),a}}),t}(Ki),Wi=function(e){function t(t,r,n){var i=e.call(this,t,n)||this;return Object.defineProperty(i,"options",{enumerable:!0,configurable:!0,writable:!0,value:r}),i}return Kr(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(n)?this.options.set(n,e?e.storedValue:null):n,o=kn(this,e,t,r,i);return this.watchTargetNodeForInvalidations(o,i,this.options),o}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===i)return e.setParent(r,n),e;var o=this.instantiate(r,n,void 0,i);return e.die(),o}}),t}(Ki);function Yi(e,t){var r=t||void 0,n=t?t.onInvalidated:void 0;return r&&(r.get||r.set)?new Wi(e,{get:r.get,set:r.set},n):new qi(e,n)}var Qi=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"validType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Identifier}),n}return Kr(t,e),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!(e&&e.type instanceof _i))throw Hn("Identifier types can only be instantiated as direct child of a model type");return kn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(e.storedValue!==t)throw Hn("Tried to change identifier from '"+e.storedValue+"' to '"+t+"'. Changing identifiers is not allowed.");return e.setParent(r,n),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return typeof e!==this.validType?Sn(t,e,"Value is not a valid "+this.describe()+", expected a "+this.validType):Pn()}}),t}(pn),Xi=function(e){function t(){var t=e.call(this,"identifier","string")||this;return Object.defineProperty(t,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Identifier}),t}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifier"}}),t}(Qi),Zi=function(e){function t(){return e.call(this,"identifierNumber","number")||this}return Kr(t,e),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifierNumber"}}),t}(Qi),Ji=new Xi,eo=new Zi;function to(e){return""+e}function ro(e){return"string"==typeof e||"number"==typeof e}var no,io=function(e){function t(t){var r=e.call(this,t.name)||this;return Object.defineProperty(r,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Custom}),r}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.options.isTargetType(e))return Pn();var r=this.options.getValidationMessage(e);return r?Sn(t,e,"Invalid value for type '"+this.name+"': "+r):Pn()}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.options.toSnapshot(e.storedValue)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return kn(this,e,t,r,this.options.isTargetType(n)?n:this.options.fromSnapshot(n,e&&e.root.environment))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=!this.options.isTargetType(t);if(!e.isDetaching&&(e.type===this&&(i?t===e.snapshot:t===e.storedValue)))return e.setParent(r,n),e;var o=i?this.options.fromSnapshot(t,r.root.environment):t,a=this.instantiate(r,n,void 0,o);return e.die(),a}}),t}(pn),oo={enumeration:function(e,t){var r="string"==typeof e?t:e,n=Ni.apply(void 0,Qr(r.map((function(e){return Ci(""+e)}))));return"string"==typeof e&&(n.name=e),n},model:function(){for(var e=[],t=0;t",e)},array:function(e){return new hi(e.name+"[]",e)},frozen:function(e){return 0===arguments.length?Hi:hn(e)?new $i(e):Ri(Hi,e)},identifier:Ji,identifierNumber:eo,late:function(e,t){var r="string"==typeof e?e:"late("+e.toString()+")";return new Li(r,"string"==typeof e?t:e)},undefined:xi,null:Ai,snapshotProcessor:function(e,t,r){return new si(e,t,r)}},ao=new Uint8Array(16);function so(){if(!no&&!(no="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return no(ao)}var uo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function co(e){return"string"==typeof e&&uo.test(e)}for(var lo=[],fo=0;fo<256;++fo)lo.push((fo+256).toString(16).substr(1));function po(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(lo[e[t+0]]+lo[e[t+1]]+lo[e[t+2]]+lo[e[t+3]]+"-"+lo[e[t+4]]+lo[e[t+5]]+"-"+lo[e[t+6]]+lo[e[t+7]]+"-"+lo[e[t+8]]+lo[e[t+9]]+"-"+lo[e[t+10]]+lo[e[t+11]]+lo[e[t+12]]+lo[e[t+13]]+lo[e[t+14]]+lo[e[t+15]]).toLowerCase();if(!co(r))throw TypeError("Stringified UUID is invalid");return r}function ho(e,t,r){var n=(e=e||{}).random||(e.rng||so)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return po(n)}function bo(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function vo(e,t){return e<>>32-t}var yo=function(e,t,r){function n(e,n,i,o){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}(n)),16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var a=new Uint8Array(16+e.length);if(a.set(n),a.set(e,n.length),(a=r(a))[6]=15&a[6]|t,a[8]=63&a[8]|128,i){o=o||0;for(var s=0;s<16;++s)i[o+s]=a[s];return i}return po(a)}try{n.name=e}catch(e){}return n.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",n.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",n}("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i>>0;m=g,g=y,y=vo(v,30)>>>0,v=d,d=O}r[0]=r[0]+d>>>0,r[1]=r[1]+v>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+g>>>0,r[4]=r[4]+m>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]})); /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -242,39 +242,39 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */var Oo=function(e,t){return(Oo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function jo(e,t){function r(){this.constructor=e}Oo(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Po(e){return"function"==typeof e}var So=!1,Ao={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;So=e},get useDeprecatedSynchronousErrorHandling(){return So}};function xo(e){setTimeout((function(){throw e}),0)}var Eo={closed:!0,next:function(e){},error:function(e){if(Ao.useDeprecatedSynchronousErrorHandling)throw e;xo(e)},complete:function(){}},To=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function Io(e){return null!==e&&"object"==typeof e}var Co=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),ko=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var r=this,n=r._parentOrParents,i=r._ctorUnsubscribe,o=r._unsubscribe,a=r._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,n instanceof e)n.remove(this);else if(null!==n)for(var s=0;s1)this.connection=null;else{var r=this.connection,n=e._connection;this.connection=null,!n||r&&n!==r||n.unsubscribe()}}else this.connection=null},t}(Vo),Xo=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subjectFactory=r,n._refCount=0,n._isComplete=!1,n}return jo(t,e),t.prototype._subscribe=function(e){return this.getSubject().subscribe(e)},t.prototype.getSubject=function(){var e=this._subject;return e&&!e.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype.connect=function(){var e=this._connection;return e||(this._isComplete=!1,(e=this._connection=new ko).add(this.source.subscribe(new Jo(this.getSubject(),this))),e.closed&&(this._connection=null,e=ko.EMPTY)),e},t.prototype.refCount=function(){return Wo()(this)},t}(Lo),Zo=function(){var e=Xo.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:e._subscribe},_isComplete:{value:e._isComplete,writable:!0},getSubject:{value:e.getSubject},connect:{value:e.connect},refCount:{value:e.refCount}}}(),Jo=function(e){function t(t,r){var n=e.call(this,t)||this;return n.connectable=r,n}return jo(t,e),t.prototype._error=function(t){this._unsubscribe(),e.prototype._error.call(this,t)},t.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){var e=this.connectable;if(e){this.connectable=null;var t=e._connection;e._refCount=0,e._subject=null,e._connection=null,t&&t.unsubscribe()}},t}(Go),ea=function(e){function t(t,r){var n=e.call(this,t,r)||this;return n.scheduler=t,n.work=r,n.pending=!1,n}return jo(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var r=this.id,n=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(n,r,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(n,this.id,t),this},t.prototype.requestAsyncId=function(e,t,r){return void 0===r&&(r=0),setInterval(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,t,r){if(void 0===r&&(r=0),null!==r&&this.delay===r&&!1===this.pending)return t;clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,t);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var r=!1,n=void 0;try{this.work(e)}catch(e){r=!0,n=!!e&&e||new Error(e)}if(r)return this.unsubscribe(),n},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,r=t.actions,n=r.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==n&&r.splice(n,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,r){return e.call(this)||this}return jo(t,e),t.prototype.schedule=function(e,t){return this},t}(ko)),ta=function(){function e(t,r){void 0===r&&(r=e.now),this.SchedulerAction=t,this.now=r}return e.prototype.schedule=function(e,t,r){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(r,t)},e.now=function(){return Date.now()},e}(),ra=function(e){function t(r,n){void 0===n&&(n=ta.now);var i=e.call(this,r,(function(){return t.delegate&&t.delegate!==i?t.delegate.now():n()}))||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return jo(t,e),t.prototype.schedule=function(r,n,i){return void 0===n&&(n=0),t.delegate&&t.delegate!==this?t.delegate.schedule(r,n,i):e.prototype.schedule.call(this,r,n,i)},t.prototype.flush=function(e){var t=this.actions;if(this.active)t.push(e);else{var r;this.active=!0;do{if(r=e.execute(e.state,e.delay))break}while(e=t.shift());if(this.active=!1,r){for(;e=t.shift();)e.unsubscribe();throw r}}},t}(ta),na=new Lo((function(e){return e.complete()}));function ia(e){return e&&"function"==typeof e.schedule}var oa=function(e){return function(t){for(var r=0,n=e.length;r0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(Pa);function Ta(e,t,r){return r?Ta(e,t).pipe(fa((function(e){return To(e)?r.apply(void 0,e):r(e)}))):new Lo((function(r){var n,i=function(){for(var e=[],t=0;t=0}function Ca(e,t){return function(r){return r.lift(new ka(e,t))}}var ka=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Da(e,this.predicate,this.thisArg))},e}(),Da=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.predicate=r,i.thisArg=n,i.count=0,i}return jo(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(Vo);function Na(e,t,r){void 0===e&&(e=0);var n=-1;return Ia(t)?n=Number(t)<1?1:Number(t):ia(t)&&(r=t),ia(r)||(r=ca),new Lo((function(t){var i=Ia(e)?e:+e-r.now();return r.schedule(Va,i,{index:0,period:n,subscriber:t})}))}function Va(e){var t=e.index,r=e.period,n=e.subscriber;if(n.next(t),!n.closed){if(-1===r)return n.complete();e.index=t+1,this.schedule(e,r)}}var Ra="object"==typeof global&&global&&global.Object===Object&&global,Ua="object"==typeof self&&self&&self.Object===Object&&self,Ma=Ra||Ua||Function("return this")(),Fa=Ma.Symbol,za=Object.prototype,La=za.hasOwnProperty,$a=za.toString,Ha=Fa?Fa.toStringTag:void 0;var Ba=Object.prototype.toString;var Ga=Fa?Fa.toStringTag:void 0;function Ka(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Ga&&Ga in Object(e)?function(e){var t=La.call(e,Ha),r=e[Ha];try{e[Ha]=void 0;var n=!0}catch(e){}var i=$a.call(e);return n&&(t?e[Ha]=r:delete e[Ha]),i}(e):function(e){return Ba.call(e)}(e)}function qa(e){return null!=e&&"object"==typeof e}function Wa(e){return"symbol"==typeof e||qa(e)&&"[object Symbol]"==Ka(e)}function Ya(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r0){if(++gs>=800)return arguments[0]}else gs=0;return ys.apply(void 0,arguments)});function Os(e){return e!=e}function js(e,t){return!!(null==e?0:e.length)&&function(e,t,r){return t==t?function(e,t,r){for(var n=r-1,i=e.length;++n-1}var Ps=/^(?:0|[1-9]\d*)$/;function Ss(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&Ps.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}function ks(e){return qa(e)&&"[object Arguments]"==Ka(e)}var Ds=Object.prototype,Ns=Ds.hasOwnProperty,Vs=Ds.propertyIsEnumerable,Rs=ks(function(){return arguments}())?ks:function(e){return qa(e)&&Ns.call(e,"callee")&&!Vs.call(e,"callee")};function Us(e){return function(t){return e(t)}}var Ms="object"==typeof exports&&exports&&!exports.nodeType&&exports,Fs=Ms&&"object"==typeof module&&module&&!module.nodeType&&module,zs=Fs&&Fs.exports===Ms&&Ra.process,Ls=function(){try{var e=Fs&&Fs.require&&Fs.require("util").types;return e||zs&&zs.binding&&zs.binding("util")}catch(e){}}(),$s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Hs=/^\w*$/;var Bs=bs(Object,"create");var Gs=Object.prototype.hasOwnProperty;var Ks=Object.prototype.hasOwnProperty;function qs(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1},Qs.prototype.set=function(e,t){var r=this.__data__,n=Ws(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};var Xs=bs(Ma,"Map");function Zs(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function Js(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t0&&r(s)?t>1?lu(s,t-1,r,n,i):su(i,s):n||(i[i.length]=s)}return i}function fu(e){return(null==e?0:e.length)?lu(e,1):[]}function pu(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new Js;++t=200&&(o=hu,a=!1,t=new pu(t));e:for(;++i=2&&(n=arguments[1]);var i=Number.POSITIVE_INFINITY;return t>=3&&(i=arguments[2]),function(t){return t.lift(new Su(e,n,i,r))}}var Su=function(){function e(e,t,r,n){this.bufferTimeSpan=e,this.bufferCreationInterval=t,this.maxBufferSize=r,this.scheduler=n}return e.prototype.call=function(e,t){return t.subscribe(new xu(e,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))},e}(),Au=function(){return function(){this.buffer=[]}}(),xu=function(e){function t(t,r,n,i,o){var a=e.call(this,t)||this;a.bufferTimeSpan=r,a.bufferCreationInterval=n,a.maxBufferSize=i,a.scheduler=o,a.contexts=[];var s=a.openContext();if(a.timespanOnly=null==n||n<0,a.timespanOnly){var u={subscriber:a,context:s,bufferTimeSpan:r};a.add(s.closeAction=o.schedule(Eu,r,u))}else{var c={subscriber:a,context:s},l={bufferTimeSpan:r,bufferCreationInterval:n,subscriber:a,scheduler:o};a.add(s.closeAction=o.schedule(Iu,r,c)),a.add(o.schedule(Tu,n,l))}return a}return jo(t,e),t.prototype._next=function(e){for(var t,r=this.contexts,n=r.length,i=0;i0;){var n=t.shift();r.next(n.buffer)}e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){this.contexts=null},t.prototype.onBufferFull=function(e){this.closeContext(e);var t=e.closeAction;if(t.unsubscribe(),this.remove(t),!this.closed&&this.timespanOnly){e=this.openContext();var r=this.bufferTimeSpan,n={subscriber:this,context:e,bufferTimeSpan:r};this.add(e.closeAction=this.scheduler.schedule(Eu,r,n))}},t.prototype.openContext=function(){var e=new Au;return this.contexts.push(e),e},t.prototype.closeContext=function(e){this.destination.next(e.buffer);var t=this.contexts;(t?t.indexOf(e):-1)>=0&&t.splice(t.indexOf(e),1)},t}(Vo);function Eu(e){var t=e.subscriber,r=e.context;r&&t.closeContext(r),t.closed||(e.context=t.openContext(),e.context.closeAction=this.schedule(e,e.bufferTimeSpan))}function Tu(e){var t=e.bufferCreationInterval,r=e.bufferTimeSpan,n=e.subscriber,i=e.scheduler,o=n.openContext();n.closed||(n.add(o.closeAction=i.schedule(Iu,r,{subscriber:n,context:o})),this.schedule(e,t))}function Iu(e){var t=e.subscriber,r=e.context;t.closeContext(r)}function Cu(e){return function(t){var r=new ku(e),n=t.lift(r);return r.caught=n}}var ku=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new Du(e,this.selector,this.caught))},e}(),Du=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.selector=r,i.caught=n,i}return jo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=void 0;try{r=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var n=new ja(this);this.add(n);var i=Sa(r,n);i!==n&&this.add(i)}},t}(Pa);function Nu(e,t){return Aa(e,t,1)}function Vu(e,t){return t?function(r){return new Mu(r,t).lift(new Ru(e))}:function(t){return t.lift(new Ru(e))}}var Ru=function(){function e(e){this.delayDurationSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new Uu(e,this.delayDurationSelector))},e}(),Uu=function(e){function t(t,r){var n=e.call(this,t)||this;return n.delayDurationSelector=r,n.completed=!1,n.delayNotifierSubscriptions=[],n.index=0,n}return jo(t,e),t.prototype.notifyNext=function(e,t,r,n,i){this.destination.next(e),this.removeSubscription(i),this.tryComplete()},t.prototype.notifyError=function(e,t){this._error(e)},t.prototype.notifyComplete=function(e){var t=this.removeSubscription(e);t&&this.destination.next(t),this.tryComplete()},t.prototype._next=function(e){var t=this.index++;try{var r=this.delayDurationSelector(e,t);r&&this.tryDelay(r,e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){this.completed=!0,this.tryComplete(),this.unsubscribe()},t.prototype.removeSubscription=function(e){e.unsubscribe();var t=this.delayNotifierSubscriptions.indexOf(e);return-1!==t&&this.delayNotifierSubscriptions.splice(t,1),e.outerValue},t.prototype.tryDelay=function(e,t){var r=function(e,t,r,n,i){if(void 0===i&&(i=new da(e,r,n)),!i.closed)return t instanceof Lo?t.subscribe(i):_a(t)(i)}(this,e,t);r&&!r.closed&&(this.destination.add(r),this.delayNotifierSubscriptions.push(r))},t.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()},t}(ba),Mu=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subscriptionDelay=r,n}return jo(t,e),t.prototype._subscribe=function(e){this.subscriptionDelay.subscribe(new Fu(e,this.source))},t}(Lo),Fu=function(e){function t(t,r){var n=e.call(this)||this;return n.parent=t,n.source=r,n.sourceSubscribed=!1,n}return jo(t,e),t.prototype._next=function(e){this.subscribeToSource()},t.prototype._error=function(e){this.unsubscribe(),this.parent.error(e)},t.prototype._complete=function(){this.unsubscribe(),this.subscribeToSource()},t.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))},t}(Vo);var zu=function(){function e(e,t,r){void 0===r&&(r=!1),this.accumulator=e,this.seed=t,this.hasSeed=r}return e.prototype.call=function(e,t){return t.subscribe(new Lu(e,this.accumulator,this.seed,this.hasSeed))},e}(),Lu=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o.accumulator=r,o._seed=n,o.hasSeed=i,o.index=0,o}return jo(t,e),Object.defineProperty(t.prototype,"seed",{get:function(){return this._seed},set:function(e){this.hasSeed=!0,this._seed=e},enumerable:!0,configurable:!0}),t.prototype._next=function(e){if(this.hasSeed)return this._tryNext(e);this.seed=e,this.destination.next(e)},t.prototype._tryNext=function(e){var t,r=this.index++;try{t=this.accumulator(this.seed,e,r)}catch(e){this.destination.error(e)}this.seed=t,this.destination.next(t)},t}(Vo);var $u=function(){function e(e,t){this.subjectFactory=e,this.selector=t}return e.prototype.call=function(e,t){var r=this.selector,n=this.subjectFactory(),i=r(n).subscribe(e);return i.add(t.subscribe(n)),i},e}();var Hu=function(){function e(e,t){this.notifier=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new Bu(e,this.notifier,this.source))},e}(),Bu=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.notifier=r,i.source=n,i}return jo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=this.errors,n=this.retries,i=this.retriesSubscription;if(n)this.errors=void 0,this.retriesSubscription=void 0;else{r=new Ko;try{n=(0,this.notifier)(r)}catch(t){return e.prototype.error.call(this,t)}i=Sa(n,new ja(this))}this._unsubscribeAndRecycle(),this.errors=r,this.retries=n,this.retriesSubscription=i,r.next(t)}},t.prototype._unsubscribe=function(){var e=this.errors,t=this.retriesSubscription;e&&(e.unsubscribe(),this.errors=void 0),t&&(t.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},t.prototype.notifyNext=function(){var e=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=e,this.source.subscribe(this)},t}(Pa);function Gu(){return new Ko}function Ku(){return function(e){return Wo()((t=Gu,function(e){var n;if(n="function"==typeof t?t:function(){return t},"function"==typeof r)return e.lift(new $u(n,r));var i=Object.create(e,Zo);return i.source=e,i.subjectFactory=n,i})(e));var t,r}}function qu(e,t){return"function"==typeof t?function(r){return r.pipe(qu((function(r,n){return Oa(e(r,n)).pipe(fa((function(e,i){return t(r,e,n,i)})))})))}:function(t){return t.lift(new Wu(e))}}var Wu=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new Yu(e,this.project))},e}(),Yu=function(e){function t(t,r){var n=e.call(this,t)||this;return n.project=r,n.index=0,n}return jo(t,e),t.prototype._next=function(e){var t,r=this.index++;try{t=this.project(e,r)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var r=new ja(this),n=this.destination;n.add(r),this.innerSubscription=Sa(e,r),this.innerSubscription!==r&&n.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(Pa);function Qu(e,t,r){return function(n){return n.lift(new Xu(e,t,r))}}var Xu=function(){function e(e,t,r){this.nextOrObserver=e,this.error=t,this.complete=r}return e.prototype.call=function(e,t){return t.subscribe(new Zu(e,this.nextOrObserver,this.error,this.complete))},e}(),Zu=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o._tapNext=la,o._tapError=la,o._tapComplete=la,o._tapError=n||la,o._tapComplete=i||la,Po(r)?(o._context=o,o._tapNext=r):r&&(o._context=r,o._tapNext=r.next||la,o._tapError=r.error||la,o._tapComplete=r.complete||la),o}return jo(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(Vo); +***************************************************************************** */var Oo=function(e,t){return(Oo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function jo(e,t){function r(){this.constructor=e}Oo(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Po(e){return"function"==typeof e}var So=!1,Ao={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;So=e},get useDeprecatedSynchronousErrorHandling(){return So}};function xo(e){setTimeout((function(){throw e}),0)}var Eo={closed:!0,next:function(e){},error:function(e){if(Ao.useDeprecatedSynchronousErrorHandling)throw e;xo(e)},complete:function(){}},To=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function Io(e){return null!==e&&"object"==typeof e}var Co=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),ko=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var r=this,n=r._parentOrParents,i=r._ctorUnsubscribe,o=r._unsubscribe,a=r._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,n instanceof e)n.remove(this);else if(null!==n)for(var s=0;s1)this.connection=null;else{var r=this.connection,n=e._connection;this.connection=null,!n||r&&n!==r||n.unsubscribe()}}else this.connection=null},t}(Vo),Xo=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subjectFactory=r,n._refCount=0,n._isComplete=!1,n}return jo(t,e),t.prototype._subscribe=function(e){return this.getSubject().subscribe(e)},t.prototype.getSubject=function(){var e=this._subject;return e&&!e.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype.connect=function(){var e=this._connection;return e||(this._isComplete=!1,(e=this._connection=new ko).add(this.source.subscribe(new Jo(this.getSubject(),this))),e.closed&&(this._connection=null,e=ko.EMPTY)),e},t.prototype.refCount=function(){return Wo()(this)},t}(Lo),Zo=function(){var e=Xo.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:e._subscribe},_isComplete:{value:e._isComplete,writable:!0},getSubject:{value:e.getSubject},connect:{value:e.connect},refCount:{value:e.refCount}}}(),Jo=function(e){function t(t,r){var n=e.call(this,t)||this;return n.connectable=r,n}return jo(t,e),t.prototype._error=function(t){this._unsubscribe(),e.prototype._error.call(this,t)},t.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){var e=this.connectable;if(e){this.connectable=null;var t=e._connection;e._refCount=0,e._subject=null,e._connection=null,t&&t.unsubscribe()}},t}(Go),ea=function(e){function t(t,r){var n=e.call(this,t,r)||this;return n.scheduler=t,n.work=r,n.pending=!1,n}return jo(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var r=this.id,n=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(n,r,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(n,this.id,t),this},t.prototype.requestAsyncId=function(e,t,r){return void 0===r&&(r=0),setInterval(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,t,r){if(void 0===r&&(r=0),null!==r&&this.delay===r&&!1===this.pending)return t;clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,t);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var r=!1,n=void 0;try{this.work(e)}catch(e){r=!0,n=!!e&&e||new Error(e)}if(r)return this.unsubscribe(),n},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,r=t.actions,n=r.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==n&&r.splice(n,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,r){return e.call(this)||this}return jo(t,e),t.prototype.schedule=function(e,t){return this},t}(ko)),ta=function(){function e(t,r){void 0===r&&(r=e.now),this.SchedulerAction=t,this.now=r}return e.prototype.schedule=function(e,t,r){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(r,t)},e.now=function(){return Date.now()},e}(),ra=function(e){function t(r,n){void 0===n&&(n=ta.now);var i=e.call(this,r,(function(){return t.delegate&&t.delegate!==i?t.delegate.now():n()}))||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return jo(t,e),t.prototype.schedule=function(r,n,i){return void 0===n&&(n=0),t.delegate&&t.delegate!==this?t.delegate.schedule(r,n,i):e.prototype.schedule.call(this,r,n,i)},t.prototype.flush=function(e){var t=this.actions;if(this.active)t.push(e);else{var r;this.active=!0;do{if(r=e.execute(e.state,e.delay))break}while(e=t.shift());if(this.active=!1,r){for(;e=t.shift();)e.unsubscribe();throw r}}},t}(ta),na=new Lo((function(e){return e.complete()}));function ia(e){return e&&"function"==typeof e.schedule}var oa=function(e){return function(t){for(var r=0,n=e.length;r0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(Pa);function Ta(e,t,r){return r?Ta(e,t).pipe(fa((function(e){return To(e)?r.apply(void 0,e):r(e)}))):new Lo((function(r){var n,i=function(){for(var e=[],t=0;t=0}function Ca(e,t){return function(r){return r.lift(new ka(e,t))}}var ka=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Da(e,this.predicate,this.thisArg))},e}(),Da=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.predicate=r,i.thisArg=n,i.count=0,i}return jo(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(Vo);function Na(e,t,r){void 0===e&&(e=0);var n=-1;return Ia(t)?n=Number(t)<1?1:Number(t):ia(t)&&(r=t),ia(r)||(r=ca),new Lo((function(t){var i=Ia(e)?e:+e-r.now();return r.schedule(Va,i,{index:0,period:n,subscriber:t})}))}function Va(e){var t=e.index,r=e.period,n=e.subscriber;if(n.next(t),!n.closed){if(-1===r)return n.complete();e.index=t+1,this.schedule(e,r)}}var Ra="object"==typeof global&&global&&global.Object===Object&&global,Ua="object"==typeof self&&self&&self.Object===Object&&self,Ma=Ra||Ua||Function("return this")(),za=Ma.Symbol,Fa=Object.prototype,La=Fa.hasOwnProperty,$a=Fa.toString,Ha=za?za.toStringTag:void 0;var Ba=Object.prototype.toString;var Ga=za?za.toStringTag:void 0;function Ka(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Ga&&Ga in Object(e)?function(e){var t=La.call(e,Ha),r=e[Ha];try{e[Ha]=void 0;var n=!0}catch(e){}var i=$a.call(e);return n&&(t?e[Ha]=r:delete e[Ha]),i}(e):function(e){return Ba.call(e)}(e)}function qa(e){return null!=e&&"object"==typeof e}function Wa(e){return"symbol"==typeof e||qa(e)&&"[object Symbol]"==Ka(e)}function Ya(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r0){if(++gs>=800)return arguments[0]}else gs=0;return ys.apply(void 0,arguments)});function Os(e){return e!=e}function js(e,t){return!!(null==e?0:e.length)&&function(e,t,r){return t==t?function(e,t,r){for(var n=r-1,i=e.length;++n-1}var Ps=/^(?:0|[1-9]\d*)$/;function Ss(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&Ps.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}function ks(e){return qa(e)&&"[object Arguments]"==Ka(e)}var Ds=Object.prototype,Ns=Ds.hasOwnProperty,Vs=Ds.propertyIsEnumerable,Rs=ks(function(){return arguments}())?ks:function(e){return qa(e)&&Ns.call(e,"callee")&&!Vs.call(e,"callee")};function Us(e){return function(t){return e(t)}}var Ms="object"==typeof exports&&exports&&!exports.nodeType&&exports,zs=Ms&&"object"==typeof module&&module&&!module.nodeType&&module,Fs=zs&&zs.exports===Ms&&Ra.process,Ls=function(){try{var e=zs&&zs.require&&zs.require("util").types;return e||Fs&&Fs.binding&&Fs.binding("util")}catch(e){}}(),$s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Hs=/^\w*$/;var Bs=bs(Object,"create");var Gs=Object.prototype.hasOwnProperty;var Ks=Object.prototype.hasOwnProperty;function qs(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1},Qs.prototype.set=function(e,t){var r=this.__data__,n=Ws(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};var Xs=bs(Ma,"Map");function Zs(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function Js(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t0&&r(s)?t>1?lu(s,t-1,r,n,i):su(i,s):n||(i[i.length]=s)}return i}function fu(e){return(null==e?0:e.length)?lu(e,1):[]}function pu(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new Js;++t=200&&(o=hu,a=!1,t=new pu(t));e:for(;++i0;){var n=t.shift();r.next(n.buffer)}e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){this.contexts=null},t.prototype.onBufferFull=function(e){this.closeContext(e);var t=e.closeAction;if(t.unsubscribe(),this.remove(t),!this.closed&&this.timespanOnly){e=this.openContext();var r=this.bufferTimeSpan,n={subscriber:this,context:e,bufferTimeSpan:r};this.add(e.closeAction=this.scheduler.schedule(xu,r,n))}},t.prototype.openContext=function(){var e=new Su;return this.contexts.push(e),e},t.prototype.closeContext=function(e){this.destination.next(e.buffer);var t=this.contexts;(t?t.indexOf(e):-1)>=0&&t.splice(t.indexOf(e),1)},t}(Vo);function xu(e){var t=e.subscriber,r=e.context;r&&t.closeContext(r),t.closed||(e.context=t.openContext(),e.context.closeAction=this.schedule(e,e.bufferTimeSpan))}function Eu(e){var t=e.bufferCreationInterval,r=e.bufferTimeSpan,n=e.subscriber,i=e.scheduler,o=n.openContext();n.closed||(n.add(o.closeAction=i.schedule(Tu,r,{subscriber:n,context:o})),this.schedule(e,t))}function Tu(e){var t=e.subscriber,r=e.context;t.closeContext(r)}function Iu(e){return function(t){var r=new Cu(e),n=t.lift(r);return r.caught=n}}var Cu=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new ku(e,this.selector,this.caught))},e}(),ku=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.selector=r,i.caught=n,i}return jo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=void 0;try{r=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var n=new ja(this);this.add(n);var i=Sa(r,n);i!==n&&this.add(i)}},t}(Pa);function Du(e,t){return Aa(e,t,1)}function Nu(e,t){return t?function(r){return new Uu(r,t).lift(new Vu(e))}:function(t){return t.lift(new Vu(e))}}var Vu=function(){function e(e){this.delayDurationSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new Ru(e,this.delayDurationSelector))},e}(),Ru=function(e){function t(t,r){var n=e.call(this,t)||this;return n.delayDurationSelector=r,n.completed=!1,n.delayNotifierSubscriptions=[],n.index=0,n}return jo(t,e),t.prototype.notifyNext=function(e,t,r,n,i){this.destination.next(e),this.removeSubscription(i),this.tryComplete()},t.prototype.notifyError=function(e,t){this._error(e)},t.prototype.notifyComplete=function(e){var t=this.removeSubscription(e);t&&this.destination.next(t),this.tryComplete()},t.prototype._next=function(e){var t=this.index++;try{var r=this.delayDurationSelector(e,t);r&&this.tryDelay(r,e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){this.completed=!0,this.tryComplete(),this.unsubscribe()},t.prototype.removeSubscription=function(e){e.unsubscribe();var t=this.delayNotifierSubscriptions.indexOf(e);return-1!==t&&this.delayNotifierSubscriptions.splice(t,1),e.outerValue},t.prototype.tryDelay=function(e,t){var r=function(e,t,r,n,i){if(void 0===i&&(i=new da(e,r,n)),!i.closed)return t instanceof Lo?t.subscribe(i):_a(t)(i)}(this,e,t);r&&!r.closed&&(this.destination.add(r),this.delayNotifierSubscriptions.push(r))},t.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()},t}(ba),Uu=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subscriptionDelay=r,n}return jo(t,e),t.prototype._subscribe=function(e){this.subscriptionDelay.subscribe(new Mu(e,this.source))},t}(Lo),Mu=function(e){function t(t,r){var n=e.call(this)||this;return n.parent=t,n.source=r,n.sourceSubscribed=!1,n}return jo(t,e),t.prototype._next=function(e){this.subscribeToSource()},t.prototype._error=function(e){this.unsubscribe(),this.parent.error(e)},t.prototype._complete=function(){this.unsubscribe(),this.subscribeToSource()},t.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))},t}(Vo);var zu=function(){function e(e,t,r){void 0===r&&(r=!1),this.accumulator=e,this.seed=t,this.hasSeed=r}return e.prototype.call=function(e,t){return t.subscribe(new Fu(e,this.accumulator,this.seed,this.hasSeed))},e}(),Fu=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o.accumulator=r,o._seed=n,o.hasSeed=i,o.index=0,o}return jo(t,e),Object.defineProperty(t.prototype,"seed",{get:function(){return this._seed},set:function(e){this.hasSeed=!0,this._seed=e},enumerable:!0,configurable:!0}),t.prototype._next=function(e){if(this.hasSeed)return this._tryNext(e);this.seed=e,this.destination.next(e)},t.prototype._tryNext=function(e){var t,r=this.index++;try{t=this.accumulator(this.seed,e,r)}catch(e){this.destination.error(e)}this.seed=t,this.destination.next(t)},t}(Vo);var Lu=function(){function e(e,t){this.subjectFactory=e,this.selector=t}return e.prototype.call=function(e,t){var r=this.selector,n=this.subjectFactory(),i=r(n).subscribe(e);return i.add(t.subscribe(n)),i},e}();var $u=function(){function e(e,t){this.notifier=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new Hu(e,this.notifier,this.source))},e}(),Hu=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.notifier=r,i.source=n,i}return jo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=this.errors,n=this.retries,i=this.retriesSubscription;if(n)this.errors=void 0,this.retriesSubscription=void 0;else{r=new Ko;try{n=(0,this.notifier)(r)}catch(t){return e.prototype.error.call(this,t)}i=Sa(n,new ja(this))}this._unsubscribeAndRecycle(),this.errors=r,this.retries=n,this.retriesSubscription=i,r.next(t)}},t.prototype._unsubscribe=function(){var e=this.errors,t=this.retriesSubscription;e&&(e.unsubscribe(),this.errors=void 0),t&&(t.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},t.prototype.notifyNext=function(){var e=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=e,this.source.subscribe(this)},t}(Pa);function Bu(){return new Ko}function Gu(){return function(e){return Wo()((t=Bu,function(e){var n;if(n="function"==typeof t?t:function(){return t},"function"==typeof r)return e.lift(new Lu(n,r));var i=Object.create(e,Zo);return i.source=e,i.subjectFactory=n,i})(e));var t,r}}function Ku(e,t){return"function"==typeof t?function(r){return r.pipe(Ku((function(r,n){return Oa(e(r,n)).pipe(fa((function(e,i){return t(r,e,n,i)})))})))}:function(t){return t.lift(new qu(e))}}var qu=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new Wu(e,this.project))},e}(),Wu=function(e){function t(t,r){var n=e.call(this,t)||this;return n.project=r,n.index=0,n}return jo(t,e),t.prototype._next=function(e){var t,r=this.index++;try{t=this.project(e,r)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var r=new ja(this),n=this.destination;n.add(r),this.innerSubscription=Sa(e,r),this.innerSubscription!==r&&n.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(Pa);function Yu(e,t,r){return function(n){return n.lift(new Qu(e,t,r))}}var Qu=function(){function e(e,t,r){this.nextOrObserver=e,this.error=t,this.complete=r}return e.prototype.call=function(e,t){return t.subscribe(new Xu(e,this.nextOrObserver,this.error,this.complete))},e}(),Xu=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o._tapNext=la,o._tapError=la,o._tapComplete=la,o._tapError=n||la,o._tapComplete=i||la,Po(r)?(o._context=o,o._tapNext=r):r&&(o._context=r,o._tapNext=r.next||la,o._tapError=r.error||la,o._tapComplete=r.complete||la),o}return jo(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(Vo); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -class Ju{all=new Map;constructor(e={},t=null){this.bindThis=t||globalThis,this.on(e),this.createSource$=eu((e=>Ta((t=>this.on(e,t)),(t=>this.off(e,t))).pipe(Ku())))}#on(e,t){const r=this.all.get(e);r?r.unshift(t):this.all.set(e,[t])}on(e,t){"string"==typeof e?this.#on(e,t):e instanceof Object&&Object.entries(e).forEach((([e,t])=>{t instanceof Array?t.forEach((t=>this.#on(e,t))):t instanceof Function&&this.#on(e,t)}))}off(e,t){if("*"===e)return this.all.clear();{const r=this.all.get(e);return!!r&&(t?r.splice(r.indexOf(t)>>>0,1):this.all.set(e,[]))}}emit(e,...t){const r=this.all.get(e);return r?r.map((e=>e.apply(this.bindThis,t))):[]}}class ec{_belongTo=null;constructor(e,t){this.$EventHub=new Ju({},this),this.$store=wo({spiderUUID:t,originData:e})}$commit(e,...t){const r=this.$store[e](...t);return this.$EventHub.emit(e,...t),r}$on(...e){return this.$EventHub.on(...e)}$off(...e){return this.$EventHub.off(...e)}$isSameTask(e){return e.$store.spiderUUID===this.$store.spiderUUID&&e.$store.uuid===this.$store.uuid}$destroy(){this._belongTo=null,this.$commit("destroy"),this.$EventHub.off("*")}get[Symbol.toStringTag](){return"Task"}} +class Zu{all=new Map;constructor(e={},t=null){this.bindThis=t||globalThis,this.on(e),this.createSource$=eu((e=>Ta((t=>this.on(e,t)),(t=>this.off(e,t))).pipe(Gu())))}#on(e,t){const r=this.all.get(e);r?r.unshift(t):this.all.set(e,[t])}on(e,t){"string"==typeof e?this.#on(e,t):e instanceof Object&&Object.entries(e).forEach((([e,t])=>{t instanceof Array?t.forEach((t=>this.#on(e,t))):t instanceof Function&&this.#on(e,t)}))}off(e,t){if("*"===e)return this.all.clear();{const r=this.all.get(e);return!!r&&(t?r.splice(r.indexOf(t)>>>0,1):this.all.set(e,[]))}}emit(e,...t){const r=this.all.get(e);return r?r.map((e=>e.apply(this.bindThis,t))):[]}}class Ju{_belongTo=null;constructor(e,t){this.$EventHub=new Zu({},this),this.$store=wo({spiderUUID:t,originData:e})}$commit(e,...t){const r=this.$store[e](...t);return this.$EventHub.emit(e,...t),r}$on(...e){return this.$EventHub.on(...e)}$off(...e){return this.$EventHub.off(...e)}$isSameTask(e){return e.$store.spiderUUID===this.$store.spiderUUID&&e.$store.uuid===this.$store.uuid}$destroy(){this._belongTo=null,this.$commit("destroy"),this.$EventHub.off("*")}get[Symbol.toStringTag](){return"Task"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class tc extends ec{constructor(e,t="00000"){super(new Set(e),e?.[0]?._spiderUUID||t),this.#linkTask()}#linkTask(){this._originData.forEach((e=>{e._belongTo=this,e.$on("destroy",(()=>this.$removeLink(e)))}))}$commit(e,...t){const r=[];this._originData.forEach((n=>r.push(n.$commit(e,...t))));const n=this.$EventHub.emit(e,...t);return"start"===e&&this._output?n[0]:r}$destroy(){const e=[...this._originData];return this.$EventHub.emit("destroy"),e}$removeLink(e){this._originData.delete(e)}get[Symbol.toStringTag](){return"TaskGroup"}} + */class ec extends Ju{constructor(e,t="00000"){super({},e?.[0]?.spiderUUID||t),this.member=new Set(e),this.#linkTask()}#linkTask(){this.member.forEach((e=>{e._belongTo=this,e.$on("destroy",(()=>this.$removeLink(e)))}))}consume=!1;$commit(e,...t){const r=[];return this.member.forEach((n=>r.push(n.$commit(e,...t)))),this.$EventHub.emit(e,...t),this.consume?r[0]:("start"===e&&(this.consume=!0),r)}$destroy(){this.$EventHub.emit("destroy"),this.$store.destroy();const e=this.member;return this.member=null,e}$removeLink(e){this.member.delete(e)}get[Symbol.toStringTag](){return"TaskGroup"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const rc=new Ju,nc=rc.createSource$("TaskUpdate"),ic=rc.createSource$("ControlUpdate"); + */const tc=new Zu,rc=tc.createSource$("TaskUpdate"),nc=tc.createSource$("ControlUpdate"); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var oc={stateChange(e){this.status=e,rc.emit("ControlUpdate",{name:"stateChange",value:e})},"Flow:stop"(){this._stop=!0,rc.emit("ControlUpdate",{name:"flowStop"})},"Flow:start"(){console.log("jspider 开始运行"),this.status="pending",this._stop=!1,rc.emit("ControlUpdate",{name:"flowStart"})},"Task:success"(e){e.$commit("complete"),e instanceof tc&&e.$destroy(),rc.emit("ControlUpdate",{name:"TaskSuccess"})},"Task:error"(e){console.log(e)}}; +var ic={stateChange(e){this.status=e,tc.emit("ControlUpdate",{name:"stateChange",value:e})},"Flow:stop"(){this._stop=!0,tc.emit("ControlUpdate",{name:"flowStop"})},"Flow:start"(){console.log("jspider 开始运行"),this.status="pending",this._stop=!1,tc.emit("ControlUpdate",{name:"flowStart"})},"Task:success"(e){e.$commit("complete"),e instanceof ec&&e.$destroy(),tc.emit("ControlUpdate",{name:"TaskSuccess"})},"Task:error"(e){console.log(e)}}; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */function ac(){const e=this.$store.$backup();rc.emit("TaskUpdate",e)}class sc{#Tasks=new Map;viewModel=[];createTask(e,t){const r=new ec(e,t);this.#Tasks.set(r.uuid,r);const n=this;return r.$on({start:ac,success:ac,complete:ac,error:ac,destroy(){n.#Tasks.delete(this.uuid)}}),this.viewModel.push(r.$store),r}} + */function oc(){const e=this.$store.$backup();tc.emit("TaskUpdate",e)}class ac{#Tasks=new Map;viewModel=[];createTask(e,t){const r=new Ju(e,t);this.#Tasks.set(r.uuid,r);const n=this;return r.$on({start:oc,success:oc,complete:oc,error:oc,destroy(){n.#Tasks.delete(this.uuid)}}),this.viewModel.push(r.$store),r}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class uc{QueuePromise=Promise.resolve();enQueue(...e){return this.QueuePromise=e.reduce(((e,t)=>e.then(t)),this.QueuePromise),this}} + */class sc{QueuePromise=Promise.resolve();enQueue(...e){return this.QueuePromise=e.reduce(((e,t)=>e.then(t)),this.QueuePromise),this}} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -285,12 +285,12 @@ var oc={stateChange(e){this.status=e,rc.emit("ControlUpdate",{name:"stateChange" * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -function cc(e){return yo(e,yo.URL)} +function uc(e){return yo(e,yo.URL)} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class lc{constructor(e){this.Plugins=e}UUID=null;operator=null;pluginUUIDMap=new Map;#PluginQueue=new uc;preparePipeline(){let e="";const t=this.Plugins.map(((t,r)=>(e+=t.main.toString(),t.init instanceof Function&&this.#PluginQueue.enQueue(t.init),t.initUUID(r),this.pluginUUIDMap.set(t.uuid,t?.name||t.uuid),t.operator(this))));return this.operator=Fo(...t),this.UUID=cc(e),this.#PluginQueue.QueuePromise}} + */class cc{constructor(e){this.Plugins=e}UUID=null;operator=null;pluginUUIDMap=new Map;#PluginQueue=new sc;preparePipeline(){let e="";const t=this.Plugins.map(((t,r)=>(e+=(t?.main||t.operator).toString(),t.init instanceof Function&&this.#PluginQueue.enQueue(t.init),t.initUUID(r),this.pluginUUIDMap.set(t.uuid,t?.name||t.uuid),t.operator(this))));return this.operator=zo(...t),this.UUID=uc(e),this.#PluginQueue.QueuePromise}} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -301,7 +301,7 @@ function cc(e){return yo(e,yo.URL)} * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var fc=new class{status="free";#runningQueue=new uc;_stop=!1;spiderSource$=null;_pipeline=null;TaskManager=new sc;constructor(){this.$EventHub=new Ju(oc,this)}_createLogicLine(){var e,t;this.spiderSource$=this.$EventHub.createSource$("Flow:input").pipe((e=this.$EventHub.createSource$("Flow:stop"),t=this.$EventHub.createSource$("Flow:start"),r=>new Lo((n=>{const i=new Set;let o=!1;const a=r.subscribe((e=>{o?i.add(e):n.next(e)}),la,(()=>{i.forEach((e=>n.next(e))),n.complete()})),s=e.subscribe((()=>{o=t.subscribe((()=>{i.forEach((e=>n.next(e))),i.clear(),o.unsubscribe(),o=!1}))}));return()=>{i.clear(),a.unsubscribe(),s.unsubscribe(),o&&o.unsubscribe()}}))),this._pipeline.operator),this.spiderSource$.subscribe((e=>this.$EventHub.emit("Task:success",e)),(e=>this.$EventHub.emit("Task:error",e)),(()=>this.$EventHub.emit("Flow:complete"))),this.$EventHub.emit("Flow:stop")}pipeline(...e){const t=new lc(e);if("free"!==this.status)throw new Error("在运行阶段是不能够进行操作的哦");this.$EventHub.emit("stateChange","preparing"),this._pipeline=t,this.#runningQueue.enQueue((()=>this._pipeline.preparePipeline()),(()=>{this.$EventHub.emit("Spider:clearFlow"),this._createLogicLine(),this.$EventHub.emit("stateChange","free")}))}createFlow(e,{fromBackup:t=!1}={}){return this.#runningQueue.enQueue((()=>{e.forEach((e=>{if(!this._pipeline)throw new Error("没有创建pipeline");const r=this.TaskManager.createTask(e,this._pipeline.UUID);t&&r.$store.$import(e),this.$EventHub.emit("Flow:input",r)}))}))}startFlow(){this.#runningQueue.enQueue((()=>{this.$EventHub.emit("Flow:start")}))}stopFlow(){this.$EventHub.emit("Flow:stop")}};class pc extends class{constructor({tasks:e=!1,controlPanel:t=!1}={}){this.config={tasks:e,controlPanel:t},e&&this.#subscriber.push(nc.subscribe((e=>this._update(e)))),t&&this.#subscriber.push(ic.subscribe((e=>this._change(e))))}config={};#subscriber=[];$destroy(){this.#subscriber.forEach((e=>{e.unsubscribe()}))}}{constructor(e){super(Object.assign(e,{tasks:!0,controlPanel:!0}))}tasks=[];#uuidArray=[];_update(e){const t=this.#uuidArray.indexOf(e.uuid);-1===t?(this.#uuidArray.push(e.uuid),this.tasks.push(e)):this.tasks.splice(t,1,e)}_change({name:e,value:t=""}){}} +var lc=new class{status="free";#runningQueue=new sc;_stop=!1;spiderSource$=null;_pipeline=null;TaskManager=new ac;constructor(){this.$EventHub=new Zu(ic,this)}_createLogicLine(){var e,t;this.spiderSource$=this.$EventHub.createSource$("Flow:input").pipe((e=this.$EventHub.createSource$("Flow:stop"),t=this.$EventHub.createSource$("Flow:start"),r=>new Lo((n=>{const i=new Set;let o=!1;const a=r.subscribe((e=>{o?i.add(e):n.next(e)}),la,(()=>{i.forEach((e=>n.next(e))),i.clear(),n.complete()})),s=e.subscribe((()=>{o=t.subscribe((()=>{i.forEach((e=>n.next(e))),i.clear(),o.unsubscribe(),o=!1}))}));return()=>{i.clear(),a.unsubscribe(),s.unsubscribe(),o&&o.unsubscribe()}}))),this._pipeline.operator),this.spiderSource$.subscribe((e=>this.$EventHub.emit("Task:success",e)),(e=>this.$EventHub.emit("Task:error",e)),(()=>this.$EventHub.emit("Flow:complete"))),this.$EventHub.emit("Flow:stop")}pipeline(...e){const t=new cc(e);if("free"!==this.status)throw new Error("在运行阶段是不能够进行操作的哦");this.$EventHub.emit("stateChange","preparing"),this._pipeline=t,this.#runningQueue.enQueue((()=>this._pipeline.preparePipeline()),(()=>{this.$EventHub.emit("Spider:clearFlow"),this._createLogicLine(),this.$EventHub.emit("stateChange","free")}))}createFlow(e,{fromBackup:t=!1}={}){return this.#runningQueue.enQueue((()=>{e.forEach((e=>{if(!this._pipeline)throw new Error("没有创建pipeline");const r=this.TaskManager.createTask(e,this._pipeline.UUID);t&&r.$store.$import(e),this.$EventHub.emit("Flow:input",r)}))}))}startFlow(){this.#runningQueue.enQueue((()=>{this.$EventHub.emit("Flow:start")}))}stopFlow(){this.$EventHub.emit("Flow:stop")}};class fc extends class{constructor({tasks:e=!1,controlPanel:t=!1}={}){this.config={tasks:e,controlPanel:t},e&&this.#subscriber.push(rc.subscribe((e=>this._update(e)))),t&&this.#subscriber.push(nc.subscribe((e=>this._change(e))))}config={};#subscriber=[];$destroy(){this.#subscriber.forEach((e=>{e.unsubscribe()}))}}{constructor(e){super(Object.assign(e,{tasks:!0,controlPanel:!0}))}tasks=[];#uuidArray=[];_update(e){const t=this.#uuidArray.indexOf(e.uuid);-1===t?(this.#uuidArray.push(e.uuid),this.tasks.push(e)):this.tasks.splice(t,1,e)}_change({name:e,value:t=""}){}} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -312,28 +312,27 @@ var fc=new class{status="free";#runningQueue=new uc;_stop=!1;spiderSource$=null; * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -class hc extends Error{constructor(e){super(e),this.name="PluginError"}}class bc extends Error{constructor(e){super(e),this.name="FlowError"}} +class pc extends Error{constructor(e){super(e),this.name="PluginError"}}class hc extends Error{constructor(e){super(e),this.name="FlowError"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class dc{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=cc(this.main.toString()+e)}TaskStarter(e){return ua(e).pipe(qu((e=>ua(e).pipe(fa((e=>[e.$commit("start",this.uuid),e._originData])),qu((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Lo?Oa(r):ua(r)})),fa((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),Cu(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new hc(r);return na}throw new hc(t[0])})),Qu((e=>this.complete&&this.complete(e))))}operator(e){return Fo(qu((e=>this.TaskStarter(e))))}}function vc(e,t={}){if(e instanceof Function)return new dc(Object.assign(t,{main:e}));if(e instanceof Object)return new dc(e);throw new hc("Plugin 必须是一个函数或者是 Plugin 描述对象")} + */class bc{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=uc((this?.main||this.operator).toString()+e)}TaskStarter(e){return ua(e).pipe(Ku((e=>ua(e).pipe(fa((e=>[e.$commit("start",this.uuid),e._originData])),Ku((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Lo?Oa(r):ua(r)})),fa((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),Iu(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new pc(r);return na}throw new pc(t[0])})),Yu((e=>this.complete&&this.complete(e))))}operator(e){return zo(Ku((e=>this.TaskStarter(e))))}}function dc(e,t={}){if(e instanceof Function)return new bc(Object.assign(t,{main:e}));if(e instanceof Object)return new bc(e);throw new pc("Plugin 必须是一个函数或者是 Plugin 描述对象")} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const yc=(e,t)=>{return Fo((r=r=>r.pipe(function(e,t){var r=!1;return arguments.length>=2&&(r=!0),function(n){return n.lift(new zu(e,t,r))}}(((t,r)=>{if(console.log("尝试次数",t,r),t>=e)throw new bc("超出尝试次数",r);return t+1}),0),Vu(((...e)=>{switch(typeof t){case"string":case"number":return Na(parseInt(t,10));case"function":return Na(t(...e));default:throw new bc("您输入的 delay 错误")}}))),function(e){return e.lift(new Hu(r,e))})); + */const vc=(e,t)=>{return zo((r=r=>r.pipe(function(e,t){var r=!1;return arguments.length>=2&&(r=!0),function(n){return n.lift(new zu(e,t,r))}}(((t,r)=>{if(console.log("尝试次数",t,r),t>=e)throw new hc("超出尝试次数",r);return t+1}),0),Nu(((...e)=>{switch(typeof t){case"string":case"number":return Na(parseInt(t,10));case"function":return Na(t(...e));default:throw new hc("您输入的 delay 错误")}}))),function(e){return e.lift(new $u(r,e))})); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */var r};function gc({url:e,options:t={}}){const{returnType:r="json"}=this.options;return console.log("- 爬取 ",e),fetch(e,t).then((e=>{if(!e.ok)throw Error(e.statusText); + */var r};function yc(e,{retry:t=3,buffer:r=3,delay:n=1e3,retryDelay:i=300,handleError:o=function(e,t){throw new Error(e,t)}}={}){return zo(function(e){var t=arguments.length,r=ca;ia(arguments[arguments.length-1])&&(r=arguments[arguments.length-1],t--);var n=null;t>=2&&(n=arguments[1]);var i=Number.POSITIVE_INFINITY;return t>=3&&(i=arguments[2]),function(t){return t.lift(new Pu(e,n,i,r))}}(1e3,void 0,r),Ca((e=>e.length)),Nu(((e,t)=>Na(t*n))),Aa((e=>Oa(e))),Du((r=>ua(r).pipe(Aa((t=>e(t))),vc(t,i),Iu(((...e)=>(o instanceof Function?o(...e):o)||na))))))} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -return function(e,t){const r=e.headers.get("content-type")||"";return t&&"auto"!==t?t?e[t]():e.json():/text|html|rtf|xml/.test(r)?e.text():/json/.test(r)?e.json():/arrayBuffer/.test(r)?e.arrayBuffer():e.buffer?e.buffer():e.blob()}(e,r)})).then((t=>(console.log(`${e} 爬取成功`),t))).catch((e=>{throw e}))}function mc(e){throw e} + */function gc({url:e,options:t={}}){const{returnType:r="json"}=this.options;return console.log("- 爬取 ",e),fetch(e,Object.assign({cache:"force-cache"},t)).then((e=>{if(!e.ok)throw Error(e.statusText);return function(e,t){const r=e.headers.get("content-type")||"";return t&&"auto"!==t?t?e[t]():e.json():/text|html|rtf|xml/.test(r)?e.text():/json/.test(r)?e.json():/arrayBuffer/.test(r)?e.arrayBuffer():e.buffer?e.buffer():e.blob()}(e,r)})).then((t=>(console.log(`${e} 爬取成功`),t))).catch((e=>{throw e}))}function mc(e){throw e} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -344,7 +343,7 @@ function _c(e,t){return e instanceof File?e:e instanceof Blob?(e.name=t,e):new F * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const wc={main:Promise.resolve(!0),add(e){this.main.then((()=>Oc(e)))}},Oc=function(e){const t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=e.name,t.click(),URL.revokeObjectURL(t.href),t.remove(),console.log("%c 下载完成","color:green")},jc=(e,{DownloadFileName:t},r)=>{const n=_c(e,t||("string"==typeof url?r.url.replace(/[^\/]*?\//g,""):""));return wc.add(n),null},Pc={script:e=>new Promise(((t,r)=>{const n=document.createElement("script");n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),n.remove(),t()},n.onerror=e=>r(e),document.body.append(n)})),css:e=>new Promise(((t,r)=>{const n=document.createElement("style");n.rel="stylesheet",n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),t()},n.onerror=e=>r(e),document.body.append(n)}))}; + */const wc={main:Promise.resolve(!0),add(e){this.main.then((()=>Oc(e)))}},Oc=function(e){const t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=e.name,t.click(),URL.revokeObjectURL(t.href),t.remove(),console.log("%c 下载完成","color:green")},jc=(e,{DownloadFileName:t}={},r)=>{const n=_c(e,t||("string"==typeof url?r.url.replace(/[^\/]*?\//g,""):""));return wc.add(n),null},Pc={script:e=>new Promise(((t,r)=>{const n=document.createElement("script");n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),n.remove(),t()},n.onerror=e=>r(e),document.body.append(n)})),css:e=>new Promise(((t,r)=>{const n=document.createElement("style");n.rel="stylesheet",n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),t()},n.onerror=e=>r(e),document.body.append(n)}))}; /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -397,7 +396,7 @@ let Rc;function Uc(){return Cc("jszip").then((()=>{Rc=window.JSZip}))} * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -class Fc extends ec{constructor(e,t="00000"){super(new Set(e),e?.[0]?._spiderUUID||t),this.#linkTask()}#linkTask(){this._originData.forEach((e=>{e._belongTo=this,e.$on("destroy",(()=>this.$removeLink(e)))}))}$commit(e,...t){const r=[];this._originData.forEach((n=>r.push(n.$commit(e,...t))));const n=this.$EventHub.emit(e,...t);return"start"===e&&this._output?n[0]:r}$destroy(){const e=[...this._originData];return this.$EventHub.emit("destroy"),e}$removeLink(e){this._originData.delete(e)}get[Symbol.toStringTag](){return"TaskGroup"}} +function zc(e=3,t=1e3){return r=>new Lo((n=>{const i=new Set;let o=0;const a=()=>{i.size&&(n.next([...i]),i.clear())},s=r.subscribe((r=>{switch(console.log(o),o&&(clearTimeout(o),o=0),i.size){case 0:return i.add(r);case e-1:return i.add(r),a();default:return o=setTimeout(a,t),i.add(r)}}),la,(()=>{a(),n.complete()}));return()=>{i.clear(),s.unsubscribe()}}))} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -408,7 +407,12 @@ class Fc extends ec{constructor(e,t="00000"){super(new Set(e),e?.[0]?._spiderUUI * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var zc=Object.freeze({__proto__:null,Request:function(e={}){return vc({init(){},name:"Request",main:gc,options:e,operator(){const{delay:e=200,buffer:t=3,retry:r=3,handleError:n=null}=this.options;return i=>i.pipe(function(e,{retry:t=3,buffer:r=3,delay:n=1e3,retryDelay:i=300,handleError:o=function(e,t){throw new Error(e,t)}}={}){return Fo(Pu(1e3,void 0,r),Ca((e=>e.length)),Vu(((e,t)=>Na(t*n))),Aa((e=>Oa(e))),Nu((r=>ua(r).pipe(Aa((t=>e(t))),yc(t,i),Cu(((...e)=>(o instanceof Function?o(...e):o)||na))))))}((e=>this.TaskStarter(e)),{delay:e,buffer:t,retry:r,handleError:n||mc}))}})},Download:function(e={}){return vc({name:"Download",main:jc,options:e})},ExcelHelper:function(e,t={}){return vc({name:"ExcelHelper",init:Dc,options:t,main(t){const{fileName:r="result",XLSXOptions:n={}}=this.options;return e instanceof Function&&(t=e(t)),Vc(t,`${r}-${(new Date).getTime()}`,n)}})},ZipFile:function(e={}){return e.zipFileName||(e.zipFileName=(new Date).getTime()),vc({init:Uc,name:"zipFile",main(e){const{zipFileName:t}=this.options;return async function(e,t){const r=new Rc;e.forEach((e=>r.file(e.name,e)));const n=await r.generateAsync({type:"blob"});return n.name=`${t}-${Mc++}.zip`,n}(e.map((e=>_c(e,t))),t)},options:e,operator(){const{chunk:e=3}=this.options;return t=>t.pipe(Pu(5e3,void 0,e),Ca((e=>e.length)),Nu((e=>this.TaskStarter(new Fc(e),this.uuid))))}})}}); +var Fc=Object.freeze({__proto__:null,Request:function(e={}){return dc({init(){},name:"Request",main:gc,options:e,operator(){const{delay:e=200,buffer:t=1,retry:r=3,handleError:n=null}=this.options;return i=>i.pipe(yc((e=>this.TaskStarter(e)),{delay:e,buffer:t,retry:r,handleError:n||mc}))}})},Download:function(e={}){return dc({name:"Download",main:jc,options:e})},ExcelHelper:function(e,t={}){return dc({name:"ExcelHelper",init:Dc,options:t,main(t){const{fileName:r="result",XLSXOptions:n={}}=this.options;return e instanceof Function&&(t=e(t)),Vc(t,`${r}-${(new Date).getTime()}`,n)}})},ZipFile:function(e={}){return e.zipFileName||(e.zipFileName=(new Date).getTime()),dc({init:Uc,name:"zipFile",main(e){const{zipFileName:t}=this.options;return async function(e,t){const r=new Rc;e.forEach((e=>r.file(e.name,e)));const n=await r.generateAsync({type:"blob"});return n.name=`${t}-${Mc++}.zip`,n} +/** + * @license + * Copyright 2021 KonghaYao 江夏尧 + * SPDX-License-Identifier: Apache-2.0 + */(_c(e,t),t)},options:e})},Combine:function(e,t=1e3,r){return dc({name:"Combine",main:r,operator(){return n=>n.pipe(zc(e,t),Ca((e=>e.length)),Du((e=>{const t=ua(new ec(e));return r instanceof Function?t.pipe(Du((e=>this.TaskStarter(e)))):t})))}})},Break:function(){return dc({name:"Break",options:options,operator:()=>e=>e.pipe(Du((e=>e instanceof ec?from(e.$destroy()):ua(e))))})}}); /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -478,10 +482,10 @@ var Zc=Object.freeze({__proto__:null,$antiDebugger:function(){Function.prototype * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class Jc{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=cc(this.main.toString()+e)}TaskStarter(e){return ua(e).pipe(qu((e=>ua(e).pipe(fa((e=>[e.$commit("start",this.uuid),e._originData])),qu((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Lo?Oa(r):ua(r)})),fa((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),Cu(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new hc(r);return na}throw new hc(t[0])})),Qu((e=>this.complete&&this.complete(e))))}operator(e){return Fo(qu((e=>this.TaskStarter(e))))}} + */class Jc{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=uc((this?.main||this.operator).toString()+e)}TaskStarter(e){return ua(e).pipe(Ku((e=>ua(e).pipe(fa((e=>[e.$commit("start",this.uuid),e._originData])),Ku((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Lo?Oa(r):ua(r)})),fa((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),Iu(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new pc(r);return na}throw new pc(t[0])})),Yu((e=>this.complete&&this.complete(e))))}operator(e){return zo(Ku((e=>this.TaskStarter(e))))}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var el=Object.assign(class{constructor({logEvery:e=!1}={}){this.config={logEvery:e},this.views=new pc(this.config)}crawl(...e){return fc.createFlow(e.flat()),this}pipeline(...e){return fc.pipeline(...e),this}start(){return fc.startFlow(),this}stop(){return fc.stopFlow(),this}},Zc,{plugins:zc,Plugin:function(e,t={}){if(e instanceof Function)return new Jc(Object.assign(t,{main:e}));if(e instanceof Object)return new Jc(e);throw new hc("Plugin 必须是一个函数或者是 Plugin 描述对象")},Task:ec,TaskGroup:tc,version:"3.1.8",buildDate:new Date(1628300553915)});module.exports=el; +var el=Object.assign(class{constructor({logEvery:e=!1}={}){this.config={logEvery:e},this.views=new fc(this.config)}crawl(...e){return lc.createFlow(e.flat()),this}pipeline(...e){return lc.pipeline(...e),this}start(){return lc.startFlow(),this}stop(){return lc.stopFlow(),this}},Zc,{plugins:Fc,Plugin:function(e,t={}){if(e instanceof Function)return new Jc(Object.assign(t,{main:e}));if(e instanceof Object)return new Jc(e);throw new pc("Plugin 必须是一个函数或者是 Plugin 描述对象")},Task:Ju,TaskGroup:ec,version:"3.2.2",buildDate:new Date(1628382223946)});module.exports=el; diff --git a/dist/JSpider.esm.min.js b/dist/JSpider.esm.min.js index 681d458..9d46fc6 100644 --- a/dist/JSpider.esm.min.js +++ b/dist/JSpider.esm.min.js @@ -1,18216 +1,491 @@ - -(function(l, r) { if (!l || l.getElementById('livereloadscript')) return; r = l.createElement('script'); r.async = 1; r.src = '//' + (self.location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1'; r.id = 'livereloadscript'; l.getElementsByTagName('head')[0].appendChild(r) })(self.document); -function die(error) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - throw new Error(typeof error === "number" ? "[MobX] minified error nr: " + error + (args.length ? " " + args.map(String).join(",") : "") + ". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts" : "[MobX] " + error); -} - -var mockGlobal = {}; -function getGlobal() { - if (typeof globalThis !== "undefined") { - return globalThis; - } - - if (typeof window !== "undefined") { - return window; - } - - if (typeof global !== "undefined") { - return global; - } - - if (typeof self !== "undefined") { - return self; - } - - return mockGlobal; -} - -var assign = Object.assign; -var getDescriptor = Object.getOwnPropertyDescriptor; -var defineProperty$2 = Object.defineProperty; -var objectPrototype = Object.prototype; -var EMPTY_ARRAY$1 = []; -Object.freeze(EMPTY_ARRAY$1); -var EMPTY_OBJECT$1 = {}; -Object.freeze(EMPTY_OBJECT$1); -var hasProxy = typeof Proxy !== "undefined"; -var plainObjectString$1 = /*#__PURE__*/Object.toString(); -function assertProxies() { - if (!hasProxy) { - die("Proxy not available"); - } -} -/** - * Makes sure that the provided function is invoked at most once. - */ - -function once(func) { - var invoked = false; - return function () { - if (invoked) return; - invoked = true; - return func.apply(this, arguments); - }; -} -var noop$1 = function noop() {}; -function isFunction$2(fn) { - return typeof fn === "function"; -} -function isStringish(value) { - var t = typeof value; - - switch (t) { - case "string": - case "symbol": - case "number": - return true; - } - - return false; -} -function isObject$2(value) { - return value !== null && typeof value === "object"; -} -function isPlainObject$1(value) { - var _proto$constructor; - - if (!isObject$2(value)) return false; - var proto = Object.getPrototypeOf(value); - if (proto == null) return true; - return ((_proto$constructor = proto.constructor) == null ? void 0 : _proto$constructor.toString()) === plainObjectString$1; -} // https://stackoverflow.com/a/37865170 - -function isGenerator(obj) { - var constructor = obj == null ? void 0 : obj.constructor; - if (!constructor) return false; - if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) return true; - return false; -} -function addHiddenProp(object, propName, value) { - defineProperty$2(object, propName, { - enumerable: false, - writable: true, - configurable: true, - value: value - }); -} -function addHiddenFinalProp$1(object, propName, value) { - defineProperty$2(object, propName, { - enumerable: false, - writable: false, - configurable: true, - value: value - }); -} -function createInstanceofPredicate(name, theClass) { - var propName = "isMobX" + name; - theClass.prototype[propName] = true; - return function (x) { - return isObject$2(x) && x[propName] === true; - }; -} -function isES6Map(thing) { - return thing instanceof Map; -} -function isES6Set(thing) { - return thing instanceof Set; -} -var hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefined"; -/** - * Returns the following: own enumerable keys and symbols. - */ - -function getPlainObjectKeys(object) { - var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway... - - if (!hasGetOwnPropertySymbols) return keys; - var symbols = Object.getOwnPropertySymbols(object); - if (!symbols.length) return keys; - return [].concat(keys, symbols.filter(function (s) { - return objectPrototype.propertyIsEnumerable.call(object, s); - })); -} // From Immer utils -// Returns all own keys, including non-enumerable and symbolic - -var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) { - return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj)); -} : -/* istanbul ignore next */ -Object.getOwnPropertyNames; -function toPrimitive(value) { - return value === null ? null : typeof value === "object" ? "" + value : value; -} -function hasProp(target, prop) { - return objectPrototype.hasOwnProperty.call(target, prop); -} // From Immer utils - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) { - // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274 - var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up - - ownKeys(target).forEach(function (key) { - res[key] = getDescriptor(target, key); - }); - return res; -}; - -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} - -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; -} - -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; -} - -function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); -} - -function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; -} - -function _createForOfIteratorHelperLoose(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -var storedAnnotationsSymbol = /*#__PURE__*/Symbol("mobx-stored-annotations"); -/** - * Creates a function that acts as - * - decorator - * - annotation object - */ - -function createDecoratorAnnotation(annotation) { - function decorator(target, property) { - storeAnnotation(target, property, annotation); - } - - return Object.assign(decorator, annotation); -} -/** - * Stores annotation to prototype, - * so it can be inspected later by `makeObservable` called from constructor - */ - -function storeAnnotation(prototype, key, annotation) { - if (!hasProp(prototype, storedAnnotationsSymbol)) { - addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol])); - } // @override must override something - - if (!isOverride(annotation)) { - prototype[storedAnnotationsSymbol][key] = annotation; - } -} -/** - * Collects annotations from prototypes and stores them on target (instance) - */ - - -function collectStoredAnnotations(target) { - if (!hasProp(target, storedAnnotationsSymbol)) { - - - addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol])); - } - - return target[storedAnnotationsSymbol]; -} - -var $mobx = /*#__PURE__*/Symbol("mobx administration"); -var Atom = /*#__PURE__*/function () { - // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed - - /** - * Create a new atom. For debugging purposes it is recommended to give it a name. - * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management. - */ - function Atom(name_) { - if (name_ === void 0) { - name_ = "Atom"; - } - - this.name_ = void 0; - this.isPendingUnobservation_ = false; - this.isBeingObserved_ = false; - this.observers_ = new Set(); - this.diffValue_ = 0; - this.lastAccessedBy_ = 0; - this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_; - this.onBOL = void 0; - this.onBUOL = void 0; - this.name_ = name_; - } // onBecomeObservedListeners - - - var _proto = Atom.prototype; - - _proto.onBO = function onBO() { - if (this.onBOL) { - this.onBOL.forEach(function (listener) { - return listener(); - }); - } - }; - - _proto.onBUO = function onBUO() { - if (this.onBUOL) { - this.onBUOL.forEach(function (listener) { - return listener(); - }); - } - } - /** - * Invoke this method to notify mobx that your atom has been used somehow. - * Returns true if there is currently a reactive context. - */ - ; - - _proto.reportObserved = function reportObserved$1() { - return reportObserved(this); - } - /** - * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate. - */ - ; - - _proto.reportChanged = function reportChanged() { - startBatch(); - propagateChanged(this); - endBatch(); - }; - - _proto.toString = function toString() { - return this.name_; - }; - - return Atom; -}(); -var isAtom = /*#__PURE__*/createInstanceofPredicate("Atom", Atom); -function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { - if (onBecomeObservedHandler === void 0) { - onBecomeObservedHandler = noop$1; - } - - if (onBecomeUnobservedHandler === void 0) { - onBecomeUnobservedHandler = noop$1; - } - - var atom = new Atom(name); // default `noop` listener will not initialize the hook Set - - if (onBecomeObservedHandler !== noop$1) { - onBecomeObserved(atom, onBecomeObservedHandler); - } - - if (onBecomeUnobservedHandler !== noop$1) { - onBecomeUnobserved(atom, onBecomeUnobservedHandler); - } - - return atom; -} - -function identityComparer(a, b) { - return a === b; -} - -function structuralComparer(a, b) { - return deepEqual(a, b); -} - -function shallowComparer(a, b) { - return deepEqual(a, b, 1); -} - -function defaultComparer(a, b) { - return Object.is(a, b); -} - -var comparer = { - identity: identityComparer, - structural: structuralComparer, - "default": defaultComparer, - shallow: shallowComparer -}; - -function deepEnhancer(v, _, name) { - // it is an observable already, done - if (isObservable(v)) return v; // something that can be converted and mutated? - - if (Array.isArray(v)) return observable$1.array(v, { - name: name - }); - if (isPlainObject$1(v)) return observable$1.object(v, undefined, { - name: name - }); - if (isES6Map(v)) return observable$1.map(v, { - name: name - }); - if (isES6Set(v)) return observable$1.set(v, { - name: name - }); - - if (typeof v === "function" && !isAction(v) && !isFlow(v)) { - if (isGenerator(v)) { - return flow(v); - } else { - return autoAction(name, v); - } - } - - return v; -} -function shallowEnhancer(v, _, name) { - if (v === undefined || v === null) return v; - if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) return v; - if (Array.isArray(v)) return observable$1.array(v, { - name: name, - deep: false - }); - if (isPlainObject$1(v)) return observable$1.object(v, undefined, { - name: name, - deep: false - }); - if (isES6Map(v)) return observable$1.map(v, { - name: name, - deep: false - }); - if (isES6Set(v)) return observable$1.set(v, { - name: name, - deep: false - }); -} -function referenceEnhancer(newValue) { - // never turn into an observable - return newValue; -} -function refStructEnhancer(v, oldValue) { - if (deepEqual(v, oldValue)) return oldValue; - return v; -} - -var OVERRIDE = "override"; -function isOverride(annotation) { - return annotation.annotationType_ === OVERRIDE; -} - -function createActionAnnotation(name, options) { - return { - annotationType_: name, - options_: options, - make_: make_$1, - extend_: extend_$1 - }; -} - -function make_$1(adm, key, descriptor, source) { - var _this$options_; - - // bound - if ((_this$options_ = this.options_) == null ? void 0 : _this$options_.bound) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 1 - /* Break */ - ; - } // own - - - if (source === adm.target_) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 2 - /* Continue */ - ; - } // prototype - - - if (isAction(descriptor.value)) { - // A prototype could have been annotated already by other constructor, - // rest of the proto chain must be annotated already - return 1 - /* Break */ - ; - } - - var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false); - defineProperty$2(source, key, actionDescriptor); - return 2 - /* Continue */ - ; -} - -function extend_$1(adm, key, descriptor, proxyTrap) { - var actionDescriptor = createActionDescriptor(adm, this, key, descriptor); - return adm.defineProperty_(key, actionDescriptor, proxyTrap); -} - -function assertActionDescriptor(adm, _ref, key, _ref2) { - _ref.annotationType_; - _ref2.value; -} - -function createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes -safeDescriptors) { - var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3; - - if (safeDescriptors === void 0) { - safeDescriptors = globalState.safeDescriptors; - } - - assertActionDescriptor(adm, annotation, key, descriptor); - var value = descriptor.value; - - if ((_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.bound) { - var _adm$proxy_; - - value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); - } - - return { - value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false), - // Non-configurable for classes - // prevents accidental field redefinition in subclass - configurable: safeDescriptors ? adm.isPlainObject_ : true, - // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058 - enumerable: false, - // Non-obsevable, therefore non-writable - // Also prevents rewriting in subclass constructor - writable: safeDescriptors ? false : true - }; -} - -function createFlowAnnotation(name, options) { - return { - annotationType_: name, - options_: options, - make_: make_$2, - extend_: extend_$2 - }; -} - -function make_$2(adm, key, descriptor, source) { - var _this$options_; - - // own - if (source === adm.target_) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 2 - /* Continue */ - ; - } // prototype - // bound - must annotate protos to support super.flow() - - - if (((_this$options_ = this.options_) == null ? void 0 : _this$options_.bound) && !isFlow(adm.target_[key])) { - if (this.extend_(adm, key, descriptor, false) === null) return 0 - /* Cancel */ - ; - } - - if (isFlow(descriptor.value)) { - // A prototype could have been annotated already by other constructor, - // rest of the proto chain must be annotated already - return 1 - /* Break */ - ; - } - - var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false); - defineProperty$2(source, key, flowDescriptor); - return 2 - /* Continue */ - ; -} - -function extend_$2(adm, key, descriptor, proxyTrap) { - var _this$options_2; - - var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound); - return adm.defineProperty_(key, flowDescriptor, proxyTrap); -} - -function assertFlowDescriptor(adm, _ref, key, _ref2) { - _ref.annotationType_; - _ref2.value; -} - -function createFlowDescriptor(adm, annotation, key, descriptor, bound, // provides ability to disable safeDescriptors for prototypes -safeDescriptors) { - if (safeDescriptors === void 0) { - safeDescriptors = globalState.safeDescriptors; - } - - assertFlowDescriptor(adm, annotation, key, descriptor); - var value = descriptor.value; - - if (bound) { - var _adm$proxy_; - - value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); - } - - return { - value: flow(value), - // Non-configurable for classes - // prevents accidental field redefinition in subclass - configurable: safeDescriptors ? adm.isPlainObject_ : true, - // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058 - enumerable: false, - // Non-obsevable, therefore non-writable - // Also prevents rewriting in subclass constructor - writable: safeDescriptors ? false : true - }; -} - -function createComputedAnnotation(name, options) { - return { - annotationType_: name, - options_: options, - make_: make_$3, - extend_: extend_$3 - }; -} - -function make_$3(adm, key, descriptor) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 1 - /* Break */ - ; -} - -function extend_$3(adm, key, descriptor, proxyTrap) { - assertComputedDescriptor(adm, this, key, descriptor); - return adm.defineComputedProperty_(key, _extends({}, this.options_, { - get: descriptor.get, - set: descriptor.set - }), proxyTrap); -} - -function assertComputedDescriptor(adm, _ref, key, _ref2) { - _ref.annotationType_; - _ref2.get; -} - -function createObservableAnnotation(name, options) { - return { - annotationType_: name, - options_: options, - make_: make_$4, - extend_: extend_$4 - }; -} - -function make_$4(adm, key, descriptor) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 1 - /* Break */ - ; -} - -function extend_$4(adm, key, descriptor, proxyTrap) { - var _this$options_$enhanc, _this$options_; - - assertObservableDescriptor(adm, this); - return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap); -} - -function assertObservableDescriptor(adm, _ref, key, descriptor) { - _ref.annotationType_; -} - -var AUTO = "true"; -var autoAnnotation = /*#__PURE__*/createAutoAnnotation(); -function createAutoAnnotation(options) { - return { - annotationType_: AUTO, - options_: options, - make_: make_$5, - extend_: extend_$5 - }; -} - -function make_$5(adm, key, descriptor, source) { - var _this$options_3, _this$options_4; - - // getter -> computed - if (descriptor.get) { - return computed.make_(adm, key, descriptor, source); - } // lone setter -> action setter - - - if (descriptor.set) { - // TODO make action applicable to setter and delegate to action.make_ - var set = createAction(key.toString(), descriptor.set); // own - - if (source === adm.target_) { - return adm.defineProperty_(key, { - configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true, - set: set - }) === null ? 0 - /* Cancel */ - : 2 - /* Continue */ - ; - } // proto - - - defineProperty$2(source, key, { - configurable: true, - set: set - }); - return 2 - /* Continue */ - ; - } // function on proto -> autoAction/flow - - - if (source !== adm.target_ && typeof descriptor.value === "function") { - var _this$options_2; - - if (isGenerator(descriptor.value)) { - var _this$options_; - - var flowAnnotation = ((_this$options_ = this.options_) == null ? void 0 : _this$options_.autoBind) ? flow.bound : flow; - return flowAnnotation.make_(adm, key, descriptor, source); - } - - var actionAnnotation = ((_this$options_2 = this.options_) == null ? void 0 : _this$options_2.autoBind) ? autoAction.bound : autoAction; - return actionAnnotation.make_(adm, key, descriptor, source); - } // other -> observable - // Copy props from proto as well, see test: - // "decorate should work with Object.create" - - - var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable$1.ref : observable$1; // if function respect autoBind option - - if (typeof descriptor.value === "function" && ((_this$options_4 = this.options_) == null ? void 0 : _this$options_4.autoBind)) { - var _adm$proxy_; - - descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); - } - - return observableAnnotation.make_(adm, key, descriptor, source); -} - -function extend_$5(adm, key, descriptor, proxyTrap) { - var _this$options_5, _this$options_6; - - // getter -> computed - if (descriptor.get) { - return computed.extend_(adm, key, descriptor, proxyTrap); - } // lone setter -> action setter - - - if (descriptor.set) { - // TODO make action applicable to setter and delegate to action.extend_ - return adm.defineProperty_(key, { - configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true, - set: createAction(key.toString(), descriptor.set) - }, proxyTrap); - } // other -> observable - // if function respect autoBind option - - - if (typeof descriptor.value === "function" && ((_this$options_5 = this.options_) == null ? void 0 : _this$options_5.autoBind)) { - var _adm$proxy_2; - - descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_); - } - - var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable$1.ref : observable$1; - return observableAnnotation.extend_(adm, key, descriptor, proxyTrap); -} - -// in the majority of cases - -var defaultCreateObservableOptions = { - deep: true, - name: undefined, - defaultDecorator: undefined, - proxy: true -}; -Object.freeze(defaultCreateObservableOptions); -function asCreateObservableOptions(thing) { - return thing || defaultCreateObservableOptions; -} -var observableAnnotation = /*#__PURE__*/createObservableAnnotation("observable"); -var observableRefAnnotation = /*#__PURE__*/createObservableAnnotation("observable.ref", { - enhancer: referenceEnhancer -}); -var observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation("observable.shallow", { - enhancer: shallowEnhancer -}); -var observableStructAnnotation = /*#__PURE__*/createObservableAnnotation("observable.struct", { - enhancer: refStructEnhancer -}); -var observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation); -function getEnhancerFromOptions(options) { - return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator); -} -function getAnnotationFromOptions(options) { - var _options$defaultDecor; - - return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined; -} -function getEnhancerFromAnnotation(annotation) { - var _annotation$options_$, _annotation$options_; - - return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer; -} -/** - * Turns an object, array or function into a reactive structure. - * @param v the value which should become observable. - */ - -function createObservable(v, arg2, arg3) { - // @observable someProp; - if (isStringish(arg2)) { - storeAnnotation(v, arg2, observableAnnotation); - return; - } // already observable - ignore - - - if (isObservable(v)) return v; // plain object - - if (isPlainObject$1(v)) return observable$1.object(v, arg2, arg3); // Array - - if (Array.isArray(v)) return observable$1.array(v, arg2); // Map - - if (isES6Map(v)) return observable$1.map(v, arg2); // Set - - if (isES6Set(v)) return observable$1.set(v, arg2); // other object - ignore - - if (typeof v === "object" && v !== null) return v; // anything else - - return observable$1.box(v, arg2); -} - -Object.assign(createObservable, observableDecoratorAnnotation); -var observableFactories = { - box: function box(value, options) { - var o = asCreateObservableOptions(options); - return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals); - }, - array: function array(initialValues, options) { - var o = asCreateObservableOptions(options); - return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name); - }, - map: function map(initialValues, options) { - var o = asCreateObservableOptions(options); - return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name); - }, - set: function set(initialValues, options) { - var o = asCreateObservableOptions(options); - return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name); - }, - object: function object(props, decorators, options) { - return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators); - }, - ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation), - shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation), - deep: observableDecoratorAnnotation, - struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation) -}; // eslint-disable-next-line - -var observable$1 = /*#__PURE__*/assign(createObservable, observableFactories); - -var COMPUTED = "computed"; -var COMPUTED_STRUCT = "computed.struct"; -var computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED); -var computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, { - equals: comparer.structural -}); -/** - * Decorator for class properties: @computed get value() { return expr; }. - * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`; - */ - -var computed = function computed(arg1, arg2) { - if (isStringish(arg2)) { - // @computed - return storeAnnotation(arg1, arg2, computedAnnotation); - } - - if (isPlainObject$1(arg1)) { - // @computed({ options }) - return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1)); - } // computed(expr, options?) - - var opts = isPlainObject$1(arg2) ? arg2 : {}; - opts.get = arg1; - opts.name || (opts.name = arg1.name || ""); - /* for generated name */ - - return new ComputedValue(opts); -}; -Object.assign(computed, computedAnnotation); -computed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation); - -var _getDescriptor$config, _getDescriptor; -// mobx versions - -var currentActionId = 0; -var nextActionId$1 = 1; -var isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, "name")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object - -var tmpNameDescriptor = { - value: "action", - configurable: true, - writable: false, - enumerable: false -}; -function createAction(actionName, fn, autoAction, ref) { - if (autoAction === void 0) { - autoAction = false; - } - - function res() { - return executeAction(actionName, autoAction, fn, ref || this, arguments); - } - - res.isMobxAction = true; - - if (isFunctionNameConfigurable) { - tmpNameDescriptor.value = actionName; - Object.defineProperty(res, "name", tmpNameDescriptor); - } - - return res; -} -function executeAction(actionName, canRunAsDerivation, fn, scope, args) { - var runInfo = _startAction(actionName, canRunAsDerivation); - - try { - return fn.apply(scope, args); - } catch (err) { - runInfo.error_ = err; - throw err; - } finally { - _endAction(runInfo); - } -} -function _startAction(actionName, canRunAsDerivation, // true for autoAction -scope, args) { - var notifySpy_ = "production" !== "production" ; - var startTime_ = 0; - - var prevDerivation_ = globalState.trackingDerivation; - var runAsAction = !canRunAsDerivation || !prevDerivation_; - startBatch(); - var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow - - if (runAsAction) { - untrackedStart(); - prevAllowStateChanges_ = allowStateChangesStart(true); - } - - var prevAllowStateReads_ = allowStateReadsStart(true); - var runInfo = { - runAsAction_: runAsAction, - prevDerivation_: prevDerivation_, - prevAllowStateChanges_: prevAllowStateChanges_, - prevAllowStateReads_: prevAllowStateReads_, - notifySpy_: notifySpy_, - startTime_: startTime_, - actionId_: nextActionId$1++, - parentActionId_: currentActionId - }; - currentActionId = runInfo.actionId_; - return runInfo; -} -function _endAction(runInfo) { - if (currentActionId !== runInfo.actionId_) { - die(30); - } - - currentActionId = runInfo.parentActionId_; - - if (runInfo.error_ !== undefined) { - globalState.suppressReactionErrors = true; - } - - allowStateChangesEnd(runInfo.prevAllowStateChanges_); - allowStateReadsEnd(runInfo.prevAllowStateReads_); - endBatch(); - if (runInfo.runAsAction_) untrackedEnd(runInfo.prevDerivation_); - - globalState.suppressReactionErrors = false; -} -function allowStateChanges(allowStateChanges, func) { - var prev = allowStateChangesStart(allowStateChanges); - - try { - return func(); - } finally { - allowStateChangesEnd(prev); - } -} -function allowStateChangesStart(allowStateChanges) { - var prev = globalState.allowStateChanges; - globalState.allowStateChanges = allowStateChanges; - return prev; -} -function allowStateChangesEnd(prev) { - globalState.allowStateChanges = prev; -} - -var _Symbol$toPrimitive; -_Symbol$toPrimitive = Symbol.toPrimitive; -var ObservableValue = /*#__PURE__*/function (_Atom) { - _inheritsLoose(ObservableValue, _Atom); - - function ObservableValue(value, enhancer, name_, notifySpy, equals) { - var _this; - - if (name_ === void 0) { - name_ = "ObservableValue"; - } - - if (equals === void 0) { - equals = comparer["default"]; - } - - _this = _Atom.call(this, name_) || this; - _this.enhancer = void 0; - _this.name_ = void 0; - _this.equals = void 0; - _this.hasUnreportedChange_ = false; - _this.interceptors_ = void 0; - _this.changeListeners_ = void 0; - _this.value_ = void 0; - _this.dehancer = void 0; - _this.enhancer = enhancer; - _this.name_ = name_; - _this.equals = equals; - _this.value_ = enhancer(value, undefined, name_); - - return _this; - } - - var _proto = ObservableValue.prototype; - - _proto.dehanceValue = function dehanceValue(value) { - if (this.dehancer !== undefined) return this.dehancer(value); - return value; - }; - - _proto.set = function set(newValue) { - this.value_; - newValue = this.prepareNewValue_(newValue); - - if (newValue !== globalState.UNCHANGED) { - - this.setNewValue_(newValue); - } - }; - - _proto.prepareNewValue_ = function prepareNewValue_(newValue) { - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this, - type: UPDATE, - newValue: newValue - }); - if (!change) return globalState.UNCHANGED; - newValue = change.newValue; - } // apply modifier - - - newValue = this.enhancer(newValue, this.value_, this.name_); - return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue; - }; - - _proto.setNewValue_ = function setNewValue_(newValue) { - var oldValue = this.value_; - this.value_ = newValue; - this.reportChanged(); - - if (hasListeners(this)) { - notifyListeners(this, { - type: UPDATE, - object: this, - newValue: newValue, - oldValue: oldValue - }); - } - }; - - _proto.get = function get() { - this.reportObserved(); - return this.dehanceValue(this.value_); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - if (fireImmediately) listener({ - observableKind: "value", - debugObjectName: this.name_, - object: this, - type: UPDATE, - newValue: this.value_, - oldValue: undefined - }); - return registerListener(this, listener); - }; - - _proto.raw = function raw() { - // used by MST ot get undehanced value - return this.value_; - }; - - _proto.toJSON = function toJSON() { - return this.get(); - }; - - _proto.toString = function toString() { - return this.name_ + "[" + this.value_ + "]"; - }; - - _proto.valueOf = function valueOf() { - return toPrimitive(this.get()); - }; - - _proto[_Symbol$toPrimitive] = function () { - return this.valueOf(); - }; - - return ObservableValue; -}(Atom); -var isObservableValue = /*#__PURE__*/createInstanceofPredicate("ObservableValue", ObservableValue); - -var _Symbol$toPrimitive$1; -/** - * A node in the state dependency root that observes other nodes, and can be observed itself. - * - * ComputedValue will remember the result of the computation for the duration of the batch, or - * while being observed. - * - * During this time it will recompute only when one of its direct dependencies changed, - * but only when it is being accessed with `ComputedValue.get()`. - * - * Implementation description: - * 1. First time it's being accessed it will compute and remember result - * give back remembered result until 2. happens - * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3. - * 3. When it's being accessed, recompute if any shallow dependency changed. - * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step. - * go to step 2. either way - * - * If at any point it's outside batch and it isn't observed: reset everything and go to 1. - */ - -_Symbol$toPrimitive$1 = Symbol.toPrimitive; -var ComputedValue = /*#__PURE__*/function () { - // nodes we are looking at. Our value depends on these nodes - // during tracking it's an array with new observed observers - // to check for cycles - // N.B: unminified as it is used by MST - - /** - * Create a new computed value based on a function expression. - * - * The `name` property is for debug purposes only. - * - * The `equals` property specifies the comparer function to use to determine if a newly produced - * value differs from the previous value. Two comparers are provided in the library; `defaultComparer` - * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure. - * Structural comparison can be convenient if you always produce a new aggregated object and - * don't want to notify observers if it is structurally the same. - * This is useful for working with vectors, mouse coordinates etc. - */ - function ComputedValue(options) { - this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; - this.observing_ = []; - this.newObserving_ = null; - this.isBeingObserved_ = false; - this.isPendingUnobservation_ = false; - this.observers_ = new Set(); - this.diffValue_ = 0; - this.runId_ = 0; - this.lastAccessedBy_ = 0; - this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - this.unboundDepsCount_ = 0; - this.value_ = new CaughtException(null); - this.name_ = void 0; - this.triggeredBy_ = void 0; - this.isComputing_ = false; - this.isRunningSetter_ = false; - this.derivation = void 0; - this.setter_ = void 0; - this.isTracing_ = TraceMode.NONE; - this.scope_ = void 0; - this.equals_ = void 0; - this.requiresReaction_ = void 0; - this.keepAlive_ = void 0; - this.onBOL = void 0; - this.onBUOL = void 0; - if (!options.get) die(31); - this.derivation = options.get; - this.name_ = options.name || ("ComputedValue"); - - if (options.set) { - this.setter_ = createAction("ComputedValue-setter", options.set); - } - - this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer["default"]); - this.scope_ = options.context; - this.requiresReaction_ = !!options.requiresReaction; - this.keepAlive_ = !!options.keepAlive; - } - - var _proto = ComputedValue.prototype; - - _proto.onBecomeStale_ = function onBecomeStale_() { - propagateMaybeChanged(this); - }; - - _proto.onBO = function onBO() { - if (this.onBOL) { - this.onBOL.forEach(function (listener) { - return listener(); - }); - } - }; - - _proto.onBUO = function onBUO() { - if (this.onBUOL) { - this.onBUOL.forEach(function (listener) { - return listener(); - }); - } - } - /** - * Returns the current value of this computed value. - * Will evaluate its computation first if needed. - */ - ; - - _proto.get = function get() { - if (this.isComputing_) die(32, this.name_, this.derivation); - - if (globalState.inBatch === 0 && // !globalState.trackingDerivatpion && - this.observers_.size === 0 && !this.keepAlive_) { - if (shouldCompute(this)) { - this.warnAboutUntrackedRead_(); - startBatch(); // See perf test 'computed memoization' - - this.value_ = this.computeValue_(false); - endBatch(); - } - } else { - reportObserved(this); - - if (shouldCompute(this)) { - var prevTrackingContext = globalState.trackingContext; - if (this.keepAlive_ && !prevTrackingContext) globalState.trackingContext = this; - if (this.trackAndCompute()) propagateChangeConfirmed(this); - globalState.trackingContext = prevTrackingContext; - } - } - - var result = this.value_; - if (isCaughtException(result)) throw result.cause; - return result; - }; - - _proto.set = function set(value) { - if (this.setter_) { - if (this.isRunningSetter_) die(33, this.name_); - this.isRunningSetter_ = true; - - try { - this.setter_.call(this.scope_, value); - } finally { - this.isRunningSetter_ = false; - } - } else die(34, this.name_); - }; - - _proto.trackAndCompute = function trackAndCompute() { - // N.B: unminified as it is used by MST - var oldValue = this.value_; - var wasSuspended = - /* see #1208 */ - this.dependenciesState_ === IDerivationState_.NOT_TRACKING_; - var newValue = this.computeValue_(true); - - var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue); - - if (changed) { - this.value_ = newValue; - } - - return changed; - }; - - _proto.computeValue_ = function computeValue_(track) { - this.isComputing_ = true; // don't allow state changes during computation - - var prev = allowStateChangesStart(false); - var res; - - if (track) { - res = trackDerivedFunction(this, this.derivation, this.scope_); - } else { - if (globalState.disableErrorBoundaries === true) { - res = this.derivation.call(this.scope_); - } else { - try { - res = this.derivation.call(this.scope_); - } catch (e) { - res = new CaughtException(e); - } - } - } - - allowStateChangesEnd(prev); - this.isComputing_ = false; - return res; - }; - - _proto.suspend_ = function suspend_() { - if (!this.keepAlive_) { - clearObserving(this); - this.value_ = undefined; // don't hold on to computed value! - } - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - var _this = this; - - var firstTime = true; - var prevValue = undefined; - return autorun(function () { - // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place - var newValue = _this.get(); - - if (!firstTime || fireImmediately) { - var prevU = untrackedStart(); - listener({ - observableKind: "computed", - debugObjectName: _this.name_, - type: UPDATE, - object: _this, - newValue: newValue, - oldValue: prevValue - }); - untrackedEnd(prevU); - } - - firstTime = false; - prevValue = newValue; - }); - }; - - _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() { - return; - }; - - _proto.toString = function toString() { - return this.name_ + "[" + this.derivation.toString() + "]"; - }; - - _proto.valueOf = function valueOf() { - return toPrimitive(this.get()); - }; - - _proto[_Symbol$toPrimitive$1] = function () { - return this.valueOf(); - }; - - return ComputedValue; -}(); -var isComputedValue = /*#__PURE__*/createInstanceofPredicate("ComputedValue", ComputedValue); - -var IDerivationState_; - -(function (IDerivationState_) { - // before being run or (outside batch and not being observed) - // at this point derivation is not holding any data about dependency tree - IDerivationState_[IDerivationState_["NOT_TRACKING_"] = -1] = "NOT_TRACKING_"; // no shallow dependency changed since last computation - // won't recalculate derivation - // this is what makes mobx fast - - IDerivationState_[IDerivationState_["UP_TO_DATE_"] = 0] = "UP_TO_DATE_"; // some deep dependency changed, but don't know if shallow dependency changed - // will require to check first if UP_TO_DATE or POSSIBLY_STALE - // currently only ComputedValue will propagate POSSIBLY_STALE - // - // having this state is second big optimization: - // don't have to recompute on every dependency change, but only when it's needed - - IDerivationState_[IDerivationState_["POSSIBLY_STALE_"] = 1] = "POSSIBLY_STALE_"; // A shallow dependency has changed since last computation and the derivation - // will need to recompute when it's needed next. - - IDerivationState_[IDerivationState_["STALE_"] = 2] = "STALE_"; -})(IDerivationState_ || (IDerivationState_ = {})); - -var TraceMode; - -(function (TraceMode) { - TraceMode[TraceMode["NONE"] = 0] = "NONE"; - TraceMode[TraceMode["LOG"] = 1] = "LOG"; - TraceMode[TraceMode["BREAK"] = 2] = "BREAK"; -})(TraceMode || (TraceMode = {})); - -var CaughtException = function CaughtException(cause) { - this.cause = void 0; - this.cause = cause; // Empty -}; -function isCaughtException(e) { - return e instanceof CaughtException; -} -/** - * Finds out whether any dependency of the derivation has actually changed. - * If dependenciesState is 1 then it will recalculate dependencies, - * if any dependency changed it will propagate it by changing dependenciesState to 2. - * - * By iterating over the dependencies in the same order that they were reported and - * stopping on the first change, all the recalculations are only called for ComputedValues - * that will be tracked by derivation. That is because we assume that if the first x - * dependencies of the derivation doesn't change then the derivation should run the same way - * up until accessing x-th dependency. - */ - -function shouldCompute(derivation) { - switch (derivation.dependenciesState_) { - case IDerivationState_.UP_TO_DATE_: - return false; - - case IDerivationState_.NOT_TRACKING_: - case IDerivationState_.STALE_: - return true; - - case IDerivationState_.POSSIBLY_STALE_: - { - // state propagation can occur outside of action/reactive context #2195 - var prevAllowStateReads = allowStateReadsStart(true); - var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction. - - var obs = derivation.observing_, - l = obs.length; - - for (var i = 0; i < l; i++) { - var obj = obs[i]; - - if (isComputedValue(obj)) { - if (globalState.disableErrorBoundaries) { - obj.get(); - } else { - try { - obj.get(); - } catch (e) { - // we are not interested in the value *or* exception at this moment, but if there is one, notify all - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return true; - } - } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers. - // and `derivation` is an observer of `obj` - // invariantShouldCompute(derivation) - - - if (derivation.dependenciesState_ === IDerivationState_.STALE_) { - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return true; - } - } - } - - changeDependenciesStateTo0(derivation); - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return false; - } - } -} -function checkIfStateModificationsAreAllowed(atom) { - { - return; - } -} -/** - * Executes the provided function `f` and tracks which observables are being accessed. - * The tracking information is stored on the `derivation` object and the derivation is registered - * as observer of any of the accessed observables. - */ - -function trackDerivedFunction(derivation, f, context) { - var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps - // array will be trimmed by bindDependencies - - changeDependenciesStateTo0(derivation); - derivation.newObserving_ = new Array(derivation.observing_.length + 100); - derivation.unboundDepsCount_ = 0; - derivation.runId_ = ++globalState.runId; - var prevTracking = globalState.trackingDerivation; - globalState.trackingDerivation = derivation; - globalState.inBatch++; - var result; - - if (globalState.disableErrorBoundaries === true) { - result = f.call(context); - } else { - try { - result = f.call(context); - } catch (e) { - result = new CaughtException(e); - } - } - - globalState.inBatch--; - globalState.trackingDerivation = prevTracking; - bindDependencies(derivation); - allowStateReadsEnd(prevAllowStateReads); - return result; -} -/** - * diffs newObserving with observing. - * update observing to be newObserving with unique observables - * notify observers that become observed/unobserved - */ - - -function bindDependencies(derivation) { - // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1"); - var prevObserving = derivation.observing_; - var observing = derivation.observing_ = derivation.newObserving_; - var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; // Go through all new observables and check diffValue: (this list can contain duplicates): - // 0: first occurrence, change to 1 and keep it - // 1: extra occurrence, drop it - - var i0 = 0, - l = derivation.unboundDepsCount_; - - for (var i = 0; i < l; i++) { - var dep = observing[i]; - - if (dep.diffValue_ === 0) { - dep.diffValue_ = 1; - if (i0 !== i) observing[i0] = dep; - i0++; - } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined, - // not hitting the condition - - - if (dep.dependenciesState_ > lowestNewObservingDerivationState) { - lowestNewObservingDerivationState = dep.dependenciesState_; - } - } - - observing.length = i0; - derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614) - // Go through all old observables and check diffValue: (it is unique after last bindDependencies) - // 0: it's not in new observables, unobserve it - // 1: it keeps being observed, don't want to notify it. change to 0 - - l = prevObserving.length; - - while (l--) { - var _dep = prevObserving[l]; - - if (_dep.diffValue_ === 0) { - removeObserver(_dep, derivation); - } - - _dep.diffValue_ = 0; - } // Go through all new observables and check diffValue: (now it should be unique) - // 0: it was set to 0 in last loop. don't need to do anything. - // 1: it wasn't observed, let's observe it. set back to 0 - - - while (i0--) { - var _dep2 = observing[i0]; - - if (_dep2.diffValue_ === 1) { - _dep2.diffValue_ = 0; - addObserver(_dep2, derivation); - } - } // Some new observed derivations may become stale during this derivation computation - // so they have had no chance to propagate staleness (#916) - - - if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) { - derivation.dependenciesState_ = lowestNewObservingDerivationState; - derivation.onBecomeStale_(); - } -} - -function clearObserving(derivation) { - // invariant(globalState.inBatch > 0, "INTERNAL ERROR clearObserving should be called only inside batch"); - var obs = derivation.observing_; - derivation.observing_ = []; - var i = obs.length; - - while (i--) { - removeObserver(obs[i], derivation); - } - - derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_; -} -function untracked(action) { - var prev = untrackedStart(); - - try { - return action(); - } finally { - untrackedEnd(prev); - } -} -function untrackedStart() { - var prev = globalState.trackingDerivation; - globalState.trackingDerivation = null; - return prev; -} -function untrackedEnd(prev) { - globalState.trackingDerivation = prev; -} -function allowStateReadsStart(allowStateReads) { - var prev = globalState.allowStateReads; - globalState.allowStateReads = allowStateReads; - return prev; -} -function allowStateReadsEnd(prev) { - globalState.allowStateReads = prev; -} -/** - * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0 - * - */ - -function changeDependenciesStateTo0(derivation) { - if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) return; - derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_; - var obs = derivation.observing_; - var i = obs.length; - - while (i--) { - obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - } -} -var MobXGlobals = function MobXGlobals() { - this.version = 6; - this.UNCHANGED = {}; - this.trackingDerivation = null; - this.trackingContext = null; - this.runId = 0; - this.mobxGuid = 0; - this.inBatch = 0; - this.pendingUnobservations = []; - this.pendingReactions = []; - this.isRunningReactions = false; - this.allowStateChanges = false; - this.allowStateReads = true; - this.enforceActions = true; - this.spyListeners = []; - this.globalReactionErrorHandlers = []; - this.computedRequiresReaction = false; - this.reactionRequiresObservable = false; - this.observableRequiresReaction = false; - this.disableErrorBoundaries = false; - this.suppressReactionErrors = false; - this.useProxies = true; - this.verifyProxies = false; - this.safeDescriptors = true; -}; -var canMergeGlobalState = true; -var globalState = /*#__PURE__*/function () { - var global = /*#__PURE__*/getGlobal(); - if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) canMergeGlobalState = false; - if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) canMergeGlobalState = false; - - if (!canMergeGlobalState) { - setTimeout(function () { - { - die(35); - } - }, 1); - return new MobXGlobals(); - } else if (global.__mobxGlobals) { - global.__mobxInstanceCount += 1; - if (!global.__mobxGlobals.UNCHANGED) global.__mobxGlobals.UNCHANGED = {}; // make merge backward compatible - - return global.__mobxGlobals; - } else { - global.__mobxInstanceCount = 1; - return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals(); - } -}(); -function getGlobalState() { - return globalState; -} -// const list = observable.observers -// const map = observable.observersIndexes -// const l = list.length -// for (let i = 0; i < l; i++) { -// const id = list[i].__mapid -// if (i) { -// invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list") // for performance -// } else { -// invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldn't be held in map.") // for performance -// } -// } -// invariant( -// list.length === 0 || Object.keys(map).length === list.length - 1, -// "INTERNAL ERROR there is no junk in map" -// ) -// } - -function addObserver(observable, node) { - // invariant(node.dependenciesState !== -1, "INTERNAL ERROR, can add only dependenciesState !== -1"); - // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR add already added node"); - // invariantObservers(observable); - observable.observers_.add(node); - if (observable.lowestObserverState_ > node.dependenciesState_) observable.lowestObserverState_ = node.dependenciesState_; // invariantObservers(observable); - // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR didn't add node"); -} -function removeObserver(observable, node) { - // invariant(globalState.inBatch > 0, "INTERNAL ERROR, remove should be called only inside batch"); - // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR remove already removed node"); - // invariantObservers(observable); - observable.observers_["delete"](node); - - if (observable.observers_.size === 0) { - // deleting last observer - queueForUnobservation(observable); - } // invariantObservers(observable); - // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR remove already removed node2"); - -} -function queueForUnobservation(observable) { - if (observable.isPendingUnobservation_ === false) { - // invariant(observable._observers.length === 0, "INTERNAL ERROR, should only queue for unobservation unobserved observables"); - observable.isPendingUnobservation_ = true; - globalState.pendingUnobservations.push(observable); - } -} -/** - * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does. - * During a batch `onBecomeUnobserved` will be called at most once per observable. - * Avoids unnecessary recalculations. - */ - -function startBatch() { - globalState.inBatch++; -} -function endBatch() { - if (--globalState.inBatch === 0) { - runReactions(); // the batch is actually about to finish, all unobserving should happen here. - - var list = globalState.pendingUnobservations; - - for (var i = 0; i < list.length; i++) { - var observable = list[i]; - observable.isPendingUnobservation_ = false; - - if (observable.observers_.size === 0) { - if (observable.isBeingObserved_) { - // if this observable had reactive observers, trigger the hooks - observable.isBeingObserved_ = false; - observable.onBUO(); - } - - if (observable instanceof ComputedValue) { - // computed values are automatically teared down when the last observer leaves - // this process happens recursively, this computed might be the last observabe of another, etc.. - observable.suspend_(); - } - } - } - - globalState.pendingUnobservations = []; - } -} -function reportObserved(observable) { - var derivation = globalState.trackingDerivation; - - if (derivation !== null) { - /** - * Simple optimization, give each derivation run an unique id (runId) - * Check if last time this observable was accessed the same runId is used - * if this is the case, the relation is already known - */ - if (derivation.runId_ !== observable.lastAccessedBy_) { - observable.lastAccessedBy_ = derivation.runId_; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close... - - derivation.newObserving_[derivation.unboundDepsCount_++] = observable; - - if (!observable.isBeingObserved_ && globalState.trackingContext) { - observable.isBeingObserved_ = true; - observable.onBO(); - } - } - - return true; - } else if (observable.observers_.size === 0 && globalState.inBatch > 0) { - queueForUnobservation(observable); - } - - return false; -} // function invariantLOS(observable: IObservable, msg: string) { -// // it's expensive so better not run it in produciton. but temporarily helpful for testing -// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2) -// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState` -// throw new Error( -// "lowestObserverState is wrong for " + -// msg + -// " because " + -// min + -// " < " + -// observable.lowestObserverState -// ) -// } - -/** - * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly - * It will propagate changes to observers from previous run - * It's hard or maybe impossible (with reasonable perf) to get it right with current approach - * Hopefully self reruning autoruns aren't a feature people should depend on - * Also most basic use cases should be ok - */ -// Called by Atom when its value changes - -function propagateChanged(observable) { - // invariantLOS(observable, "changed start"); - if (observable.lowestObserverState_ === IDerivationState_.STALE_) return; - observable.lowestObserverState_ = IDerivationState_.STALE_; // Ideally we use for..of here, but the downcompiled version is really slow... - - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { - - d.onBecomeStale_(); - } - - d.dependenciesState_ = IDerivationState_.STALE_; - }); // invariantLOS(observable, "changed end"); -} // Called by ComputedValue when it recalculate and its value changed - -function propagateChangeConfirmed(observable) { - // invariantLOS(observable, "confirmed start"); - if (observable.lowestObserverState_ === IDerivationState_.STALE_) return; - observable.lowestObserverState_ = IDerivationState_.STALE_; - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) { - d.dependenciesState_ = IDerivationState_.STALE_; - } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date. - ) { - observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - } - }); // invariantLOS(observable, "confirmed end"); -} // Used by computed when its dependency changed, but we don't wan't to immediately recompute. - -function propagateMaybeChanged(observable) { - // invariantLOS(observable, "maybe start"); - if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) return; - observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_; - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { - d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_; - d.onBecomeStale_(); - } - }); // invariantLOS(observable, "maybe end"); -} - -var Reaction = /*#__PURE__*/function () { - // nodes we are looking at. Our value depends on these nodes - function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) { - if (name_ === void 0) { - name_ = "Reaction"; - } - - if (requiresObservable_ === void 0) { - requiresObservable_ = false; - } - - this.name_ = void 0; - this.onInvalidate_ = void 0; - this.errorHandler_ = void 0; - this.requiresObservable_ = void 0; - this.observing_ = []; - this.newObserving_ = []; - this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; - this.diffValue_ = 0; - this.runId_ = 0; - this.unboundDepsCount_ = 0; - this.isDisposed_ = false; - this.isScheduled_ = false; - this.isTrackPending_ = false; - this.isRunning_ = false; - this.isTracing_ = TraceMode.NONE; - this.name_ = name_; - this.onInvalidate_ = onInvalidate_; - this.errorHandler_ = errorHandler_; - this.requiresObservable_ = requiresObservable_; - } - - var _proto = Reaction.prototype; - - _proto.onBecomeStale_ = function onBecomeStale_() { - this.schedule_(); - }; - - _proto.schedule_ = function schedule_() { - if (!this.isScheduled_) { - this.isScheduled_ = true; - globalState.pendingReactions.push(this); - runReactions(); - } - }; - - _proto.isScheduled = function isScheduled() { - return this.isScheduled_; - } - /** - * internal, use schedule() if you intend to kick off a reaction - */ - ; - - _proto.runReaction_ = function runReaction_() { - if (!this.isDisposed_) { - startBatch(); - this.isScheduled_ = false; - var prev = globalState.trackingContext; - globalState.trackingContext = this; - - if (shouldCompute(this)) { - this.isTrackPending_ = true; - - try { - this.onInvalidate_(); - - if ("production" !== "production" && this.isTrackPending_ && isSpyEnabled()) ; - } catch (e) { - this.reportExceptionInDerivation_(e); - } - } - - globalState.trackingContext = prev; - endBatch(); - } - }; - - _proto.track = function track(fn) { - if (this.isDisposed_) { - return; // console.warn("Reaction already disposed") // Note: Not a warning / error in mobx 4 either - } - - startBatch(); - - this.isRunning_ = true; - var prevReaction = globalState.trackingContext; // reactions could create reactions... - - globalState.trackingContext = this; - var result = trackDerivedFunction(this, fn, undefined); - globalState.trackingContext = prevReaction; - this.isRunning_ = false; - this.isTrackPending_ = false; - - if (this.isDisposed_) { - // disposed during last run. Clean up everything that was bound after the dispose call. - clearObserving(this); - } - - if (isCaughtException(result)) this.reportExceptionInDerivation_(result.cause); - - endBatch(); - }; - - _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) { - var _this = this; - - if (this.errorHandler_) { - this.errorHandler_(error, this); - return; - } - - if (globalState.disableErrorBoundaries) throw error; - var message = "[mobx] uncaught error in '" + this + "'"; - - if (!globalState.suppressReactionErrors) { - console.error(message, error); - /** If debugging brought you here, please, read the above message :-). Tnx! */ - } // prettier-ignore - - globalState.globalReactionErrorHandlers.forEach(function (f) { - return f(error, _this); - }); - }; - - _proto.dispose = function dispose() { - if (!this.isDisposed_) { - this.isDisposed_ = true; - - if (!this.isRunning_) { - // if disposed while running, clean up later. Maybe not optimal, but rare case - startBatch(); - clearObserving(this); - endBatch(); - } - } - }; - - _proto.getDisposer_ = function getDisposer_() { - var r = this.dispose.bind(this); - r[$mobx] = this; - return r; - }; - - _proto.toString = function toString() { - return "Reaction[" + this.name_ + "]"; - }; - - _proto.trace = function trace$1(enterBreakPoint) { - if (enterBreakPoint === void 0) { - enterBreakPoint = false; - } - - trace(this, enterBreakPoint); - }; - - return Reaction; -}(); -/** - * Magic number alert! - * Defines within how many times a reaction is allowed to re-trigger itself - * until it is assumed that this is gonna be a never ending loop... - */ - -var MAX_REACTION_ITERATIONS = 100; - -var reactionScheduler = function reactionScheduler(f) { - return f(); -}; - -function runReactions() { - // Trampolining, if runReactions are already running, new reactions will be picked up - if (globalState.inBatch > 0 || globalState.isRunningReactions) return; - reactionScheduler(runReactionsHelper); -} - -function runReactionsHelper() { - globalState.isRunningReactions = true; - var allReactions = globalState.pendingReactions; - var iterations = 0; // While running reactions, new reactions might be triggered. - // Hence we work with two variables and check whether - // we converge to no remaining reactions after a while. - - while (allReactions.length > 0) { - if (++iterations === MAX_REACTION_ITERATIONS) { - console.error("[mobx] cycle in reaction: " + allReactions[0]); - allReactions.splice(0); // clear reactions - } - - var remainingReactions = allReactions.splice(0); - - for (var i = 0, l = remainingReactions.length; i < l; i++) { - remainingReactions[i].runReaction_(); - } - } - - globalState.isRunningReactions = false; -} - -var isReaction = /*#__PURE__*/createInstanceofPredicate("Reaction", Reaction); - -function isSpyEnabled() { - return "production" !== "production" ; -} -function spyReport(event) { - return; // dead code elimination can do the rest -} -function spyReportStart(event) { - return; -} -function spyReportEnd(change) { - return; -} -function spy(listener) { - { - console.warn("[mobx.spy] Is a no-op in production builds"); - return function () {}; - } -} - -var ACTION = "action"; -var ACTION_BOUND = "action.bound"; -var AUTOACTION = "autoAction"; -var AUTOACTION_BOUND = "autoAction.bound"; -var DEFAULT_ACTION_NAME = ""; -var actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION); -var actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, { - bound: true -}); -var autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, { - autoAction: true -}); -var autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, { - autoAction: true, - bound: true -}); - -function createActionFactory(autoAction) { - var res = function action(arg1, arg2) { - // action(fn() {}) - if (isFunction$2(arg1)) return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction); // action("name", fn() {}) - - if (isFunction$2(arg2)) return createAction(arg1, arg2, autoAction); // @action - - if (isStringish(arg2)) { - return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation); - } // action("name") & @action("name") - - - if (isStringish(arg1)) { - return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, { - name: arg1, - autoAction: autoAction - })); - } - }; - - return res; -} - -var action = /*#__PURE__*/createActionFactory(false); -Object.assign(action, actionAnnotation); -var autoAction = /*#__PURE__*/createActionFactory(true); -Object.assign(autoAction, autoActionAnnotation); -action.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation); -autoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation); -function runInAction(fn) { - return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined); -} -function isAction(thing) { - return isFunction$2(thing) && thing.isMobxAction === true; -} - -/** - * Creates a named reactive view and keeps it alive, so that the view is always - * updated if one of the dependencies changes, even when the view is not further used by something else. - * @param view The reactive view - * @returns disposer function, which can be used to stop the view from being updated in the future. - */ - -function autorun(view, opts) { - var _opts$name, _opts; - - if (opts === void 0) { - opts = EMPTY_OBJECT$1; - } - - var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : "Autorun"; - var runSync = !opts.scheduler && !opts.delay; - var reaction; - - if (runSync) { - // normal autorun - reaction = new Reaction(name, function () { - this.track(reactionRunner); - }, opts.onError, opts.requiresObservable); - } else { - var scheduler = createSchedulerFromOptions(opts); // debounced autorun - - var isScheduled = false; - reaction = new Reaction(name, function () { - if (!isScheduled) { - isScheduled = true; - scheduler(function () { - isScheduled = false; - if (!reaction.isDisposed_) reaction.track(reactionRunner); - }); - } - }, opts.onError, opts.requiresObservable); - } - - function reactionRunner() { - view(reaction); - } - - reaction.schedule_(); - return reaction.getDisposer_(); -} - -var run = function run(f) { - return f(); -}; - -function createSchedulerFromOptions(opts) { - return opts.scheduler ? opts.scheduler : opts.delay ? function (f) { - return setTimeout(f, opts.delay); - } : run; -} - -function reaction(expression, effect, opts) { - var _opts$name2; - - if (opts === void 0) { - opts = EMPTY_OBJECT$1; - } - - var name = (_opts$name2 = opts.name) != null ? _opts$name2 : "Reaction"; - var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect); - var runSync = !opts.scheduler && !opts.delay; - var scheduler = createSchedulerFromOptions(opts); - var firstTime = true; - var isScheduled = false; - var value; - var oldValue = undefined; // only an issue with fireImmediately - - var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer["default"]; - var r = new Reaction(name, function () { - if (firstTime || runSync) { - reactionRunner(); - } else if (!isScheduled) { - isScheduled = true; - scheduler(reactionRunner); - } - }, opts.onError, opts.requiresObservable); - - function reactionRunner() { - isScheduled = false; - if (r.isDisposed_) return; - var changed = false; - r.track(function () { - var nextValue = allowStateChanges(false, function () { - return expression(r); - }); - changed = firstTime || !equals(value, nextValue); - oldValue = value; - value = nextValue; - }); - if (firstTime && opts.fireImmediately) effectAction(value, oldValue, r);else if (!firstTime && changed) effectAction(value, oldValue, r); - firstTime = false; - } - - r.schedule_(); - return r.getDisposer_(); -} - -function wrapErrorHandler(errorHandler, baseFn) { - return function () { - try { - return baseFn.apply(this, arguments); - } catch (e) { - errorHandler.call(this, e); - } - }; -} - -var ON_BECOME_OBSERVED = "onBO"; -var ON_BECOME_UNOBSERVED = "onBUO"; -function onBecomeObserved(thing, arg2, arg3) { - return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3); -} -function onBecomeUnobserved(thing, arg2, arg3) { - return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3); -} - -function interceptHook(hook, thing, arg2, arg3) { - var atom = typeof arg3 === "function" ? getAtom(thing, arg2) : getAtom(thing); - var cb = isFunction$2(arg3) ? arg3 : arg2; - var listenersKey = hook + "L"; - - if (atom[listenersKey]) { - atom[listenersKey].add(cb); - } else { - atom[listenersKey] = new Set([cb]); - } - - return function () { - var hookListeners = atom[listenersKey]; - - if (hookListeners) { - hookListeners["delete"](cb); - - if (hookListeners.size === 0) { - delete atom[listenersKey]; - } - } - }; -} - -function extendObservable(target, properties, annotations, options) { - - - var descriptors = getOwnPropertyDescriptors(properties); - var adm = asObservableObject(target, options)[$mobx]; - startBatch(); - - try { - ownKeys(descriptors).forEach(function (key) { - adm.extend_(key, descriptors[key], // must pass "undefined" for { key: undefined } - !annotations ? true : key in annotations ? annotations[key] : true); - }); - } finally { - endBatch(); - } - - return target; -} - -var generatorId = 0; -function FlowCancellationError() { - this.message = "FLOW_CANCELLED"; -} -FlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype); -var flowAnnotation = /*#__PURE__*/createFlowAnnotation("flow"); -var flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation("flow.bound", { - bound: true -}); -var flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) { - // @flow - if (isStringish(arg2)) { - return storeAnnotation(arg1, arg2, flowAnnotation); - } // flow(fn) - var generator = arg1; - var name = generator.name || ""; // Implementation based on https://github.com/tj/co/blob/master/index.js - - var res = function res() { - var ctx = this; - var args = arguments; - var runId = ++generatorId; - var gen = action(name + " - runid: " + runId + " - init", generator).apply(ctx, args); - var rejector; - var pendingPromise = undefined; - var promise = new Promise(function (resolve, reject) { - var stepId = 0; - rejector = reject; - - function onFulfilled(res) { - pendingPromise = undefined; - var ret; - - try { - ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.next).call(gen, res); - } catch (e) { - return reject(e); - } - - next(ret); - } - - function onRejected(err) { - pendingPromise = undefined; - var ret; - - try { - ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen["throw"]).call(gen, err); - } catch (e) { - return reject(e); - } - - next(ret); - } - - function next(ret) { - if (isFunction$2(ret == null ? void 0 : ret.then)) { - // an async iterator - ret.then(next, reject); - return; - } - - if (ret.done) return resolve(ret.value); - pendingPromise = Promise.resolve(ret.value); - return pendingPromise.then(onFulfilled, onRejected); - } - - onFulfilled(undefined); // kick off the process - }); - promise.cancel = action(name + " - runid: " + runId + " - cancel", function () { - try { - if (pendingPromise) cancelPromise(pendingPromise); // Finally block can return (or yield) stuff.. - - var _res = gen["return"](undefined); // eat anything that promise would do, it's cancelled! - - - var yieldedPromise = Promise.resolve(_res.value); - yieldedPromise.then(noop$1, noop$1); - cancelPromise(yieldedPromise); // maybe it can be cancelled :) - // reject our original promise - - rejector(new FlowCancellationError()); - } catch (e) { - rejector(e); // there could be a throwing finally block - } - }); - return promise; - }; - - res.isMobXFlow = true; - return res; -}, flowAnnotation); -flow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation); - -function cancelPromise(promise) { - if (isFunction$2(promise.cancel)) promise.cancel(); -} -function isFlow(fn) { - return (fn == null ? void 0 : fn.isMobXFlow) === true; -} - -function interceptReads(thing, propOrHandler, handler) { - var target; - - if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) { - target = getAdministration(thing); - } else if (isObservableObject(thing)) { - target = getAdministration(thing, propOrHandler); - } else ; - target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler; - return function () { - target.dehancer = undefined; - }; -} - -function intercept(thing, propOrHandler, handler) { - if (isFunction$2(handler)) return interceptProperty(thing, propOrHandler, handler);else return interceptInterceptable(thing, propOrHandler); -} - -function interceptInterceptable(thing, handler) { - return getAdministration(thing).intercept_(handler); -} - -function interceptProperty(thing, property, handler) { - return getAdministration(thing, property).intercept_(handler); -} - -function _isObservable(value, property) { - if (!value) return false; - - if (property !== undefined) { - - if (isObservableObject(value)) { - return value[$mobx].values_.has(property); - } - - return false; - } // For first check, see #701 - - - return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value); -} - -function isObservable(value) { - return _isObservable(value); -} - -function keys(obj) { - if (isObservableObject(obj)) { - return obj[$mobx].keys_(); - } - - if (isObservableMap(obj) || isObservableSet(obj)) { - return Array.from(obj.keys()); - } - - if (isObservableArray(obj)) { - return obj.map(function (_, index) { - return index; - }); - } - - die(5); -} -function values(obj) { - if (isObservableObject(obj)) { - return keys(obj).map(function (key) { - return obj[key]; - }); - } - - if (isObservableMap(obj)) { - return keys(obj).map(function (key) { - return obj.get(key); - }); - } - - if (isObservableSet(obj)) { - return Array.from(obj.values()); - } - - if (isObservableArray(obj)) { - return obj.slice(); - } - - die(6); -} -function entries(obj) { - if (isObservableObject(obj)) { - return keys(obj).map(function (key) { - return [key, obj[key]]; - }); - } - - if (isObservableMap(obj)) { - return keys(obj).map(function (key) { - return [key, obj.get(key)]; - }); - } - - if (isObservableSet(obj)) { - return Array.from(obj.entries()); - } - - if (isObservableArray(obj)) { - return obj.map(function (key, index) { - return [index, key]; - }); - } - - die(7); -} -function set(obj, key, value) { - if (arguments.length === 2 && !isObservableSet(obj)) { - startBatch(); - var _values = key; - - try { - for (var _key in _values) { - set(obj, _key, _values[_key]); - } - } finally { - endBatch(); - } - - return; - } - - if (isObservableObject(obj)) { - obj[$mobx].set_(key, value); - } else if (isObservableMap(obj)) { - obj.set(key, value); - } else if (isObservableSet(obj)) { - obj.add(key); - } else if (isObservableArray(obj)) { - if (typeof key !== "number") key = parseInt(key, 10); - if (key < 0) die("Invalid index: '" + key + "'"); - startBatch(); - if (key >= obj.length) obj.length = key + 1; - obj[key] = value; - endBatch(); - } else die(8); -} -function apiDefineProperty(obj, key, descriptor) { - if (isObservableObject(obj)) { - return obj[$mobx].defineProperty_(key, descriptor); - } - - die(39); -} - -function observe(thing, propOrCb, cbOrFire, fireImmediately) { - if (isFunction$2(cbOrFire)) return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);else return observeObservable(thing, propOrCb, cbOrFire); -} - -function observeObservable(thing, listener, fireImmediately) { - return getAdministration(thing).observe_(listener, fireImmediately); -} - -function observeObservableProperty(thing, property, listener, fireImmediately) { - return getAdministration(thing, property).observe_(listener, fireImmediately); -} - -function trace() { - die("trace() is not available in production builds"); - var enterBreakPoint = false; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - if (typeof args[args.length - 1] === "boolean") enterBreakPoint = args.pop(); - var derivation = getAtomFromArgs(args); - - if (!derivation) { - return die("'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly"); - } - - if (derivation.isTracing_ === TraceMode.NONE) { - console.log("[mobx.trace] '" + derivation.name_ + "' tracing enabled"); - } - - derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG; -} - -function getAtomFromArgs(args) { - switch (args.length) { - case 0: - return globalState.trackingDerivation; - - case 1: - return getAtom(args[0]); - - case 2: - return getAtom(args[0], args[1]); - } -} - -/** - * During a transaction no views are updated until the end of the transaction. - * The transaction will be run synchronously nonetheless. - * - * @param action a function that updates some reactive state - * @returns any value that was returned by the 'action' parameter. - */ - -function transaction(action, thisArg) { - if (thisArg === void 0) { - thisArg = undefined; - } - - startBatch(); - - try { - return action.apply(thisArg); - } finally { - endBatch(); - } -} - -function getAdm(target) { - return target[$mobx]; -} // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects, -// and skip either the internal values map, or the base object with its property descriptors! - - -var objectProxyTraps = { - has: function has(target, name) { - return getAdm(target).has_(name); - }, - get: function get(target, name) { - return getAdm(target).get_(name); - }, - set: function set(target, name, value) { - var _getAdm$set_; - - if (!isStringish(name)) return false; - - - return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true; - }, - deleteProperty: function deleteProperty(target, name) { - var _getAdm$delete_; - - if (!isStringish(name)) return false; // null (intercepted) -> true (success) - - return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true; - }, - defineProperty: function defineProperty(target, name, descriptor) { - var _getAdm$definePropert; - - - return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true; - }, - ownKeys: function ownKeys(target) { - return getAdm(target).ownKeys_(); - }, - preventExtensions: function preventExtensions(target) { - die(13); - } -}; -function asDynamicObservableObject(target, options) { - var _target$$mobx, _target$$mobx$proxy_; - - assertProxies(); - target = asObservableObject(target, options); - return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps); -} - -function hasInterceptors(interceptable) { - return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0; -} -function registerInterceptor(interceptable, handler) { - var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []); - interceptors.push(handler); - return once(function () { - var idx = interceptors.indexOf(handler); - if (idx !== -1) interceptors.splice(idx, 1); - }); -} -function interceptChange(interceptable, change) { - var prevU = untrackedStart(); - - try { - // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950 - var interceptors = [].concat(interceptable.interceptors_ || []); - - for (var i = 0, l = interceptors.length; i < l; i++) { - change = interceptors[i](change); - if (change && !change.type) die(14); - if (!change) break; - } - - return change; - } finally { - untrackedEnd(prevU); - } -} - -function hasListeners(listenable) { - return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0; -} -function registerListener(listenable, handler) { - var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []); - listeners.push(handler); - return once(function () { - var idx = listeners.indexOf(handler); - if (idx !== -1) listeners.splice(idx, 1); - }); -} -function notifyListeners(listenable, change) { - var prevU = untrackedStart(); - var listeners = listenable.changeListeners_; - if (!listeners) return; - listeners = listeners.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i](change); - } - - untrackedEnd(prevU); -} - -function makeObservable(target, annotations, options) { - var adm = asObservableObject(target, options)[$mobx]; - startBatch(); - - try { - var _annotations; - - // Default to decorators - (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target); // Annotate - - ownKeys(annotations).forEach(function (key) { - return adm.make_(key, annotations[key]); - }); - } finally { - endBatch(); - } - - return target; -} // proto[keysSymbol] = new Set() - -var SPLICE = "splice"; -var UPDATE = "update"; -var MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859 - -var arrayTraps = { - get: function get(target, name) { - var adm = target[$mobx]; - if (name === $mobx) return adm; - if (name === "length") return adm.getArrayLength_(); - - if (typeof name === "string" && !isNaN(name)) { - return adm.get_(parseInt(name)); - } - - if (hasProp(arrayExtensions, name)) { - return arrayExtensions[name]; - } - - return target[name]; - }, - set: function set(target, name, value) { - var adm = target[$mobx]; - - if (name === "length") { - adm.setArrayLength_(value); - } - - if (typeof name === "symbol" || isNaN(name)) { - target[name] = value; - } else { - // numeric string - adm.set_(parseInt(name), value); - } - - return true; - }, - preventExtensions: function preventExtensions() { - die(15); - } -}; -var ObservableArrayAdministration = /*#__PURE__*/function () { - // this is the prop that gets proxied, so can't replace it! - function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) { - if (name === void 0) { - name = "ObservableArray"; - } - - this.owned_ = void 0; - this.legacyMode_ = void 0; - this.atom_ = void 0; - this.values_ = []; - this.interceptors_ = void 0; - this.changeListeners_ = void 0; - this.enhancer_ = void 0; - this.dehancer = void 0; - this.proxy_ = void 0; - this.lastKnownLength_ = 0; - this.owned_ = owned_; - this.legacyMode_ = legacyMode_; - this.atom_ = new Atom(name); - - this.enhancer_ = function (newV, oldV) { - return enhancer(newV, oldV, "ObservableArray[..]"); - }; - } - - var _proto = ObservableArrayAdministration.prototype; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) return this.dehancer(value); - return value; - }; - - _proto.dehanceValues_ = function dehanceValues_(values) { - if (this.dehancer !== undefined && values.length > 0) return values.map(this.dehancer); - return values; - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - if (fireImmediately === void 0) { - fireImmediately = false; - } - - if (fireImmediately) { - listener({ - observableKind: "array", - object: this.proxy_, - debugObjectName: this.atom_.name_, - type: "splice", - index: 0, - added: this.values_.slice(), - addedCount: this.values_.length, - removed: [], - removedCount: 0 - }); - } - - return registerListener(this, listener); - }; - - _proto.getArrayLength_ = function getArrayLength_() { - this.atom_.reportObserved(); - return this.values_.length; - }; - - _proto.setArrayLength_ = function setArrayLength_(newLength) { - if (typeof newLength !== "number" || newLength < 0) die("Out of range: " + newLength); - var currentLength = this.values_.length; - if (newLength === currentLength) return;else if (newLength > currentLength) { - var newItems = new Array(newLength - currentLength); - - for (var i = 0; i < newLength - currentLength; i++) { - newItems[i] = undefined; - } // No Array.fill everywhere... - - - this.spliceWithArray_(currentLength, 0, newItems); - } else this.spliceWithArray_(newLength, currentLength - newLength); - }; - - _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) { - if (oldLength !== this.lastKnownLength_) die(16); - this.lastKnownLength_ += delta; - if (this.legacyMode_ && delta > 0) reserveArrayBuffer(oldLength + delta + 1); - }; - - _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) { - var _this = this; - - checkIfStateModificationsAreAllowed(this.atom_); - var length = this.values_.length; - if (index === undefined) index = 0;else if (index > length) index = length;else if (index < 0) index = Math.max(0, length + index); - if (arguments.length === 1) deleteCount = length - index;else if (deleteCount === undefined || deleteCount === null) deleteCount = 0;else deleteCount = Math.max(0, Math.min(deleteCount, length - index)); - if (newItems === undefined) newItems = EMPTY_ARRAY$1; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_, - type: SPLICE, - index: index, - removedCount: deleteCount, - added: newItems - }); - if (!change) return EMPTY_ARRAY$1; - deleteCount = change.removedCount; - newItems = change.added; - } - - newItems = newItems.length === 0 ? newItems : newItems.map(function (v) { - return _this.enhancer_(v, undefined); - }); - - if (this.legacyMode_ || "production" !== "production") { - var lengthDelta = newItems.length - deleteCount; - this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified - } - - var res = this.spliceItemsIntoValues_(index, deleteCount, newItems); - if (deleteCount !== 0 || newItems.length !== 0) this.notifyArraySplice_(index, newItems, res); - return this.dehanceValues_(res); - }; - - _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) { - if (newItems.length < MAX_SPLICE_SIZE) { - var _this$values_; - - return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems)); - } else { - var res = this.values_.slice(index, index + deleteCount); - var oldItems = this.values_.slice(index + deleteCount); - this.values_.length = index + newItems.length - deleteCount; - - for (var i = 0; i < newItems.length; i++) { - this.values_[index + i] = newItems[i]; - } - - for (var _i = 0; _i < oldItems.length; _i++) { - this.values_[index + newItems.length + _i] = oldItems[_i]; - } - - return res; - } - }; - - _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) { - var notifySpy = !this.owned_ && isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "array", - object: this.proxy_, - type: UPDATE, - debugObjectName: this.atom_.name_, - index: index, - newValue: newValue, - oldValue: oldValue - } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't - this.atom_.reportChanged(); - if (notify) notifyListeners(this, change); - }; - - _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) { - var notifySpy = !this.owned_ && isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "array", - object: this.proxy_, - debugObjectName: this.atom_.name_, - type: SPLICE, - index: index, - removed: removed, - added: added, - removedCount: removed.length, - addedCount: added.length - } : null; - this.atom_.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe - - if (notify) notifyListeners(this, change); - }; - - _proto.get_ = function get_(index) { - if (index < this.values_.length) { - this.atom_.reportObserved(); - return this.dehanceValue_(this.values_[index]); - } - - console.warn("[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + this.values_.length + "). Please check length first. Out of bound indices will not be tracked by MobX"); - }; - - _proto.set_ = function set_(index, newValue) { - var values = this.values_; - - if (index < values.length) { - // update at index in range - checkIfStateModificationsAreAllowed(this.atom_); - var oldValue = values[index]; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: UPDATE, - object: this.proxy_, - index: index, - newValue: newValue - }); - if (!change) return; - newValue = change.newValue; - } - - newValue = this.enhancer_(newValue, oldValue); - var changed = newValue !== oldValue; - - if (changed) { - values[index] = newValue; - this.notifyArrayChildUpdate_(index, newValue, oldValue); - } - } else if (index === values.length) { - // add a new item - this.spliceWithArray_(index, 0, [newValue]); - } else { - // out of bounds - die(17, index, values.length); - } - }; - - return ObservableArrayAdministration; -}(); -function createObservableArray(initialValues, enhancer, name, owned) { - if (name === void 0) { - name = "ObservableArray"; - } - - if (owned === void 0) { - owned = false; - } - - assertProxies(); - var adm = new ObservableArrayAdministration(name, enhancer, owned, false); - addHiddenFinalProp$1(adm.values_, $mobx, adm); - var proxy = new Proxy(adm.values_, arrayTraps); - adm.proxy_ = proxy; - - if (initialValues && initialValues.length) { - var prev = allowStateChangesStart(true); - adm.spliceWithArray_(0, 0, initialValues); - allowStateChangesEnd(prev); - } - - return proxy; -} // eslint-disable-next-line - -var arrayExtensions = { - clear: function clear() { - return this.splice(0); - }, - replace: function replace(newItems) { - var adm = this[$mobx]; - return adm.spliceWithArray_(0, adm.values_.length, newItems); - }, - // Used by JSON.stringify - toJSON: function toJSON() { - return this.slice(); - }, - - /* - * functions that do alter the internal structure of the array, (based on lib.es6.d.ts) - * since these functions alter the inner structure of the array, the have side effects. - * Because the have side effects, they should not be used in computed function, - * and for that reason the do not call dependencyState.notifyObserved - */ - splice: function splice(index, deleteCount) { - for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - newItems[_key - 2] = arguments[_key]; - } - - var adm = this[$mobx]; - - switch (arguments.length) { - case 0: - return []; - - case 1: - return adm.spliceWithArray_(index); - - case 2: - return adm.spliceWithArray_(index, deleteCount); - } - - return adm.spliceWithArray_(index, deleteCount, newItems); - }, - spliceWithArray: function spliceWithArray(index, deleteCount, newItems) { - return this[$mobx].spliceWithArray_(index, deleteCount, newItems); - }, - push: function push() { - var adm = this[$mobx]; - - for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - items[_key2] = arguments[_key2]; - } - - adm.spliceWithArray_(adm.values_.length, 0, items); - return adm.values_.length; - }, - pop: function pop() { - return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0]; - }, - shift: function shift() { - return this.splice(0, 1)[0]; - }, - unshift: function unshift() { - var adm = this[$mobx]; - - for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - items[_key3] = arguments[_key3]; - } - - adm.spliceWithArray_(0, 0, items); - return adm.values_.length; - }, - reverse: function reverse() { - // reverse by default mutates in place before returning the result - // which makes it both a 'derivation' and a 'mutation'. - if (globalState.trackingDerivation) { - die(37, "reverse"); - } - - this.replace(this.slice().reverse()); - return this; - }, - sort: function sort() { - // sort by default mutates in place before returning the result - // which goes against all good practices. Let's not change the array in place! - if (globalState.trackingDerivation) { - die(37, "sort"); - } - - var copy = this.slice(); - copy.sort.apply(copy, arguments); - this.replace(copy); - return this; - }, - remove: function remove(value) { - var adm = this[$mobx]; - var idx = adm.dehanceValues_(adm.values_).indexOf(value); - - if (idx > -1) { - this.splice(idx, 1); - return true; - } - - return false; - } -}; -/** - * Wrap function from prototype - * Without this, everything works as well, but this works - * faster as everything works on unproxied values - */ - -addArrayExtension("concat", simpleFunc); -addArrayExtension("flat", simpleFunc); -addArrayExtension("includes", simpleFunc); -addArrayExtension("indexOf", simpleFunc); -addArrayExtension("join", simpleFunc); -addArrayExtension("lastIndexOf", simpleFunc); -addArrayExtension("slice", simpleFunc); -addArrayExtension("toString", simpleFunc); -addArrayExtension("toLocaleString", simpleFunc); // map - -addArrayExtension("every", mapLikeFunc); -addArrayExtension("filter", mapLikeFunc); -addArrayExtension("find", mapLikeFunc); -addArrayExtension("findIndex", mapLikeFunc); -addArrayExtension("flatMap", mapLikeFunc); -addArrayExtension("forEach", mapLikeFunc); -addArrayExtension("map", mapLikeFunc); -addArrayExtension("some", mapLikeFunc); // reduce - -addArrayExtension("reduce", reduceLikeFunc); -addArrayExtension("reduceRight", reduceLikeFunc); - -function addArrayExtension(funcName, funcFactory) { - if (typeof Array.prototype[funcName] === "function") { - arrayExtensions[funcName] = funcFactory(funcName); - } -} // Report and delegate to dehanced array - - -function simpleFunc(funcName) { - return function () { - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); - return dehancedValues[funcName].apply(dehancedValues, arguments); - }; -} // Make sure callbacks recieve correct array arg #2326 - - -function mapLikeFunc(funcName) { - return function (callback, thisArg) { - var _this2 = this; - - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); - return dehancedValues[funcName](function (element, index) { - return callback.call(thisArg, element, index, _this2); - }); - }; -} // Make sure callbacks recieve correct array arg #2326 - - -function reduceLikeFunc(funcName) { - return function () { - var _this3 = this; - - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); // #2432 - reduce behavior depends on arguments.length - - var callback = arguments[0]; - - arguments[0] = function (accumulator, currentValue, index) { - return callback(accumulator, currentValue, index, _this3); - }; - - return dehancedValues[funcName].apply(dehancedValues, arguments); - }; -} - -var isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration); -function isObservableArray(thing) { - return isObject$2(thing) && isObservableArrayAdministration(thing[$mobx]); -} - -var _Symbol$iterator, _Symbol$toStringTag; -var ObservableMapMarker = {}; -var ADD = "add"; -var DELETE = "delete"; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54 -// But: https://github.com/mobxjs/mobx/issues/1556 - -_Symbol$iterator = Symbol.iterator; -_Symbol$toStringTag = Symbol.toStringTag; -var ObservableMap = /*#__PURE__*/function () { - // hasMap, not hashMap >-). - function ObservableMap(initialData, enhancer_, name_) { - if (enhancer_ === void 0) { - enhancer_ = deepEnhancer; - } - - if (name_ === void 0) { - name_ = "ObservableMap"; - } - - this.enhancer_ = void 0; - this.name_ = void 0; - this[$mobx] = ObservableMapMarker; - this.data_ = void 0; - this.hasMap_ = void 0; - this.keysAtom_ = void 0; - this.interceptors_ = void 0; - this.changeListeners_ = void 0; - this.dehancer = void 0; - this.enhancer_ = enhancer_; - this.name_ = name_; - - if (!isFunction$2(Map)) { - die(18); - } - - this.keysAtom_ = createAtom("ObservableMap.keys()"); - this.data_ = new Map(); - this.hasMap_ = new Map(); - this.merge(initialData); - } - - var _proto = ObservableMap.prototype; - - _proto.has_ = function has_(key) { - return this.data_.has(key); - }; - - _proto.has = function has(key) { - var _this = this; - - if (!globalState.trackingDerivation) return this.has_(key); - var entry = this.hasMap_.get(key); - - if (!entry) { - var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, "ObservableMap.key?", false); - this.hasMap_.set(key, newEntry); - onBecomeUnobserved(newEntry, function () { - return _this.hasMap_["delete"](key); - }); - } - - return entry.get(); - }; - - _proto.set = function set(key, value) { - var hasKey = this.has_(key); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: hasKey ? UPDATE : ADD, - object: this, - newValue: value, - name: key - }); - if (!change) return this; - value = change.newValue; - } - - if (hasKey) { - this.updateValue_(key, value); - } else { - this.addValue_(key, value); - } - - return this; - }; - - _proto["delete"] = function _delete(key) { - var _this2 = this; - - checkIfStateModificationsAreAllowed(this.keysAtom_); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: DELETE, - object: this, - name: key - }); - if (!change) return false; - } - - if (this.has_(key)) { - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - - var _change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: DELETE, - object: this, - oldValue: this.data_.get(key).value_, - name: key - } : null; - transaction(function () { - _this2.keysAtom_.reportChanged(); - - _this2.updateHasMapEntry_(key, false); - - var observable = _this2.data_.get(key); - - observable.setNewValue_(undefined); - - _this2.data_["delete"](key); - }); - if (notify) notifyListeners(this, _change); - return true; - } - - return false; - }; - - _proto.updateHasMapEntry_ = function updateHasMapEntry_(key, value) { - var entry = this.hasMap_.get(key); - - if (entry) { - entry.setNewValue_(value); - } - }; - - _proto.updateValue_ = function updateValue_(key, newValue) { - var observable = this.data_.get(key); - newValue = observable.prepareNewValue_(newValue); - - if (newValue !== globalState.UNCHANGED) { - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: UPDATE, - object: this, - oldValue: observable.value_, - name: key, - newValue: newValue - } : null; - observable.setNewValue_(newValue); - if (notify) notifyListeners(this, change); - } - }; - - _proto.addValue_ = function addValue_(key, newValue) { - var _this3 = this; - - checkIfStateModificationsAreAllowed(this.keysAtom_); - transaction(function () { - var observable = new ObservableValue(newValue, _this3.enhancer_, "ObservableMap.key", false); - - _this3.data_.set(key, observable); - - newValue = observable.value_; // value might have been changed - - _this3.updateHasMapEntry_(key, true); - - _this3.keysAtom_.reportChanged(); - }); - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: ADD, - object: this, - name: key, - newValue: newValue - } : null; - if (notify) notifyListeners(this, change); - }; - - _proto.get = function get(key) { - if (this.has(key)) return this.dehanceValue_(this.data_.get(key).get()); - return this.dehanceValue_(undefined); - }; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) { - return this.dehancer(value); - } - - return value; - }; - - _proto.keys = function keys() { - this.keysAtom_.reportObserved(); - return this.data_.keys(); - }; - - _proto.values = function values() { - var self = this; - var keys = this.keys(); - return makeIterable({ - next: function next() { - var _keys$next = keys.next(), - done = _keys$next.done, - value = _keys$next.value; - - return { - done: done, - value: done ? undefined : self.get(value) - }; - } - }); - }; - - _proto.entries = function entries() { - var self = this; - var keys = this.keys(); - return makeIterable({ - next: function next() { - var _keys$next2 = keys.next(), - done = _keys$next2.done, - value = _keys$next2.value; - - return { - done: done, - value: done ? undefined : [value, self.get(value)] - }; - } - }); - }; - - _proto[_Symbol$iterator] = function () { - return this.entries(); - }; - - _proto.forEach = function forEach(callback, thisArg) { - for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) { - var _step$value = _step.value, - key = _step$value[0], - value = _step$value[1]; - callback.call(thisArg, value, key, this); - } - } - /** Merge another object into this object, returns this. */ - ; - - _proto.merge = function merge(other) { - var _this4 = this; - - if (isObservableMap(other)) { - other = new Map(other); - } - - transaction(function () { - if (isPlainObject$1(other)) getPlainObjectKeys(other).forEach(function (key) { - return _this4.set(key, other[key]); - });else if (Array.isArray(other)) other.forEach(function (_ref) { - var key = _ref[0], - value = _ref[1]; - return _this4.set(key, value); - });else if (isES6Map(other)) { - if (other.constructor !== Map) die(19, other); - other.forEach(function (value, key) { - return _this4.set(key, value); - }); - } else if (other !== null && other !== undefined) die(20, other); - }); - return this; - }; - - _proto.clear = function clear() { - var _this5 = this; - - transaction(function () { - untracked(function () { - for (var _iterator2 = _createForOfIteratorHelperLoose(_this5.keys()), _step2; !(_step2 = _iterator2()).done;) { - var key = _step2.value; - - _this5["delete"](key); - } - }); - }); - }; - - _proto.replace = function replace(values) { - var _this6 = this; - - // Implementation requirements: - // - respect ordering of replacement map - // - allow interceptors to run and potentially prevent individual operations - // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions) - // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!) - // - note that result map may differ from replacement map due to the interceptors - transaction(function () { - // Convert to map so we can do quick key lookups - var replacementMap = convertToMap(values); - var orderedData = new Map(); // Used for optimization - - var keysReportChangedCalled = false; // Delete keys that don't exist in replacement map - // if the key deletion is prevented by interceptor - // add entry at the beginning of the result map - - for (var _iterator3 = _createForOfIteratorHelperLoose(_this6.data_.keys()), _step3; !(_step3 = _iterator3()).done;) { - var key = _step3.value; - - // Concurrently iterating/deleting keys - // iterator should handle this correctly - if (!replacementMap.has(key)) { - var deleted = _this6["delete"](key); // Was the key removed? - - - if (deleted) { - // _keysAtom.reportChanged() was already called - keysReportChangedCalled = true; - } else { - // Delete prevented by interceptor - var value = _this6.data_.get(key); - - orderedData.set(key, value); - } - } - } // Merge entries - - - for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) { - var _step4$value = _step4.value, - _key = _step4$value[0], - _value = _step4$value[1]; - - // We will want to know whether a new key is added - var keyExisted = _this6.data_.has(_key); // Add or update value - - - _this6.set(_key, _value); // The addition could have been prevent by interceptor - - - if (_this6.data_.has(_key)) { - // The update could have been prevented by interceptor - // and also we want to preserve existing values - // so use value from _data map (instead of replacement map) - var _value2 = _this6.data_.get(_key); - - orderedData.set(_key, _value2); // Was a new key added? - - if (!keyExisted) { - // _keysAtom.reportChanged() was already called - keysReportChangedCalled = true; - } - } - } // Check for possible key order change - - - if (!keysReportChangedCalled) { - if (_this6.data_.size !== orderedData.size) { - // If size differs, keys are definitely modified - _this6.keysAtom_.reportChanged(); - } else { - var iter1 = _this6.data_.keys(); - - var iter2 = orderedData.keys(); - var next1 = iter1.next(); - var next2 = iter2.next(); - - while (!next1.done) { - if (next1.value !== next2.value) { - _this6.keysAtom_.reportChanged(); - - break; - } - - next1 = iter1.next(); - next2 = iter2.next(); - } - } - } // Use correctly ordered map - - - _this6.data_ = orderedData; - }); - return this; - }; - - _proto.toString = function toString() { - return "[object ObservableMap]"; - }; - - _proto.toJSON = function toJSON() { - return Array.from(this); - }; - - /** - * Observes this object. Triggers for the events 'add', 'update' and 'delete'. - * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe - * for callback details - */ - _proto.observe_ = function observe_(listener, fireImmediately) { - return registerListener(this, listener); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _createClass(ObservableMap, [{ - key: "size", - get: function get() { - this.keysAtom_.reportObserved(); - return this.data_.size; - } - }, { - key: _Symbol$toStringTag, - get: function get() { - return "Map"; - } - }]); - - return ObservableMap; -}(); // eslint-disable-next-line - -var isObservableMap = /*#__PURE__*/createInstanceofPredicate("ObservableMap", ObservableMap); - -function convertToMap(dataStructure) { - if (isES6Map(dataStructure) || isObservableMap(dataStructure)) { - return dataStructure; - } else if (Array.isArray(dataStructure)) { - return new Map(dataStructure); - } else if (isPlainObject$1(dataStructure)) { - var map = new Map(); - - for (var key in dataStructure) { - map.set(key, dataStructure[key]); - } - - return map; - } else { - return die(21, dataStructure); - } -} - -var _Symbol$iterator$1, _Symbol$toStringTag$1; -var ObservableSetMarker = {}; -_Symbol$iterator$1 = Symbol.iterator; -_Symbol$toStringTag$1 = Symbol.toStringTag; -var ObservableSet = /*#__PURE__*/function () { - function ObservableSet(initialData, enhancer, name_) { - if (enhancer === void 0) { - enhancer = deepEnhancer; - } - - if (name_ === void 0) { - name_ = "ObservableSet"; - } - - this.name_ = void 0; - this[$mobx] = ObservableSetMarker; - this.data_ = new Set(); - this.atom_ = void 0; - this.changeListeners_ = void 0; - this.interceptors_ = void 0; - this.dehancer = void 0; - this.enhancer_ = void 0; - this.name_ = name_; - - if (!isFunction$2(Set)) { - die(22); - } - - this.atom_ = createAtom(this.name_); - - this.enhancer_ = function (newV, oldV) { - return enhancer(newV, oldV, name_); - }; - - if (initialData) { - this.replace(initialData); - } - } - - var _proto = ObservableSet.prototype; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) { - return this.dehancer(value); - } - - return value; - }; - - _proto.clear = function clear() { - var _this = this; - - transaction(function () { - untracked(function () { - for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) { - var value = _step.value; - - _this["delete"](value); - } - }); - }); - }; - - _proto.forEach = function forEach(callbackFn, thisArg) { - for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) { - var value = _step2.value; - callbackFn.call(thisArg, value, value, this); - } - }; - - _proto.add = function add(value) { - var _this2 = this; - - checkIfStateModificationsAreAllowed(this.atom_); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: ADD, - object: this, - newValue: value - }); - if (!change) return this; // ideally, value = change.value would be done here, so that values can be - // changed by interceptor. Same applies for other Set and Map api's. - } - - if (!this.has(value)) { - transaction(function () { - _this2.data_.add(_this2.enhancer_(value, undefined)); - - _this2.atom_.reportChanged(); - }); - var notifySpy = "production" !== "production" ; - var notify = hasListeners(this); - - var _change = notify || notifySpy ? { - observableKind: "set", - debugObjectName: this.name_, - type: ADD, - object: this, - newValue: value - } : null; - if (notify) notifyListeners(this, _change); - } - - return this; - }; - - _proto["delete"] = function _delete(value) { - var _this3 = this; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: DELETE, - object: this, - oldValue: value - }); - if (!change) return false; - } - - if (this.has(value)) { - var notifySpy = "production" !== "production" ; - var notify = hasListeners(this); - - var _change2 = notify || notifySpy ? { - observableKind: "set", - debugObjectName: this.name_, - type: DELETE, - object: this, - oldValue: value - } : null; - transaction(function () { - _this3.atom_.reportChanged(); - - _this3.data_["delete"](value); - }); - if (notify) notifyListeners(this, _change2); - return true; - } - - return false; - }; - - _proto.has = function has(value) { - this.atom_.reportObserved(); - return this.data_.has(this.dehanceValue_(value)); - }; - - _proto.entries = function entries() { - var nextIndex = 0; - var keys = Array.from(this.keys()); - var values = Array.from(this.values()); - return makeIterable({ - next: function next() { - var index = nextIndex; - nextIndex += 1; - return index < values.length ? { - value: [keys[index], values[index]], - done: false - } : { - done: true - }; - } - }); - }; - - _proto.keys = function keys() { - return this.values(); - }; - - _proto.values = function values() { - this.atom_.reportObserved(); - var self = this; - var nextIndex = 0; - var observableValues = Array.from(this.data_.values()); - return makeIterable({ - next: function next() { - return nextIndex < observableValues.length ? { - value: self.dehanceValue_(observableValues[nextIndex++]), - done: false - } : { - done: true - }; - } - }); - }; - - _proto.replace = function replace(other) { - var _this4 = this; - - if (isObservableSet(other)) { - other = new Set(other); - } - - transaction(function () { - if (Array.isArray(other)) { - _this4.clear(); - - other.forEach(function (value) { - return _this4.add(value); - }); - } else if (isES6Set(other)) { - _this4.clear(); - - other.forEach(function (value) { - return _this4.add(value); - }); - } else if (other !== null && other !== undefined) { - die("Cannot initialize set from " + other); - } - }); - return this; - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - return registerListener(this, listener); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.toJSON = function toJSON() { - return Array.from(this); - }; - - _proto.toString = function toString() { - return "[object ObservableSet]"; - }; - - _proto[_Symbol$iterator$1] = function () { - return this.values(); - }; - - _createClass(ObservableSet, [{ - key: "size", - get: function get() { - this.atom_.reportObserved(); - return this.data_.size; - } - }, { - key: _Symbol$toStringTag$1, - get: function get() { - return "Set"; - } - }]); - - return ObservableSet; -}(); // eslint-disable-next-line - -var isObservableSet = /*#__PURE__*/createInstanceofPredicate("ObservableSet", ObservableSet); - -var descriptorCache = /*#__PURE__*/Object.create(null); -var REMOVE = "remove"; -var ObservableObjectAdministration = /*#__PURE__*/function () { - function ObservableObjectAdministration(target_, values_, name_, // Used anytime annotation is not explicitely provided - defaultAnnotation_) { - if (values_ === void 0) { - values_ = new Map(); - } - - if (defaultAnnotation_ === void 0) { - defaultAnnotation_ = autoAnnotation; - } - - this.target_ = void 0; - this.values_ = void 0; - this.name_ = void 0; - this.defaultAnnotation_ = void 0; - this.keysAtom_ = void 0; - this.changeListeners_ = void 0; - this.interceptors_ = void 0; - this.proxy_ = void 0; - this.isPlainObject_ = void 0; - this.appliedAnnotations_ = void 0; - this.pendingKeys_ = void 0; - this.target_ = target_; - this.values_ = values_; - this.name_ = name_; - this.defaultAnnotation_ = defaultAnnotation_; - this.keysAtom_ = new Atom("ObservableObject.keys"); // Optimization: we use this frequently - - this.isPlainObject_ = isPlainObject$1(this.target_); - } - - var _proto = ObservableObjectAdministration.prototype; - - _proto.getObservablePropValue_ = function getObservablePropValue_(key) { - return this.values_.get(key).get(); - }; - - _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) { - var observable = this.values_.get(key); - - if (observable instanceof ComputedValue) { - observable.set(newValue); - return true; - } // intercept - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: UPDATE, - object: this.proxy_ || this.target_, - name: key, - newValue: newValue - }); - if (!change) return null; - newValue = change.newValue; - } - - newValue = observable.prepareNewValue_(newValue); // notify spy & observers - - if (newValue !== globalState.UNCHANGED) { - var notify = hasListeners(this); - var notifySpy = "production" !== "production" ; - - var _change = notify || notifySpy ? { - type: UPDATE, - observableKind: "object", - debugObjectName: this.name_, - object: this.proxy_ || this.target_, - oldValue: observable.value_, - name: key, - newValue: newValue - } : null; - observable.setNewValue_(newValue); - if (notify) notifyListeners(this, _change); - } - - return true; - }; - - _proto.get_ = function get_(key) { - if (globalState.trackingDerivation && !hasProp(this.target_, key)) { - // Key doesn't exist yet, subscribe for it in case it's added later - this.has_(key); - } - - return this.target_[key]; - } - /** - * @param {PropertyKey} key - * @param {any} value - * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is - * @param {boolean} proxyTrap whether it's called from proxy trap - * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor - */ - ; - - _proto.set_ = function set_(key, value, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - // Don't use .has(key) - we care about own - if (hasProp(this.target_, key)) { - // Existing prop - if (this.values_.has(key)) { - // Observable (can be intercepted) - return this.setObservablePropValue_(key, value); - } else if (proxyTrap) { - // Non-observable - proxy - return Reflect.set(this.target_, key, value); - } else { - // Non-observable - this.target_[key] = value; - return true; - } - } else { - // New prop - return this.extend_(key, { - value: value, - enumerable: true, - writable: true, - configurable: true - }, this.defaultAnnotation_, proxyTrap); - } - } // Trap for "in" - ; - - _proto.has_ = function has_(key) { - if (!globalState.trackingDerivation) { - // Skip key subscription outside derivation - return key in this.target_; - } - - this.pendingKeys_ || (this.pendingKeys_ = new Map()); - var entry = this.pendingKeys_.get(key); - - if (!entry) { - entry = new ObservableValue(key in this.target_, referenceEnhancer, "ObservableObject.key?", false); - this.pendingKeys_.set(key, entry); - } - - return entry.get(); - } - /** - * @param {PropertyKey} key - * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop - */ - ; - - _proto.make_ = function make_(key, annotation) { - if (annotation === true) { - annotation = this.defaultAnnotation_; - } - - if (annotation === false) { - return; - } - - if (!(key in this.target_)) { - var _this$target_$storedA; - - // Throw on missing key, except for decorators: - // Decorator annotations are collected from whole prototype chain. - // When called from super() some props may not exist yet. - // However we don't have to worry about missing prop, - // because the decorator must have been applied to something. - if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) == null ? void 0 : _this$target_$storedA[key]) { - return; // will be annotated by subclass constructor - } else { - die(1, annotation.annotationType_, this.name_ + "." + key.toString()); - } - } - - var source = this.target_; - - while (source && source !== objectPrototype) { - var descriptor = getDescriptor(source, key); - - if (descriptor) { - var outcome = annotation.make_(this, key, descriptor, source); - if (outcome === 0 - /* Cancel */ - ) return; - if (outcome === 1 - /* Break */ - ) break; - } - - source = Object.getPrototypeOf(source); - } - - recordAnnotationApplied(this, annotation, key); - } - /** - * @param {PropertyKey} key - * @param {PropertyDescriptor} descriptor - * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is - * @param {boolean} proxyTrap whether it's called from proxy trap - * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor - */ - ; - - _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - if (annotation === true) { - annotation = this.defaultAnnotation_; - } - - if (annotation === false) { - return this.defineProperty_(key, descriptor, proxyTrap); - } - var outcome = annotation.extend_(this, key, descriptor, proxyTrap); - - if (outcome) { - recordAnnotationApplied(this, annotation, key); - } - - return outcome; - } - /** - * @param {PropertyKey} key - * @param {PropertyDescriptor} descriptor - * @param {boolean} proxyTrap whether it's called from proxy trap - * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor - */ - ; - - _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - try { - startBatch(); // Delete - - var deleteOutcome = this.delete_(key); - - if (!deleteOutcome) { - // Failure or intercepted - return deleteOutcome; - } // ADD interceptor - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || this.target_, - name: key, - type: ADD, - newValue: descriptor.value - }); - if (!change) return null; - var newValue = change.newValue; - - if (descriptor.value !== newValue) { - descriptor = _extends({}, descriptor, { - value: newValue - }); - } - } // Define - - - if (proxyTrap) { - if (!Reflect.defineProperty(this.target_, key, descriptor)) { - return false; - } - } else { - defineProperty$2(this.target_, key, descriptor); - } // Notify - - - this.notifyPropertyAddition_(key, descriptor.value); - } finally { - endBatch(); - } - - return true; - } // If original descriptor becomes relevant, move this to annotation directly - ; - - _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - try { - startBatch(); // Delete - - var deleteOutcome = this.delete_(key); - - if (!deleteOutcome) { - // Failure or intercepted - return deleteOutcome; - } // ADD interceptor - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || this.target_, - name: key, - type: ADD, - newValue: value - }); - if (!change) return null; - value = change.newValue; - } - - var cachedDescriptor = getCachedObservablePropDescriptor(key); - var descriptor = { - configurable: globalState.safeDescriptors ? this.isPlainObject_ : true, - enumerable: true, - get: cachedDescriptor.get, - set: cachedDescriptor.set - }; // Define - - if (proxyTrap) { - if (!Reflect.defineProperty(this.target_, key, descriptor)) { - return false; - } - } else { - defineProperty$2(this.target_, key, descriptor); - } - - var observable = new ObservableValue(value, enhancer, "production" !== "production" ? this.name_ + "." + key.toString() : "ObservableObject.key", false); - this.values_.set(key, observable); // Notify (value possibly changed by ObservableValue) - - this.notifyPropertyAddition_(key, observable.value_); - } finally { - endBatch(); - } - - return true; - } // If original descriptor becomes relevant, move this to annotation directly - ; - - _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - try { - startBatch(); // Delete - - var deleteOutcome = this.delete_(key); - - if (!deleteOutcome) { - // Failure or intercepted - return deleteOutcome; - } // ADD interceptor - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || this.target_, - name: key, - type: ADD, - newValue: undefined - }); - if (!change) return null; - } - - options.name || (options.name = "production" !== "production" ? this.name_ + "." + key.toString() : "ObservableObject.key"); - options.context = this.proxy_ || this.target_; - var cachedDescriptor = getCachedObservablePropDescriptor(key); - var descriptor = { - configurable: globalState.safeDescriptors ? this.isPlainObject_ : true, - enumerable: false, - get: cachedDescriptor.get, - set: cachedDescriptor.set - }; // Define - - if (proxyTrap) { - if (!Reflect.defineProperty(this.target_, key, descriptor)) { - return false; - } - } else { - defineProperty$2(this.target_, key, descriptor); - } - - this.values_.set(key, new ComputedValue(options)); // Notify - - this.notifyPropertyAddition_(key, undefined); - } finally { - endBatch(); - } - - return true; - } - /** - * @param {PropertyKey} key - * @param {PropertyDescriptor} descriptor - * @param {boolean} proxyTrap whether it's called from proxy trap - * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor - */ - ; - - _proto.delete_ = function delete_(key, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - // No such prop - if (!hasProp(this.target_, key)) { - return true; - } // Intercept - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || this.target_, - name: key, - type: REMOVE - }); // Cancelled - - if (!change) return null; - } // Delete - - - try { - var _this$pendingKeys_, _this$pendingKeys_$ge; - - startBatch(); - var notify = hasListeners(this); - var notifySpy = "production" !== "production" && isSpyEnabled(); - var observable = this.values_.get(key); // Value needed for spies/listeners - - var value = undefined; // Optimization: don't pull the value unless we will need it - - if (!observable && (notify || notifySpy)) { - var _getDescriptor; - - value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value; - } // delete prop (do first, may fail) - - - if (proxyTrap) { - if (!Reflect.deleteProperty(this.target_, key)) { - return false; - } - } else { - delete this.target_[key]; - } // Allow re-annotating this field - - - if ("production" !== "production") ; // Clear observable - - - if (observable) { - this.values_["delete"](key); // for computed, value is undefined - - if (observable instanceof ObservableValue) { - value = observable.value_; - } // Notify: autorun(() => obj[key]), see #1796 - - - propagateChanged(observable); - } // Notify "keys/entries/values" observers - - - this.keysAtom_.reportChanged(); // Notify "has" observers - // "in" as it may still exist in proto - - (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_); // Notify spies/listeners - - if (notify || notifySpy) { - var _change2 = { - type: REMOVE, - observableKind: "object", - object: this.proxy_ || this.target_, - debugObjectName: this.name_, - oldValue: value, - name: key - }; - if ("production" !== "production" && notifySpy) ; - if (notify) notifyListeners(this, _change2); - if ("production" !== "production" && notifySpy) ; - } - } finally { - endBatch(); - } - - return true; - } - /** - * Observes this object. Triggers for the events 'add', 'update' and 'delete'. - * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe - * for callback details - */ - ; - - _proto.observe_ = function observe_(callback, fireImmediately) { - return registerListener(this, callback); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) { - var _this$pendingKeys_2, _this$pendingKeys_2$g; - - var notify = hasListeners(this); - var notifySpy = "production" !== "production" ; - - if (notify || notifySpy) { - var change = notify || notifySpy ? { - type: ADD, - observableKind: "object", - debugObjectName: this.name_, - object: this.proxy_ || this.target_, - name: key, - newValue: value - } : null; - if (notify) notifyListeners(this, change); - } - - (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true); // Notify "keys/entries/values" observers - - this.keysAtom_.reportChanged(); - }; - - _proto.ownKeys_ = function ownKeys_() { - this.keysAtom_.reportObserved(); - return ownKeys(this.target_); - }; - - _proto.keys_ = function keys_() { - // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change. - // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap. - // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object) - // We choose to over-report in Object.keys(object), because: - // - typically it's used with simple data objects - // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected - this.keysAtom_.reportObserved(); - return Object.keys(this.target_); - }; - - return ObservableObjectAdministration; -}(); -function asObservableObject(target, options) { - var _options$name; - - if (hasProp(target, $mobx)) { - - return target; - } - var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : "ObservableObject"; - var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options)); - addHiddenProp(target, $mobx, adm); - return target; -} -var isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration); - -function getCachedObservablePropDescriptor(key) { - return descriptorCache[key] || (descriptorCache[key] = { - get: function get() { - return this[$mobx].getObservablePropValue_(key); - }, - set: function set(value) { - return this[$mobx].setObservablePropValue_(key, value); - } - }); -} - -function isObservableObject(thing) { - if (isObject$2(thing)) { - return isObservableObjectAdministration(thing[$mobx]); - } - - return false; -} -function recordAnnotationApplied(adm, annotation, key) { - var _adm$target_$storedAn; - - - (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key]; -} - -/** - * This array buffer contains two lists of properties, so that all arrays - * can recycle their property definitions, which significantly improves performance of creating - * properties on the fly. - */ - -var OBSERVABLE_ARRAY_BUFFER_SIZE = 0; // Typescript workaround to make sure ObservableArray extends Array - -var StubArray = function StubArray() {}; - -function inherit(ctor, proto) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(ctor.prototype, proto); - } else if (ctor.prototype.__proto__ !== undefined) { - ctor.prototype.__proto__ = proto; - } else { - ctor.prototype = proto; - } -} - -inherit(StubArray, Array.prototype); // Weex proto freeze protection was here, -// but it is unclear why the hack is need as MobX never changed the prototype -// anyway, so removed it in V6 - -var LegacyObservableArray = /*#__PURE__*/function (_StubArray) { - _inheritsLoose(LegacyObservableArray, _StubArray); - - function LegacyObservableArray(initialValues, enhancer, name, owned) { - var _this; - - if (name === void 0) { - name = "ObservableArray"; - } - - if (owned === void 0) { - owned = false; - } - - _this = _StubArray.call(this) || this; - var adm = new ObservableArrayAdministration(name, enhancer, owned, true); - adm.proxy_ = _assertThisInitialized(_this); - addHiddenFinalProp$1(_assertThisInitialized(_this), $mobx, adm); - - if (initialValues && initialValues.length) { - var prev = allowStateChangesStart(true); // @ts-ignore - - _this.spliceWithArray(0, 0, initialValues); - - allowStateChangesEnd(prev); - } - - return _this; - } - - var _proto = LegacyObservableArray.prototype; - - _proto.concat = function concat() { - this[$mobx].atom_.reportObserved(); - - for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { - arrays[_key] = arguments[_key]; - } - - return Array.prototype.concat.apply(this.slice(), //@ts-ignore - arrays.map(function (a) { - return isObservableArray(a) ? a.slice() : a; - })); - }; - - _proto[Symbol.iterator] = function () { - var self = this; - var nextIndex = 0; - return makeIterable({ - next: function next() { - // @ts-ignore - return nextIndex < self.length ? { - value: self[nextIndex++], - done: false - } : { - done: true, - value: undefined - }; - } - }); - }; - - _createClass(LegacyObservableArray, [{ - key: "length", - get: function get() { - return this[$mobx].getArrayLength_(); - }, - set: function set(newLength) { - this[$mobx].setArrayLength_(newLength); - } - }, { - key: Symbol.toStringTag, - get: function get() { - return "Array"; - } - }]); - - return LegacyObservableArray; -}(StubArray); - -Object.entries(arrayExtensions).forEach(function (_ref) { - var prop = _ref[0], - fn = _ref[1]; - if (prop !== "concat") addHiddenProp(LegacyObservableArray.prototype, prop, fn); -}); - -function createArrayEntryDescriptor(index) { - return { - enumerable: false, - configurable: true, - get: function get() { - return this[$mobx].get_(index); - }, - set: function set(value) { - this[$mobx].set_(index, value); - } - }; -} - -function createArrayBufferItem(index) { - defineProperty$2(LegacyObservableArray.prototype, "" + index, createArrayEntryDescriptor(index)); -} - -function reserveArrayBuffer(max) { - if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) { - for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) { - createArrayBufferItem(index); - } - - OBSERVABLE_ARRAY_BUFFER_SIZE = max; - } -} -reserveArrayBuffer(1000); -function createLegacyArray(initialValues, enhancer, name) { - return new LegacyObservableArray(initialValues, enhancer, name); -} - -function getAtom(thing, property) { - if (typeof thing === "object" && thing !== null) { - if (isObservableArray(thing)) { - if (property !== undefined) die(23); - return thing[$mobx].atom_; - } - - if (isObservableSet(thing)) { - return thing[$mobx]; - } - - if (isObservableMap(thing)) { - if (property === undefined) return thing.keysAtom_; - var observable = thing.data_.get(property) || thing.hasMap_.get(property); - if (!observable) die(25, property, getDebugName(thing)); - return observable; - } - - if (isObservableObject(thing)) { - if (!property) return die(26); - - var _observable = thing[$mobx].values_.get(property); - - if (!_observable) die(27, property, getDebugName(thing)); - return _observable; - } - - if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { - return thing; - } - } else if (isFunction$2(thing)) { - if (isReaction(thing[$mobx])) { - // disposer function - return thing[$mobx]; - } - } - - die(28); -} -function getAdministration(thing, property) { - if (!thing) die(29); - if (property !== undefined) return getAdministration(getAtom(thing, property)); - if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) return thing; - if (isObservableMap(thing) || isObservableSet(thing)) return thing; - if (thing[$mobx]) return thing[$mobx]; - die(24, thing); -} -function getDebugName(thing, property) { - var named; - - if (property !== undefined) { - named = getAtom(thing, property); - } else if (isAction(thing)) { - return thing.name; - } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) { - named = getAdministration(thing); - } else { - // valid for arrays as well - named = getAtom(thing); - } - - return named.name_; -} - -var toString$1 = objectPrototype.toString; -function deepEqual(a, b, depth) { - if (depth === void 0) { - depth = -1; - } - - return eq$1(a, b, depth); -} // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289 -// Internal recursive comparison function for `isEqual`. - -function eq$1(a, b, depth, aStack, bStack) { - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). - if (a === b) return a !== 0 || 1 / a === 1 / b; // `null` or `undefined` only equal to itself (strict comparison). - - if (a == null || b == null) return false; // `NaN`s are equivalent, but non-reflexive. - - if (a !== a) return b !== b; // Exhaust primitive checks - - var type = typeof a; - if (!isFunction$2(type) && type !== "object" && typeof b != "object") return false; // Compare `[[Class]]` names. - - var className = toString$1.call(a); - if (className !== toString$1.call(b)) return false; - - switch (className) { - // Strings, numbers, regular expressions, dates, and booleans are compared by value. - case "[object RegExp]": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') - - case "[object String]": - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - return "" + a === "" + b; - - case "[object Number]": - // `NaN`s are equivalent, but non-reflexive. - // Object(NaN) is equivalent to NaN. - if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. - - return +a === 0 ? 1 / +a === 1 / b : +a === +b; - - case "[object Date]": - case "[object Boolean]": - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - return +a === +b; - - case "[object Symbol]": - return typeof Symbol !== "undefined" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b); - - case "[object Map]": - case "[object Set]": - // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level. - // Hide this extra level by increasing the depth. - if (depth >= 0) { - depth++; - } - - break; - } // Unwrap any wrapped objects. - - - a = unwrap(a); - b = unwrap(b); - var areArrays = className === "[object Array]"; - - if (!areArrays) { - if (typeof a != "object" || typeof b != "object") return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s - // from different frames are. - - var aCtor = a.constructor, - bCtor = b.constructor; - - if (aCtor !== bCtor && !(isFunction$2(aCtor) && aCtor instanceof aCtor && isFunction$2(bCtor) && bCtor instanceof bCtor) && "constructor" in a && "constructor" in b) { - return false; - } - } - - if (depth === 0) { - return false; - } else if (depth < 0) { - depth = -1; - } // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - // Initializing stack of traversed objects. - // It's done here since we only need them for objects and arrays comparison. - - - aStack = aStack || []; - bStack = bStack || []; - var length = aStack.length; - - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (aStack[length] === a) return bStack[length] === b; - } // Add the first object to the stack of traversed objects. - - - aStack.push(a); - bStack.push(b); // Recursively compare objects and arrays. - - if (areArrays) { - // Compare array lengths to determine if a deep comparison is necessary. - length = a.length; - if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. - - while (length--) { - if (!eq$1(a[length], b[length], depth - 1, aStack, bStack)) return false; - } - } else { - // Deep compare objects. - var keys = Object.keys(a); - var key; - length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. - - if (Object.keys(b).length !== length) return false; - - while (length--) { - // Deep compare each member - key = keys[length]; - if (!(hasProp(b, key) && eq$1(a[key], b[key], depth - 1, aStack, bStack))) return false; - } - } // Remove the first object from the stack of traversed objects. - - - aStack.pop(); - bStack.pop(); - return true; -} - -function unwrap(a) { - if (isObservableArray(a)) return a.slice(); - if (isES6Map(a) || isObservableMap(a)) return Array.from(a.entries()); - if (isES6Set(a) || isObservableSet(a)) return Array.from(a.entries()); - return a; -} - -function makeIterable(iterator) { - iterator[Symbol.iterator] = getSelf; - return iterator; -} - -function getSelf() { - return this; -} - -/** - * (c) Michel Weststrate 2015 - 2020 - * MIT Licensed - * - * Welcome to the mobx sources! To get an global overview of how MobX internally works, - * this is a good place to start: - * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74 - * - * Source folders: - * =============== - * - * - api/ Most of the public static methods exposed by the module can be found here. - * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here. - * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`. - * - utils/ Utility stuff. - * - */ -["Symbol", "Map", "Set", "Symbol"].forEach(function (m) { - var g = getGlobal(); - - if (typeof g[m] === "undefined") { - die("MobX requires global '" + m + "' to be available or polyfilled"); - } -}); - -if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "object") { - // See: https://github.com/andykog/mobx-devtools/ - __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({ - spy: spy, - extras: { - getDebugName: getDebugName - }, - $mobx: $mobx - }); -} - -var livelinessChecking = "warn"; -/** - * Returns the current liveliness checking mode. - * - * @returns `"warn"`, `"error"` or `"ignore"` - */ -function getLivelinessChecking() { - return livelinessChecking; -} - -/** - * @hidden - */ -var Hook; -(function (Hook) { - Hook["afterCreate"] = "afterCreate"; - Hook["afterAttach"] = "afterAttach"; - Hook["afterCreationFinalization"] = "afterCreationFinalization"; - Hook["beforeDetach"] = "beforeDetach"; - Hook["beforeDestroy"] = "beforeDestroy"; -})(Hook || (Hook = {})); - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics$1 = function(d, b) { - extendStatics$1 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics$1(d, b); -}; - -function __extends$1(d, b) { - extendStatics$1(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -/** - * Returns the _actual_ type of the given tree node. (Or throws) - * - * @param object - * @returns - */ -function getType(object) { - return getStateTreeNode(object).type; -} -/** - * Applies a JSON-patch to the given model instance or bails out if the patch couldn't be applied - * See [patches](https://github.com/mobxjs/mobx-state-tree#patches) for more details. - * - * Can apply a single past, or an array of patches. - * - * @param target - * @param patch - * @returns - */ -function applyPatch(target, patch) { - getStateTreeNode(target).applyPatches(asArray(patch)); -} -/** - * Applies a snapshot to a given model instances. Patch and snapshot listeners will be invoked as usual. - * - * @param target - * @param snapshot - * @returns - */ -function applySnapshot(target, snapshot) { - return getStateTreeNode(target).applySnapshot(snapshot); -} -/** - * Calculates a snapshot from the given model instance. The snapshot will always reflect the latest state but use - * structural sharing where possible. Doesn't require MobX transactions to be completed. - * - * @param target - * @param applyPostProcess If true (the default) then postProcessSnapshot gets applied. - * @returns - */ -function getSnapshot(target, applyPostProcess) { - if (applyPostProcess === void 0) { applyPostProcess = true; } - var node = getStateTreeNode(target); - if (applyPostProcess) - return node.snapshot; - return freeze(node.type.getSnapshot(node, false)); -} -/** - * Given an object in a model tree, returns the root object of that tree. - * - * Please note that in child nodes access to the root is only possible - * once the `afterAttach` hook has fired. - * - * @param target - * @returns - */ -function getRoot(target) { - return getStateTreeNode(target).root.storedValue; -} -/** - * Returns the path of the given object in the model tree - * - * @param target - * @returns - */ -function getPath(target) { - return getStateTreeNode(target).path; -} -/** - * Returns the identifier of the target node. - * This is the *string normalized* identifier, which might not match the type of the identifier attribute - * - * @param target - * @returns - */ -function getIdentifier(target) { - return getStateTreeNode(target).identifier; -} -/** - * Removes a model element from the state tree, and mark it as end-of-life; the element should not be used anymore - */ -function destroy(target) { - var node = getStateTreeNode(target); - if (node.isRoot) - node.die(); - else - node.parent.removeChild(node.subpath); -} - -/** - * @internal - * @hidden - */ -var BaseNode = /** @class */ (function () { - function BaseNode(type, parent, subpath, environment) { - Object.defineProperty(this, "type", { - enumerable: true, - configurable: true, - writable: true, - value: type - }); - Object.defineProperty(this, "environment", { - enumerable: true, - configurable: true, - writable: true, - value: environment - }); - Object.defineProperty(this, "_escapedSubpath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_subpath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_subpathUponDeath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_pathUponDeath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "storedValue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); // usually the same type as the value, but not always (such as with references) - Object.defineProperty(this, "aliveAtom", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_state", { - enumerable: true, - configurable: true, - writable: true, - value: NodeLifeCycle.INITIALIZING - }); - Object.defineProperty(this, "_hookSubscribers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_parent", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "pathAtom", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.environment = environment; - this.baseSetParent(parent, subpath); - } - Object.defineProperty(BaseNode.prototype, "subpath", { - get: function () { - return this._subpath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "subpathUponDeath", { - get: function () { - return this._subpathUponDeath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "pathUponDeath", { - get: function () { - return this._pathUponDeath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "value", { - get: function () { - return this.type.getValue(this); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "state", { - get: function () { - return this._state; - }, - set: function (val) { - var wasAlive = this.isAlive; - this._state = val; - var isAlive = this.isAlive; - if (this.aliveAtom && wasAlive !== isAlive) { - this.aliveAtom.reportChanged(); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "fireInternalHook", { - enumerable: false, - configurable: true, - writable: true, - value: function (name) { - if (this._hookSubscribers) { - this._hookSubscribers.emit(name, this, name); - } - } - }); - Object.defineProperty(BaseNode.prototype, "registerHook", { - enumerable: false, - configurable: true, - writable: true, - value: function (hook, hookHandler) { - if (!this._hookSubscribers) { - this._hookSubscribers = new EventHandlers(); - } - return this._hookSubscribers.register(hook, hookHandler); - } - }); - Object.defineProperty(BaseNode.prototype, "parent", { - get: function () { - return this._parent; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "baseSetParent", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath) { - this._parent = parent; - this._subpath = subpath; - this._escapedSubpath = undefined; // regenerate when needed - if (this.pathAtom) { - this.pathAtom.reportChanged(); - } - } - }); - Object.defineProperty(BaseNode.prototype, "path", { - /* - * Returns (escaped) path representation as string - */ - get: function () { - return this.getEscapedPath(true); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "getEscapedPath", { - enumerable: false, - configurable: true, - writable: true, - value: function (reportObserved) { - if (reportObserved) { - if (!this.pathAtom) { - this.pathAtom = createAtom("path"); - } - this.pathAtom.reportObserved(); - } - if (!this.parent) - return ""; - // regenerate escaped subpath if needed - if (this._escapedSubpath === undefined) { - this._escapedSubpath = !this._subpath ? "" : escapeJsonPath(this._subpath); - } - return this.parent.getEscapedPath(reportObserved) + "/" + this._escapedSubpath; - } - }); - Object.defineProperty(BaseNode.prototype, "isRoot", { - get: function () { - return this.parent === null; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "isAlive", { - get: function () { - return this.state !== NodeLifeCycle.DEAD; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "isDetaching", { - get: function () { - return this.state === NodeLifeCycle.DETACHING; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "observableIsAlive", { - get: function () { - if (!this.aliveAtom) { - this.aliveAtom = createAtom("alive"); - } - this.aliveAtom.reportObserved(); - return this.isAlive; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "baseFinalizeCreation", { - enumerable: false, - configurable: true, - writable: true, - value: function (whenFinalized) { - // goal: afterCreate hooks runs depth-first. After attach runs parent first, so on afterAttach the parent has completed already - if (this.state === NodeLifeCycle.CREATED) { - if (this.parent) { - if (this.parent.state !== NodeLifeCycle.FINALIZED) { - // parent not ready yet, postpone - return; - } - this.fireHook(Hook.afterAttach); - } - this.state = NodeLifeCycle.FINALIZED; - if (whenFinalized) { - whenFinalized(); - } - } - } - }); - Object.defineProperty(BaseNode.prototype, "baseFinalizeDeath", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._hookSubscribers) { - this._hookSubscribers.clearAll(); - } - this._subpathUponDeath = this._subpath; - this._pathUponDeath = this.getEscapedPath(false); - this.baseSetParent(null, ""); - this.state = NodeLifeCycle.DEAD; - } - }); - Object.defineProperty(BaseNode.prototype, "baseAboutToDie", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.fireHook(Hook.beforeDestroy); - } - }); - return BaseNode; -}()); - -/** - * @internal - * @hidden - */ -var ScalarNode = /** @class */ (function (_super) { - __extends$1(ScalarNode, _super); - function ScalarNode(simpleType, parent, subpath, environment, initialSnapshot) { - var _this = _super.call(this, simpleType, parent, subpath, environment) || this; - try { - _this.storedValue = simpleType.createNewInstance(initialSnapshot); - } - catch (e) { - // short-cut to die the instance, to avoid the snapshot computed starting to throw... - _this.state = NodeLifeCycle.DEAD; - throw e; - } - _this.state = NodeLifeCycle.CREATED; - // for scalar nodes there's no point in firing this event since it would fire on the constructor, before - // anybody can actually register for/listen to it - // this.fireHook(Hook.AfterCreate) - _this.finalizeCreation(); - return _this; - } - Object.defineProperty(ScalarNode.prototype, "root", { - get: function () { - // future optimization: store root ref in the node and maintain it - if (!this.parent) - throw fail$1("This scalar node is not part of a tree"); - return this.parent.root; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ScalarNode.prototype, "setParent", { - enumerable: false, - configurable: true, - writable: true, - value: function (newParent, subpath) { - var parentChanged = this.parent !== newParent; - var subpathChanged = this.subpath !== subpath; - if (!parentChanged && !subpathChanged) { - return; - } - this.environment = undefined; // use parent's - this.baseSetParent(this.parent, subpath); - } - }); - Object.defineProperty(ScalarNode.prototype, "snapshot", { - get: function () { - return freeze(this.getSnapshot()); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ScalarNode.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.type.getSnapshot(this); - } - }); - Object.defineProperty(ScalarNode.prototype, "toString", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var path = (this.isAlive ? this.path : this.pathUponDeath) || ""; - return this.type.name + "@" + path + (this.isAlive ? "" : " [dead]"); - } - }); - Object.defineProperty(ScalarNode.prototype, "die", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) - return; - this.aboutToDie(); - this.finalizeDeath(); - } - }); - Object.defineProperty(ScalarNode.prototype, "finalizeCreation", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.baseFinalizeCreation(); - } - }); - Object.defineProperty(ScalarNode.prototype, "aboutToDie", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.baseAboutToDie(); - } - }); - Object.defineProperty(ScalarNode.prototype, "finalizeDeath", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.baseFinalizeDeath(); - } - }); - Object.defineProperty(ScalarNode.prototype, "fireHook", { - enumerable: false, - configurable: true, - writable: true, - value: function (name) { - this.fireInternalHook(name); - } - }); - return ScalarNode; -}(BaseNode)); -ScalarNode.prototype.die = action(ScalarNode.prototype.die); - -var nextNodeId = 1; -var snapshotReactionOptions = { - onError: function (e) { - throw e; - } -}; -/** - * @internal - * @hidden - */ -var ObjectNode = /** @class */ (function (_super) { - __extends$1(ObjectNode, _super); - function ObjectNode(complexType, parent, subpath, environment, initialValue) { - var _this = _super.call(this, complexType, parent, subpath, environment) || this; - Object.defineProperty(_this, "nodeId", { - enumerable: true, - configurable: true, - writable: true, - value: ++nextNodeId - }); - Object.defineProperty(_this, "identifierAttribute", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "identifier", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); // Identifier is always normalized to string, even if the identifier property isn't - Object.defineProperty(_this, "unnormalizedIdentifier", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "identifierCache", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "isProtectionEnabled", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(_this, "middlewares", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_applyPatches", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_applySnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_autoUnbox", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); // unboxing is disabled when reading child nodes - Object.defineProperty(_this, "_isRunningAction", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); // only relevant for root - Object.defineProperty(_this, "_hasSnapshotReaction", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(_this, "_observableInstanceState", { - enumerable: true, - configurable: true, - writable: true, - value: 0 /* UNINITIALIZED */ - }); - Object.defineProperty(_this, "_childNodes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_initialSnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_cachedInitialSnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_cachedInitialSnapshotCreated", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(_this, "_snapshotComputed", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_snapshotUponDeath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // #region internal event handling - Object.defineProperty(_this, "_internalEvents", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - _this._snapshotComputed = computed(function () { return freeze(_this.getSnapshot()); }); - _this.unbox = _this.unbox.bind(_this); - _this._initialSnapshot = freeze(initialValue); - _this.identifierAttribute = complexType.identifierAttribute; - if (!parent) { - _this.identifierCache = new IdentifierCache(); - } - _this._childNodes = complexType.initializeChildNodes(_this, _this._initialSnapshot); - // identifier can not be changed during lifecycle of a node - // so we safely can read it from initial snapshot - _this.identifier = null; - _this.unnormalizedIdentifier = null; - if (_this.identifierAttribute && _this._initialSnapshot) { - var id = _this._initialSnapshot[_this.identifierAttribute]; - if (id === undefined) { - // try with the actual node if not (for optional identifiers) - var childNode = _this._childNodes[_this.identifierAttribute]; - if (childNode) { - id = childNode.value; - } - } - if (typeof id !== "string" && typeof id !== "number") { - throw fail$1("Instance identifier '" + _this.identifierAttribute + "' for type '" + _this.type.name + "' must be a string or a number"); - } - // normalize internal identifier to string - _this.identifier = normalizeIdentifier(id); - _this.unnormalizedIdentifier = id; - } - if (!parent) { - _this.identifierCache.addNodeToCache(_this); - } - else { - parent.root.identifierCache.addNodeToCache(_this); - } - return _this; - } - Object.defineProperty(ObjectNode.prototype, "applyPatches", { - enumerable: false, - configurable: true, - writable: true, - value: function (patches) { - this.createObservableInstanceIfNeeded(); - this._applyPatches(patches); - } - }); - Object.defineProperty(ObjectNode.prototype, "applySnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - this.createObservableInstanceIfNeeded(); - this._applySnapshot(snapshot); - } - }); - Object.defineProperty(ObjectNode.prototype, "createObservableInstanceIfNeeded", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._observableInstanceState === 0 /* UNINITIALIZED */) { - this.createObservableInstance(); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "createObservableInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var e_1, _a; - this._observableInstanceState = 1 /* CREATING */; - // make sure the parent chain is created as well - // array with parent chain from parent to child - var parentChain = []; - var parent = this.parent; - // for performance reasons we never go back further than the most direct - // uninitialized parent - // this is done to avoid traversing the whole tree to the root when using - // the same reference again - while (parent && - parent._observableInstanceState === 0 /* UNINITIALIZED */) { - parentChain.unshift(parent); - parent = parent.parent; - } - try { - // initialize the uninitialized parent chain from parent to child - for (var parentChain_1 = __values(parentChain), parentChain_1_1 = parentChain_1.next(); !parentChain_1_1.done; parentChain_1_1 = parentChain_1.next()) { - var p = parentChain_1_1.value; - p.createObservableInstanceIfNeeded(); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (parentChain_1_1 && !parentChain_1_1.done && (_a = parentChain_1.return)) _a.call(parentChain_1); - } - finally { if (e_1) throw e_1.error; } - } - var type = this.type; - try { - this.storedValue = type.createNewInstance(this._childNodes); - this.preboot(); - this._isRunningAction = true; - type.finalizeNewInstance(this, this.storedValue); - } - catch (e) { - // short-cut to die the instance, to avoid the snapshot computed starting to throw... - this.state = NodeLifeCycle.DEAD; - throw e; - } - finally { - this._isRunningAction = false; - } - this._observableInstanceState = 2 /* CREATED */; - this._snapshotComputed.trackAndCompute(); - if (this.isRoot) - this._addSnapshotReaction(); - this._childNodes = EMPTY_OBJECT; - this.state = NodeLifeCycle.CREATED; - this.fireHook(Hook.afterCreate); - this.finalizeCreation(); - } - }); - Object.defineProperty(ObjectNode.prototype, "root", { - get: function () { - var parent = this.parent; - return parent ? parent.root : this; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectNode.prototype, "clearParent", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.parent) - return; - // detach if attached - this.fireHook(Hook.beforeDetach); - var previousState = this.state; - this.state = NodeLifeCycle.DETACHING; - var root = this.root; - var newEnv = root.environment; - var newIdCache = root.identifierCache.splitCache(this); - try { - this.parent.removeChild(this.subpath); - this.baseSetParent(null, ""); - this.environment = newEnv; - this.identifierCache = newIdCache; - } - finally { - this.state = previousState; - } - } - }); - Object.defineProperty(ObjectNode.prototype, "setParent", { - enumerable: false, - configurable: true, - writable: true, - value: function (newParent, subpath) { - var parentChanged = newParent !== this.parent; - var subpathChanged = subpath !== this.subpath; - if (!parentChanged && !subpathChanged) { - return; - } - if (parentChanged) { - // attach to new parent - this.environment = undefined; // will use root's - newParent.root.identifierCache.mergeCache(this); - this.baseSetParent(newParent, subpath); - this.fireHook(Hook.afterAttach); - } - else if (subpathChanged) { - // moving to a new subpath on the same parent - this.baseSetParent(this.parent, subpath); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "fireHook", { - enumerable: false, - configurable: true, - writable: true, - value: function (name) { - var _this = this; - this.fireInternalHook(name); - var fn = this.storedValue && - typeof this.storedValue === "object" && - this.storedValue[name]; - if (typeof fn === "function") { - // we check for it to allow old mobx peer dependencies that don't have the method to work (even when still bugged) - if (runInAction) { - runInAction(function () { - fn.apply(_this.storedValue); - }); - } - else { - fn.apply(this.storedValue); - } - } - } - }); - Object.defineProperty(ObjectNode.prototype, "snapshot", { - // advantage of using computed for a snapshot is that nicely respects transactions etc. - get: function () { - return this._snapshotComputed.get(); - }, - enumerable: false, - configurable: true - }); - // NOTE: we use this method to get snapshot without creating @computed overhead - Object.defineProperty(ObjectNode.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.isAlive) - return this._snapshotUponDeath; - return this._observableInstanceState === 2 /* CREATED */ - ? this._getActualSnapshot() - : this._getCachedInitialSnapshot(); - } - }); - Object.defineProperty(ObjectNode.prototype, "_getActualSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.type.getSnapshot(this); - } - }); - Object.defineProperty(ObjectNode.prototype, "_getCachedInitialSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this._cachedInitialSnapshotCreated) { - var type = this.type; - var childNodes = this._childNodes; - var snapshot = this._initialSnapshot; - this._cachedInitialSnapshot = type.processInitialSnapshot(childNodes, snapshot); - this._cachedInitialSnapshotCreated = true; - } - return this._cachedInitialSnapshot; - } - }); - Object.defineProperty(ObjectNode.prototype, "isRunningAction", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._isRunningAction) - return true; - if (this.isRoot) - return false; - return this.parent.isRunningAction(); - } - }); - Object.defineProperty(ObjectNode.prototype, "assertAlive", { - enumerable: false, - configurable: true, - writable: true, - value: function (context) { - var livelinessChecking = getLivelinessChecking(); - if (!this.isAlive && livelinessChecking !== "ignore") { - var error = this._getAssertAliveError(context); - switch (livelinessChecking) { - case "error": - throw fail$1(error); - case "warn": - warnError(error); - } - } - } - }); - Object.defineProperty(ObjectNode.prototype, "_getAssertAliveError", { - enumerable: false, - configurable: true, - writable: true, - value: function (context) { - var escapedPath = this.getEscapedPath(false) || this.pathUponDeath || ""; - var subpath = (context.subpath && escapeJsonPath(context.subpath)) || ""; - var actionContext = context.actionContext || getCurrentActionContext(); - // try to use a real action context if possible since it includes the action name - if (actionContext && actionContext.type !== "action" && actionContext.parentActionEvent) { - actionContext = actionContext.parentActionEvent; - } - var actionFullPath = ""; - if (actionContext && actionContext.name != null) { - // try to use the context, and if it not available use the node one - var actionPath = (actionContext && actionContext.context && getPath(actionContext.context)) || - escapedPath; - actionFullPath = actionPath + "." + actionContext.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: '" + escapedPath + "', Subpath: '" + subpath + "', Action: '" + actionFullPath + "'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."; - } - }); - Object.defineProperty(ObjectNode.prototype, "getChildNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (subpath) { - this.assertAlive({ - subpath: subpath - }); - this._autoUnbox = false; - try { - return this._observableInstanceState === 2 /* CREATED */ - ? this.type.getChildNode(this, subpath) - : this._childNodes[subpath]; - } - finally { - this._autoUnbox = true; - } - } - }); - Object.defineProperty(ObjectNode.prototype, "getChildren", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.assertAlive(EMPTY_OBJECT); - this._autoUnbox = false; - try { - return this._observableInstanceState === 2 /* CREATED */ - ? this.type.getChildren(this) - : convertChildNodesToArray(this._childNodes); - } - finally { - this._autoUnbox = true; - } - } - }); - Object.defineProperty(ObjectNode.prototype, "getChildType", { - enumerable: false, - configurable: true, - writable: true, - value: function (propertyName) { - return this.type.getChildType(propertyName); - } - }); - Object.defineProperty(ObjectNode.prototype, "isProtected", { - get: function () { - return this.root.isProtectionEnabled; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectNode.prototype, "assertWritable", { - enumerable: false, - configurable: true, - writable: true, - value: function (context) { - this.assertAlive(context); - if (!this.isRunningAction() && this.isProtected) { - throw fail$1("Cannot modify '" + this + "', the object is protected and can only be modified by using an action."); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "removeChild", { - enumerable: false, - configurable: true, - writable: true, - value: function (subpath) { - this.type.removeChild(this, subpath); - } - }); - // bound on the constructor - Object.defineProperty(ObjectNode.prototype, "unbox", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNode) { - if (!childNode) - return childNode; - this.assertAlive({ - subpath: childNode.subpath || childNode.subpathUponDeath - }); - return this._autoUnbox ? childNode.value : childNode; - } - }); - Object.defineProperty(ObjectNode.prototype, "toString", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var path = (this.isAlive ? this.path : this.pathUponDeath) || ""; - var identifier = this.identifier ? "(id: " + this.identifier + ")" : ""; - return this.type.name + "@" + path + identifier + (this.isAlive ? "" : " [dead]"); - } - }); - Object.defineProperty(ObjectNode.prototype, "finalizeCreation", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var _this = this; - this.baseFinalizeCreation(function () { - var e_2, _a; - try { - for (var _b = __values(_this.getChildren()), _c = _b.next(); !_c.done; _c = _b.next()) { - var child = _c.value; - child.finalizeCreation(); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_2) throw e_2.error; } - } - _this.fireInternalHook(Hook.afterCreationFinalization); - }); - } - }); - Object.defineProperty(ObjectNode.prototype, "detach", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.isAlive) - throw fail$1("Error while detaching, node is not alive."); - this.clearParent(); - } - }); - Object.defineProperty(ObjectNode.prototype, "preboot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var self = this; - this._applyPatches = createActionInvoker(this.storedValue, "@APPLY_PATCHES", function (patches) { - patches.forEach(function (patch) { - if (!patch.path) { - self.type.applySnapshot(self, patch.value); - return; - } - var parts = splitJsonPath(patch.path); - var node = resolveNodeByPathParts(self, parts.slice(0, -1)); - node.applyPatchLocally(parts[parts.length - 1], patch); - }); - }); - this._applySnapshot = createActionInvoker(this.storedValue, "@APPLY_SNAPSHOT", function (snapshot) { - // if the snapshot is the same as the current one, avoid performing a reconcile - if (snapshot === self.snapshot) - return; - // else, apply it by calling the type logic - return self.type.applySnapshot(self, snapshot); - }); - addHiddenFinalProp(this.storedValue, "$treenode", this); - addHiddenFinalProp(this.storedValue, "toJSON", toJSON); - } - }); - Object.defineProperty(ObjectNode.prototype, "die", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) - return; - this.aboutToDie(); - this.finalizeDeath(); - } - }); - Object.defineProperty(ObjectNode.prototype, "aboutToDie", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._observableInstanceState === 0 /* UNINITIALIZED */) { - return; - } - this.getChildren().forEach(function (node) { - node.aboutToDie(); - }); - // beforeDestroy should run before the disposers since else we could end up in a situation where - // a disposer added with addDisposer at this stage (beforeDestroy) is actually never released - this.baseAboutToDie(); - this._internalEventsEmit("dispose" /* Dispose */); - this._internalEventsClear("dispose" /* Dispose */); - } - }); - Object.defineProperty(ObjectNode.prototype, "finalizeDeath", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - // invariant: not called directly but from "die" - this.getChildren().forEach(function (node) { - node.finalizeDeath(); - }); - this.root.identifierCache.notifyDied(this); - // "kill" the computed prop and just store the last snapshot - var snapshot = this.snapshot; - this._snapshotUponDeath = snapshot; - this._internalEventsClearAll(); - this.baseFinalizeDeath(); - } - }); - Object.defineProperty(ObjectNode.prototype, "onSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (onChange) { - this._addSnapshotReaction(); - return this._internalEventsRegister("snapshot" /* Snapshot */, onChange); - } - }); - Object.defineProperty(ObjectNode.prototype, "emitSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - this._internalEventsEmit("snapshot" /* Snapshot */, snapshot); - } - }); - Object.defineProperty(ObjectNode.prototype, "onPatch", { - enumerable: false, - configurable: true, - writable: true, - value: function (handler) { - return this._internalEventsRegister("patch" /* Patch */, handler); - } - }); - Object.defineProperty(ObjectNode.prototype, "emitPatch", { - enumerable: false, - configurable: true, - writable: true, - value: function (basePatch, source) { - if (this._internalEventsHasSubscribers("patch" /* Patch */)) { - var localizedPatch = extend({}, basePatch, { - path: source.path.substr(this.path.length) + "/" + basePatch.path // calculate the relative path of the patch - }); - var _a = __read(splitPatch(localizedPatch), 2), patch = _a[0], reversePatch = _a[1]; - this._internalEventsEmit("patch" /* Patch */, patch, reversePatch); - } - if (this.parent) - this.parent.emitPatch(basePatch, source); - } - }); - Object.defineProperty(ObjectNode.prototype, "hasDisposer", { - enumerable: false, - configurable: true, - writable: true, - value: function (disposer) { - return this._internalEventsHas("dispose" /* Dispose */, disposer); - } - }); - Object.defineProperty(ObjectNode.prototype, "addDisposer", { - enumerable: false, - configurable: true, - writable: true, - value: function (disposer) { - if (!this.hasDisposer(disposer)) { - this._internalEventsRegister("dispose" /* Dispose */, disposer, true); - return; - } - throw fail$1("cannot add a disposer when it is already registered for execution"); - } - }); - Object.defineProperty(ObjectNode.prototype, "removeDisposer", { - enumerable: false, - configurable: true, - writable: true, - value: function (disposer) { - if (!this._internalEventsHas("dispose" /* Dispose */, disposer)) { - throw fail$1("cannot remove a disposer which was never registered for execution"); - } - this._internalEventsUnregister("dispose" /* Dispose */, disposer); - } - }); - Object.defineProperty(ObjectNode.prototype, "removeMiddleware", { - enumerable: false, - configurable: true, - writable: true, - value: function (middleware) { - if (this.middlewares) { - var index = this.middlewares.indexOf(middleware); - if (index >= 0) { - this.middlewares.splice(index, 1); - } - } - } - }); - Object.defineProperty(ObjectNode.prototype, "addMiddleWare", { - enumerable: false, - configurable: true, - writable: true, - value: function (handler, includeHooks) { - var _this = this; - if (includeHooks === void 0) { includeHooks = true; } - var middleware = { handler: handler, includeHooks: includeHooks }; - if (!this.middlewares) - this.middlewares = [middleware]; - else - this.middlewares.push(middleware); - return function () { - _this.removeMiddleware(middleware); - }; - } - }); - Object.defineProperty(ObjectNode.prototype, "applyPatchLocally", { - enumerable: false, - configurable: true, - writable: true, - value: function (subpath, patch) { - this.assertWritable({ - subpath: subpath - }); - this.createObservableInstanceIfNeeded(); - this.type.applyPatchLocally(this, subpath, patch); - } - }); - Object.defineProperty(ObjectNode.prototype, "_addSnapshotReaction", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var _this = this; - if (!this._hasSnapshotReaction) { - var snapshotDisposer = reaction(function () { return _this.snapshot; }, function (snapshot) { return _this.emitSnapshot(snapshot); }, snapshotReactionOptions); - this.addDisposer(snapshotDisposer); - this._hasSnapshotReaction = true; - } - } - }); - // we proxy the methods to avoid creating an EventHandlers instance when it is not needed - Object.defineProperty(ObjectNode.prototype, "_internalEventsHasSubscribers", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - return !!this._internalEvents && this._internalEvents.hasSubscribers(event); - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsRegister", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, eventHandler, atTheBeginning) { - if (atTheBeginning === void 0) { atTheBeginning = false; } - if (!this._internalEvents) { - this._internalEvents = new EventHandlers(); - } - return this._internalEvents.register(event, eventHandler, atTheBeginning); - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsHas", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, eventHandler) { - return !!this._internalEvents && this._internalEvents.has(event, eventHandler); - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsUnregister", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, eventHandler) { - if (this._internalEvents) { - this._internalEvents.unregister(event, eventHandler); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsEmit", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - if (this._internalEvents) { - (_a = this._internalEvents).emit.apply(_a, __spread([event], args)); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsClear", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - if (this._internalEvents) { - this._internalEvents.clear(event); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsClearAll", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._internalEvents) { - this._internalEvents.clearAll(); - } - } - }); - return ObjectNode; -}(BaseNode)); -ObjectNode.prototype.createObservableInstance = action(ObjectNode.prototype.createObservableInstance); -ObjectNode.prototype.detach = action(ObjectNode.prototype.detach); -ObjectNode.prototype.die = action(ObjectNode.prototype.die); - -var _a; -/** - * @internal - * @hidden - */ -var TypeFlags; -(function (TypeFlags) { - TypeFlags[TypeFlags["String"] = 1] = "String"; - TypeFlags[TypeFlags["Number"] = 2] = "Number"; - TypeFlags[TypeFlags["Boolean"] = 4] = "Boolean"; - TypeFlags[TypeFlags["Date"] = 8] = "Date"; - TypeFlags[TypeFlags["Literal"] = 16] = "Literal"; - TypeFlags[TypeFlags["Array"] = 32] = "Array"; - TypeFlags[TypeFlags["Map"] = 64] = "Map"; - TypeFlags[TypeFlags["Object"] = 128] = "Object"; - TypeFlags[TypeFlags["Frozen"] = 256] = "Frozen"; - TypeFlags[TypeFlags["Optional"] = 512] = "Optional"; - TypeFlags[TypeFlags["Reference"] = 1024] = "Reference"; - TypeFlags[TypeFlags["Identifier"] = 2048] = "Identifier"; - TypeFlags[TypeFlags["Late"] = 4096] = "Late"; - TypeFlags[TypeFlags["Refinement"] = 8192] = "Refinement"; - TypeFlags[TypeFlags["Union"] = 16384] = "Union"; - TypeFlags[TypeFlags["Null"] = 32768] = "Null"; - TypeFlags[TypeFlags["Undefined"] = 65536] = "Undefined"; - TypeFlags[TypeFlags["Integer"] = 131072] = "Integer"; - TypeFlags[TypeFlags["Custom"] = 262144] = "Custom"; - TypeFlags[TypeFlags["SnapshotProcessor"] = 524288] = "SnapshotProcessor"; -})(TypeFlags || (TypeFlags = {})); -/** - * @internal - * @hidden - */ -var cannotDetermineSubtype = "cannotDetermine"; -/** @hidden */ -var $type = Symbol("$type"); -/** - * A base type produces a MST node (Node in the state tree) - * - * @internal - * @hidden - */ -var BaseType = /** @class */ (function () { - function BaseType(name) { - Object.defineProperty(this, _a, { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // these are just to make inner types avaialable to inherited classes - Object.defineProperty(this, "C", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "S", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "T", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "N", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "isType", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = name; - } - Object.defineProperty(BaseType.prototype, "create", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot, environment) { - typecheckInternal(this, snapshot); - return this.instantiate(null, "", environment, snapshot).value; - } - }); - Object.defineProperty(BaseType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, applyPostProcess) { - // istanbul ignore next - throw fail$1("unimplemented method"); - } - }); - Object.defineProperty(BaseType.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return type === this; - } - }); - Object.defineProperty(BaseType.prototype, "validate", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var node = getStateTreeNodeSafe(value); - if (node) { - var valueType = getType(value); - return this.isAssignableFrom(valueType) - ? typeCheckSuccess() - : typeCheckFailure(context, value); - // it is tempting to compare snapshots, but in that case we should always clone on assignments... - } - return this.isValidSnapshot(value, context); - } - }); - Object.defineProperty(BaseType.prototype, "is", { - enumerable: false, - configurable: true, - writable: true, - value: function (thing) { - return this.validate(thing, [{ path: "", type: this }]).length === 0; - } - }); - Object.defineProperty(BaseType.prototype, "Type", { - get: function () { - // istanbul ignore next - throw fail$1("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: false, - configurable: true - }); - Object.defineProperty(BaseType.prototype, "TypeWithoutSTN", { - get: function () { - // istanbul ignore next - throw fail$1("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: false, - configurable: true - }); - Object.defineProperty(BaseType.prototype, "SnapshotType", { - get: function () { - // istanbul ignore next - throw fail$1("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: false, - configurable: true - }); - Object.defineProperty(BaseType.prototype, "CreationType", { - get: function () { - // istanbul ignore next - throw fail$1("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: false, - configurable: true - }); - return BaseType; -}()); -_a = $type; -BaseType.prototype.create = action(BaseType.prototype.create); -/** - * A complex type produces a MST node (Node in the state tree) - * - * @internal - * @hidden - */ -var ComplexType = /** @class */ (function (_super) { - __extends$1(ComplexType, _super); - function ComplexType(name) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "identifierAttribute", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - return _this; - } - Object.defineProperty(ComplexType.prototype, "create", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot, environment) { - if (snapshot === void 0) { snapshot = this.getDefaultSnapshot(); } - return _super.prototype.create.call(this, snapshot, environment); - } - }); - Object.defineProperty(ComplexType.prototype, "getValue", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - node.createObservableInstanceIfNeeded(); - return node.storedValue; - } - }); - Object.defineProperty(ComplexType.prototype, "tryToReconcileNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue) { - if (current.isDetaching) - return false; - if (current.snapshot === newValue) { - // newValue is the current snapshot of the node, noop - return true; - } - if (isStateTreeNode(newValue) && getStateTreeNode(newValue) === current) { - // the current node is the same as the new one - return true; - } - if (current.type === this && - isMutable(newValue) && - !isStateTreeNode(newValue) && - (!current.identifierAttribute || - current.identifier === - normalizeIdentifier(newValue[current.identifierAttribute]))) { - // the newValue has no node, so can be treated like a snapshot - // we can reconcile - current.applySnapshot(newValue); - return true; - } - return false; - } - }); - Object.defineProperty(ComplexType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - var nodeReconciled = this.tryToReconcileNode(current, newValue); - if (nodeReconciled) { - current.setParent(parent, subpath); - return current; - } - // current node cannot be recycled in any way - current.die(); // noop if detaching - // attempt to reuse the new one - if (isStateTreeNode(newValue) && this.isAssignableFrom(getType(newValue))) { - // newValue is a Node as well, move it here.. - var newNode = getStateTreeNode(newValue); - newNode.setParent(parent, subpath); - return newNode; - } - // nothing to do, we have to create a new node - return this.instantiate(parent, subpath, undefined, newValue); - } - }); - Object.defineProperty(ComplexType.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return null; - } - }); - return ComplexType; -}(BaseType)); -ComplexType.prototype.create = action(ComplexType.prototype.create); -/** - * @internal - * @hidden - */ -var SimpleType = /** @class */ (function (_super) { - __extends$1(SimpleType, _super); - function SimpleType() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(SimpleType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - return snapshot; - } - }); - Object.defineProperty(SimpleType.prototype, "getValue", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - // if we ever find a case where scalar nodes can be accessed without iterating through its parent - // uncomment this to make sure the parent chain is created when this is accessed - // if (node.parent) { - // node.parent.createObservableInstanceIfNeeded() - // } - return node.storedValue; - } - }); - Object.defineProperty(SimpleType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return node.storedValue; - } - }); - Object.defineProperty(SimpleType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - // reconcile only if type and value are still the same, and only if the node is not detaching - if (!current.isDetaching && current.type === this && current.storedValue === newValue) { - return current; - } - var res = this.instantiate(parent, subpath, undefined, newValue); - current.die(); // noop if detaching - return res; - } - }); - Object.defineProperty(SimpleType.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return null; - } - }); - return SimpleType; -}(BaseType)); -/** - * Returns if a given value represents a type. - * - * @param value Value to check. - * @returns `true` if the value is a type. - */ -function isType(value) { - return typeof value === "object" && value && value.isType === true; -} - -/** @class */ ((function () { - function RunningAction(hooks, call) { - Object.defineProperty(this, "hooks", { - enumerable: true, - configurable: true, - writable: true, - value: hooks - }); - Object.defineProperty(this, "call", { - enumerable: true, - configurable: true, - writable: true, - value: call - }); - Object.defineProperty(this, "flowsPending", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "running", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - if (hooks) { - hooks.onStart(call); - } - } - Object.defineProperty(RunningAction.prototype, "finish", { - enumerable: false, - configurable: true, - writable: true, - value: function (error) { - if (this.running) { - this.running = false; - if (this.hooks) { - this.hooks.onFinish(this.call, error); - } - } - } - }); - Object.defineProperty(RunningAction.prototype, "incFlowsPending", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.flowsPending++; - } - }); - Object.defineProperty(RunningAction.prototype, "decFlowsPending", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.flowsPending--; - } - }); - Object.defineProperty(RunningAction.prototype, "hasFlowsPending", { - get: function () { - return this.flowsPending > 0; - }, - enumerable: false, - configurable: true - }); - return RunningAction; -})()); - -var nextActionId = 1; -var currentActionContext; -/** - * @internal - * @hidden - */ -function getCurrentActionContext() { - return currentActionContext; -} -/** - * @internal - * @hidden - */ -function getNextActionId() { - return nextActionId++; -} -// TODO: optimize away entire action context if there is no middleware in tree? -/** - * @internal - * @hidden - */ -function runWithActionContext(context, fn) { - var node = getStateTreeNode(context.context); - if (context.type === "action") { - node.assertAlive({ - actionContext: context - }); - } - var baseIsRunningAction = node._isRunningAction; - node._isRunningAction = true; - var previousContext = currentActionContext; - currentActionContext = context; - try { - return runMiddleWares(node, context, fn); - } - finally { - currentActionContext = previousContext; - node._isRunningAction = baseIsRunningAction; - } -} -/** - * @internal - * @hidden - */ -function getParentActionContext(parentContext) { - if (!parentContext) - return undefined; - if (parentContext.type === "action") - return parentContext; - return parentContext.parentActionEvent; -} -/** - * @internal - * @hidden - */ -function createActionInvoker(target, name, fn) { - var res = function () { - var id = getNextActionId(); - var parentContext = currentActionContext; - var parentActionContext = getParentActionContext(parentContext); - return runWithActionContext({ - type: "action", - name: name, - id: id, - args: argsToArray(arguments), - context: target, - tree: getRoot(target), - rootId: parentContext ? parentContext.rootId : id, - parentId: parentContext ? parentContext.id : 0, - allParentIds: parentContext - ? __spread(parentContext.allParentIds, [parentContext.id]) : [], - parentEvent: parentContext, - parentActionEvent: parentActionContext - }, fn); - }; - res._isMSTAction = true; - return res; -} -var CollectedMiddlewares = /** @class */ (function () { - function CollectedMiddlewares(node, fn) { - Object.defineProperty(this, "arrayIndex", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "inArrayIndex", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "middlewares", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - // we just push middleware arrays into an array of arrays to avoid making copies - if (fn.$mst_middleware) { - this.middlewares.push(fn.$mst_middleware); - } - var n = node; - // Find all middlewares. Optimization: cache this? - while (n) { - if (n.middlewares) - this.middlewares.push(n.middlewares); - n = n.parent; - } - } - Object.defineProperty(CollectedMiddlewares.prototype, "isEmpty", { - get: function () { - return this.middlewares.length <= 0; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CollectedMiddlewares.prototype, "getNextMiddleware", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var array = this.middlewares[this.arrayIndex]; - if (!array) - return undefined; - var item = array[this.inArrayIndex++]; - if (!item) { - this.arrayIndex++; - this.inArrayIndex = 0; - return this.getNextMiddleware(); - } - return item; - } - }); - return CollectedMiddlewares; -}()); -function runMiddleWares(node, baseCall, originalFn) { - var middlewares = new CollectedMiddlewares(node, originalFn); - // Short circuit - if (middlewares.isEmpty) - return action(originalFn).apply(null, baseCall.args); - var result = null; - function runNextMiddleware(call) { - var middleware = middlewares.getNextMiddleware(); - var handler = middleware && middleware.handler; - if (!handler) { - return action(originalFn).apply(null, call.args); - } - // skip hooks if asked to - if (!middleware.includeHooks && Hook[call.name]) { - return runNextMiddleware(call); - } - function next(call2, callback) { - // the result can contain - // - the non manipulated return value from an action - // - the non manipulated abort value - // - one of the above but manipulated through the callback function - result = runNextMiddleware(call2); - if (callback) { - result = callback(result); - } - } - function abort(value) { - // overwrite the result - // can be manipulated through middlewares earlier in the queue using the callback fn - result = value; - } - handler(call, next, abort); - return result; - } - return runNextMiddleware(baseCall); -} - -function safeStringify(value) { - try { - return JSON.stringify(value); - } - catch (e) { - // istanbul ignore next - return ""; - } -} -/** - * @internal - * @hidden - */ -function prettyPrintValue(value) { - return typeof value === "function" - ? "" - : isStateTreeNode(value) - ? "<" + value + ">" - : "`" + safeStringify(value) + "`"; -} -function shortenPrintValue(valueInString) { - return valueInString.length < 280 - ? valueInString - : valueInString.substring(0, 272) + "......" + valueInString.substring(valueInString.length - 8); -} -function toErrorString(error) { - var value = error.value; - var type = error.context[error.context.length - 1].type; - var fullPath = error.context - .map(function (_a) { - var path = _a.path; - return path; - }) - .filter(function (path) { return path.length > 0; }) - .join("/"); - var pathPrefix = fullPath.length > 0 ? "at path \"/" + fullPath + "\" " : ""; - var currentTypename = isStateTreeNode(value) - ? "value of type " + getStateTreeNode(value).type.name + ":" - : isPrimitive(value) - ? "value" - : "snapshot"; - var isSnapshotCompatible = type && isStateTreeNode(value) && type.is(getStateTreeNode(value).snapshot); - return ("" + pathPrefix + currentTypename + " " + prettyPrintValue(value) + " is not assignable " + (type ? "to type: `" + type.name + "`" : "") + - (error.message ? " (" + error.message + ")" : "") + - (type - ? isPrimitiveType(type) || isPrimitive(value) - ? "." - : ", expected an instance of `" + type.name + "` or a snapshot like `" + type.describe() + "` instead." + - (isSnapshotCompatible - ? " (Note that a snapshot of the provided value is compatible with the targeted type)" - : "") - : ".")); -} -/** - * @internal - * @hidden - */ -function getContextForPath(context, path, type) { - return context.concat([{ path: path, type: type }]); -} -/** - * @internal - * @hidden - */ -function typeCheckSuccess() { - return EMPTY_ARRAY; -} -/** - * @internal - * @hidden - */ -function typeCheckFailure(context, value, message) { - return [{ context: context, value: value, message: message }]; -} -/** - * @internal - * @hidden - */ -function flattenTypeErrors(errors) { - return errors.reduce(function (a, i) { return a.concat(i); }, []); -} -// TODO; doublecheck: typecheck should only needed to be invoked from: type.create and array / map / value.property will change -/** - * @internal - * @hidden - */ -function typecheckInternal(type, value) { - // runs typeChecking if it is in dev-mode or through a process.env.ENABLE_TYPE_CHECK flag - if (isTypeCheckingEnabled()) { - typecheck(type, value); - } -} -/** - * Run's the typechecker for the given type on the given value, which can be a snapshot or an instance. - * Throws if the given value is not according the provided type specification. - * Use this if you need typechecks even in a production build (by default all automatic runtime type checks will be skipped in production builds) - * - * @param type Type to check against. - * @param value Value to be checked, either a snapshot or an instance. - */ -function typecheck(type, value) { - var errors = type.validate(value, [{ path: "", type: type }]); - if (errors.length > 0) { - throw fail$1(validationErrorsToString(type, value, errors)); - } -} -function validationErrorsToString(type, value, errors) { - if (errors.length === 0) { - return undefined; - } - return ("Error while converting " + shortenPrintValue(prettyPrintValue(value)) + " to `" + type.name + "`:\n\n " + errors.map(toErrorString).join("\n ")); -} - -var identifierCacheId = 0; -/** - * @internal - * @hidden - */ -var IdentifierCache = /** @class */ (function () { - function IdentifierCache() { - Object.defineProperty(this, "cacheId", { - enumerable: true, - configurable: true, - writable: true, - value: identifierCacheId++ - }); - // n.b. in cache all identifiers are normalized to strings - Object.defineProperty(this, "cache", { - enumerable: true, - configurable: true, - writable: true, - value: observable$1.map() - }); - // last time the cache (array) for a given time changed - // n.b. it is not really the time, but just an integer that gets increased after each modification to the array - Object.defineProperty(this, "lastCacheModificationPerId", { - enumerable: true, - configurable: true, - writable: true, - value: observable$1.map() - }); - } - Object.defineProperty(IdentifierCache.prototype, "updateLastCacheModificationPerId", { - enumerable: false, - configurable: true, - writable: true, - value: function (identifier) { - var lcm = this.lastCacheModificationPerId.get(identifier); - // we start at 1 since 0 means no update since cache creation - this.lastCacheModificationPerId.set(identifier, lcm === undefined ? 1 : lcm + 1); - } - }); - Object.defineProperty(IdentifierCache.prototype, "getLastCacheModificationPerId", { - enumerable: false, - configurable: true, - writable: true, - value: function (identifier) { - var modificationId = this.lastCacheModificationPerId.get(identifier) || 0; - return this.cacheId + "-" + modificationId; - } - }); - Object.defineProperty(IdentifierCache.prototype, "addNodeToCache", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, lastCacheUpdate) { - if (lastCacheUpdate === void 0) { lastCacheUpdate = true; } - if (node.identifierAttribute) { - var identifier = node.identifier; - if (!this.cache.has(identifier)) { - this.cache.set(identifier, observable$1.array([], mobxShallow)); - } - var set = this.cache.get(identifier); - if (set.indexOf(node) !== -1) - throw fail$1("Already registered"); - set.push(node); - if (lastCacheUpdate) { - this.updateLastCacheModificationPerId(identifier); - } - } - } - }); - Object.defineProperty(IdentifierCache.prototype, "mergeCache", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var _this = this; - values(node.identifierCache.cache).forEach(function (nodes) { - return nodes.forEach(function (child) { - _this.addNodeToCache(child); - }); - }); - } - }); - Object.defineProperty(IdentifierCache.prototype, "notifyDied", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - if (node.identifierAttribute) { - var id = node.identifier; - var set = this.cache.get(id); - if (set) { - set.remove(node); - // remove empty sets from cache - if (!set.length) { - this.cache.delete(id); - } - this.updateLastCacheModificationPerId(node.identifier); - } - } - } - }); - Object.defineProperty(IdentifierCache.prototype, "splitCache", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var _this = this; - var res = new IdentifierCache(); - var basePath = node.path; - entries(this.cache).forEach(function (_a) { - var _b = __read(_a, 2), id = _b[0], nodes = _b[1]; - var modified = false; - for (var i = nodes.length - 1; i >= 0; i--) { - if (nodes[i].path.indexOf(basePath) === 0) { - res.addNodeToCache(nodes[i], false); // no need to update lastUpdated since it is a whole new cache - nodes.splice(i, 1); - modified = true; - } - } - if (modified) { - _this.updateLastCacheModificationPerId(id); - } - }); - return res; - } - }); - Object.defineProperty(IdentifierCache.prototype, "has", { - enumerable: false, - configurable: true, - writable: true, - value: function (type, identifier) { - var set = this.cache.get(identifier); - if (!set) - return false; - return set.some(function (candidate) { return type.isAssignableFrom(candidate.type); }); - } - }); - Object.defineProperty(IdentifierCache.prototype, "resolve", { - enumerable: false, - configurable: true, - writable: true, - value: function (type, identifier) { - var set = this.cache.get(identifier); - if (!set) - return null; - var matches = set.filter(function (candidate) { return type.isAssignableFrom(candidate.type); }); - switch (matches.length) { - case 0: - return null; - case 1: - return matches[0]; - default: - throw fail$1("Cannot resolve a reference to type '" + type.name + "' with id: '" + identifier + "' unambigously, there are multiple candidates: " + matches - .map(function (n) { return n.path; }) - .join(", ")); - } - } - }); - return IdentifierCache; -}()); - -/** - * @internal - * @hidden - */ -function createObjectNode(type, parent, subpath, environment, initialValue) { - var existingNode = getStateTreeNodeSafe(initialValue); - if (existingNode) { - if (existingNode.parent) { - // istanbul ignore next - throw fail$1("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 '" + (parent ? parent.path : "") + "/" + subpath + "', but it lives already at '" + existingNode.path + "'"); - } - if (parent) { - existingNode.setParent(parent, subpath); - } - // else it already has no parent since it is a pre-requisite - return existingNode; - } - // not a node, a snapshot - return new ObjectNode(type, parent, subpath, environment, initialValue); -} -/** - * @internal - * @hidden - */ -function createScalarNode(type, parent, subpath, environment, initialValue) { - return new ScalarNode(type, parent, subpath, environment, initialValue); -} -/** - * @internal - * @hidden - */ -function isNode(value) { - return value instanceof ScalarNode || value instanceof ObjectNode; -} - -/** - * @internal - * @hidden - */ -var NodeLifeCycle; -(function (NodeLifeCycle) { - NodeLifeCycle[NodeLifeCycle["INITIALIZING"] = 0] = "INITIALIZING"; - NodeLifeCycle[NodeLifeCycle["CREATED"] = 1] = "CREATED"; - NodeLifeCycle[NodeLifeCycle["FINALIZED"] = 2] = "FINALIZED"; - NodeLifeCycle[NodeLifeCycle["DETACHING"] = 3] = "DETACHING"; - NodeLifeCycle[NodeLifeCycle["DEAD"] = 4] = "DEAD"; // no coming back from this one -})(NodeLifeCycle || (NodeLifeCycle = {})); -/** - * Returns true if the given value is a node in a state tree. - * More precisely, that is, if the value is an instance of a - * `types.model`, `types.array` or `types.map`. - * - * @param value - * @returns true if the value is a state tree node. - */ -function isStateTreeNode(value) { - return !!(value && value.$treenode); -} -/** - * @internal - * @hidden - */ -function getStateTreeNode(value) { - if (!isStateTreeNode(value)) { - // istanbul ignore next - throw fail$1("Value " + value + " is no MST Node"); - } - return value.$treenode; -} -/** - * @internal - * @hidden - */ -function getStateTreeNodeSafe(value) { - return (value && value.$treenode) || null; -} -/** - * @internal - * @hidden - */ -function toJSON() { - return getStateTreeNode(this).snapshot; -} -/** - * @internal - * @hidden - */ -function resolveNodeByPathParts(base, pathParts, failIfResolveFails) { - if (failIfResolveFails === void 0) { failIfResolveFails = true; } - var current = base; - for (var i = 0; i < pathParts.length; i++) { - var part = pathParts[i]; - if (part === "..") { - current = current.parent; - if (current) - continue; // not everything has a parent - } - else if (part === ".") { - continue; - } - else if (current) { - if (current instanceof ScalarNode) { - // check if the value of a scalar resolves to a state tree node (e.g. references) - // then we can continue resolving... - try { - var value = current.value; - if (isStateTreeNode(value)) { - current = getStateTreeNode(value); - // fall through - } - } - catch (e) { - if (!failIfResolveFails) { - return undefined; - } - throw e; - } - } - if (current instanceof ObjectNode) { - var subType = current.getChildType(part); - if (subType) { - current = current.getChildNode(part); - if (current) - continue; - } - } - } - if (failIfResolveFails) - throw fail$1("Could not resolve '" + part + "' in path '" + (joinJsonPath(pathParts.slice(0, i)) || "/") + "' while resolving '" + joinJsonPath(pathParts) + "'"); - else - return undefined; - } - return current; -} -/** - * @internal - * @hidden - */ -function convertChildNodesToArray(childNodes) { - if (!childNodes) - return EMPTY_ARRAY; - var keys = Object.keys(childNodes); - if (!keys.length) - return EMPTY_ARRAY; - var result = new Array(keys.length); - keys.forEach(function (key, index) { - result[index] = childNodes[key]; - }); - return result; -} - -var plainObjectString = Object.toString(); -/** - * @internal - * @hidden - */ -var EMPTY_ARRAY = Object.freeze([]); -/** - * @internal - * @hidden - */ -var EMPTY_OBJECT = Object.freeze({}); -/** - * @internal - * @hidden - */ -var mobxShallow = getGlobalState().useProxies - ? { deep: false } - : { deep: false, proxy: false }; -Object.freeze(mobxShallow); -/** - * @internal - * @hidden - */ -function fail$1(message) { - if (message === void 0) { message = "Illegal state"; } - return new Error("[mobx-state-tree] " + message); -} -/** - * @internal - * @hidden - */ -function identity$2(_) { - return _; -} -/** - * pollyfill (for IE) suggested in MDN: - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger - * @internal - * @hidden - */ -var isInteger = Number.isInteger || - function (value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; - }; -/** - * @internal - * @hidden - */ -function isArray$2(val) { - return Array.isArray(val) || isObservableArray(val); -} -/** - * @internal - * @hidden - */ -function asArray(val) { - if (!val) - return EMPTY_ARRAY; - if (isArray$2(val)) - return val; - return [val]; -} -/** - * @internal - * @hidden - */ -function extend(a) { - var b = []; - for (var _i = 1; _i < arguments.length; _i++) { - b[_i - 1] = arguments[_i]; - } - for (var i = 0; i < b.length; i++) { - var current = b[i]; - for (var key in current) - a[key] = current[key]; - } - return a; -} -/** - * @internal - * @hidden - */ -function isPlainObject(value) { - var _a; - if (value === null || typeof value !== "object") - return false; - var proto = Object.getPrototypeOf(value); - if (proto == null) - return true; - return ((_a = proto.constructor) === null || _a === void 0 ? void 0 : _a.toString()) === plainObjectString; -} -/** - * @internal - * @hidden - */ -function isMutable(value) { - return (value !== null && - typeof value === "object" && - !(value instanceof Date) && - !(value instanceof RegExp)); -} -/** - * @internal - * @hidden - */ -function isPrimitive(value, includeDate) { - if (includeDate === void 0) { includeDate = true; } - if (value === null || value === undefined) - return true; - if (typeof value === "string" || - typeof value === "number" || - typeof value === "boolean" || - (includeDate && value instanceof Date)) - return true; - return false; -} -/** - * @internal - * @hidden - * Freeze a value and return it (if not in production) - */ -function freeze(value) { - return value; -} -/** - * @internal - * @hidden - * Recursively freeze a value (if not in production) - */ -function deepFreeze(value) { - return value; -} -/** - * @internal - * @hidden - */ -function isSerializable(value) { - return typeof value !== "function"; -} -/** - * @internal - * @hidden - */ -function defineProperty$1(object, key, descriptor) { - isObservableObject(object) - ? apiDefineProperty(object, key, descriptor) - : Object.defineProperty(object, key, descriptor); -} -/** - * @internal - * @hidden - */ -function addHiddenFinalProp(object, propName, value) { - defineProperty$1(object, propName, { - enumerable: false, - writable: false, - configurable: true, - value: value - }); -} -/** - * @internal - * @hidden - */ -var EventHandler = /** @class */ (function () { - function EventHandler() { - Object.defineProperty(this, "handlers", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - } - Object.defineProperty(EventHandler.prototype, "hasSubscribers", { - get: function () { - return this.handlers.length > 0; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(EventHandler.prototype, "register", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn, atTheBeginning) { - var _this = this; - if (atTheBeginning === void 0) { atTheBeginning = false; } - if (atTheBeginning) { - this.handlers.unshift(fn); - } - else { - this.handlers.push(fn); - } - return function () { - _this.unregister(fn); - }; - } - }); - Object.defineProperty(EventHandler.prototype, "has", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - return this.handlers.indexOf(fn) >= 0; - } - }); - Object.defineProperty(EventHandler.prototype, "unregister", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var index = this.handlers.indexOf(fn); - if (index >= 0) { - this.handlers.splice(index, 1); - } - } - }); - Object.defineProperty(EventHandler.prototype, "clear", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.handlers.length = 0; - } - }); - Object.defineProperty(EventHandler.prototype, "emit", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // make a copy just in case it changes - var handlers = this.handlers.slice(); - handlers.forEach(function (f) { return f.apply(void 0, __spread(args)); }); - } - }); - return EventHandler; -}()); -/** - * @internal - * @hidden - */ -var EventHandlers = /** @class */ (function () { - function EventHandlers() { - Object.defineProperty(this, "eventHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - } - Object.defineProperty(EventHandlers.prototype, "hasSubscribers", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - var handler = this.eventHandlers && this.eventHandlers[event]; - return !!handler && handler.hasSubscribers; - } - }); - Object.defineProperty(EventHandlers.prototype, "register", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, fn, atTheBeginning) { - if (atTheBeginning === void 0) { atTheBeginning = false; } - if (!this.eventHandlers) { - this.eventHandlers = {}; - } - var handler = this.eventHandlers[event]; - if (!handler) { - handler = this.eventHandlers[event] = new EventHandler(); - } - return handler.register(fn, atTheBeginning); - } - }); - Object.defineProperty(EventHandlers.prototype, "has", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, fn) { - var handler = this.eventHandlers && this.eventHandlers[event]; - return !!handler && handler.has(fn); - } - }); - Object.defineProperty(EventHandlers.prototype, "unregister", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, fn) { - var handler = this.eventHandlers && this.eventHandlers[event]; - if (handler) { - handler.unregister(fn); - } - } - }); - Object.defineProperty(EventHandlers.prototype, "clear", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - if (this.eventHandlers) { - delete this.eventHandlers[event]; - } - } - }); - Object.defineProperty(EventHandlers.prototype, "clearAll", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.eventHandlers = undefined; - } - }); - Object.defineProperty(EventHandlers.prototype, "emit", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var handler = this.eventHandlers && this.eventHandlers[event]; - if (handler) { - (_a = handler).emit.apply(_a, __spread(args)); - } - } - }); - return EventHandlers; -}()); -/** - * @internal - * @hidden - */ -function argsToArray(args) { - var res = new Array(args.length); - for (var i = 0; i < args.length; i++) - res[i] = args[i]; - return res; -} -/** - * @internal - * @hidden - */ -function stringStartsWith(str, beginning) { - return str.indexOf(beginning) === 0; -} -/** - * @internal - * @hidden - */ -function warnError(msg) { - console.warn(new Error("[mobx-state-tree] " + msg)); -} -/** - * @internal - * @hidden - */ -function isTypeCheckingEnabled() { - return ((typeof process !== "undefined" && process.env && process.env.ENABLE_TYPE_CHECK === "true")); -} - -/** - * @internal - * @hidden - */ -function splitPatch(patch) { - if (!("oldValue" in patch)) - throw fail$1("Patches without `oldValue` field cannot be inversed"); - return [stripPatch(patch), invertPatch(patch)]; -} -/** - * @internal - * @hidden - */ -function stripPatch(patch) { - // strips `oldvalue` information from the patch, so that it becomes a patch conform the json-patch spec - // this removes the ability to undo the patch - switch (patch.op) { - case "add": - return { op: "add", path: patch.path, value: patch.value }; - case "remove": - return { op: "remove", path: patch.path }; - case "replace": - return { op: "replace", path: patch.path, value: patch.value }; - } -} -function invertPatch(patch) { - switch (patch.op) { - case "add": - return { - op: "remove", - path: patch.path - }; - case "remove": - return { - op: "add", - path: patch.path, - value: patch.oldValue - }; - case "replace": - return { - op: "replace", - path: patch.path, - value: patch.oldValue - }; - } -} -/** - * Simple simple check to check it is a number. - */ -function isNumber(x) { - return typeof x === "number"; -} -/** - * Escape slashes and backslashes. - * - * http://tools.ietf.org/html/rfc6901 - */ -function escapeJsonPath(path) { - if (isNumber(path) === true) { - return "" + path; - } - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) - return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} -/** - * Unescape slashes and backslashes. - */ -function unescapeJsonPath(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -/** - * Generates a json-path compliant json path from path parts. - * - * @param path - * @returns - */ -function joinJsonPath(path) { - // `/` refers to property with an empty name, while `` refers to root itself! - if (path.length === 0) - return ""; - var getPathStr = function (p) { return p.map(escapeJsonPath).join("/"); }; - if (path[0] === "." || path[0] === "..") { - // relative - return getPathStr(path); - } - else { - // absolute - return "/" + getPathStr(path); - } -} -/** - * Splits and decodes a json path into several parts. - * - * @param path - * @returns - */ -function splitJsonPath(path) { - // `/` refers to property with an empty name, while `` refers to root itself! - var parts = path.split("/").map(unescapeJsonPath); - var valid = path === "" || - path === "." || - path === ".." || - stringStartsWith(path, "/") || - stringStartsWith(path, "./") || - stringStartsWith(path, "../"); - if (!valid) { - throw fail$1("a json path must be either rooted, empty or relative, but got '" + path + "'"); - } - // '/a/b/c' -> ["a", "b", "c"] - // '../../b/c' -> ["..", "..", "b", "c"] - // '' -> [] - // '/' -> [''] - // './a' -> [".", "a"] - // /./a' -> [".", "a"] equivalent to './a' - if (parts[0] === "") { - parts.shift(); - } - return parts; -} - -var SnapshotProcessor = /** @class */ (function (_super) { - __extends$1(SnapshotProcessor, _super); - function SnapshotProcessor(_subtype, _processors, name) { - var _this = _super.call(this, name || _subtype.name) || this; - Object.defineProperty(_this, "_subtype", { - enumerable: true, - configurable: true, - writable: true, - value: _subtype - }); - Object.defineProperty(_this, "_processors", { - enumerable: true, - configurable: true, - writable: true, - value: _processors - }); - return _this; - } - Object.defineProperty(SnapshotProcessor.prototype, "flags", { - get: function () { - return this._subtype.flags | TypeFlags.SnapshotProcessor; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SnapshotProcessor.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "snapshotProcessor(" + this._subtype.describe() + ")"; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "preProcessSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (sn) { - if (this._processors.preProcessor) { - return this._processors.preProcessor.call(null, sn); - } - return sn; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "postProcessSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (sn) { - if (this._processors.postProcessor) { - return this._processors.postProcessor.call(null, sn); - } - return sn; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "_fixNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var _this = this; - // the node has to use these methods rather than the original type ones - proxyNodeTypeMethods(node.type, this, "create"); - var oldGetSnapshot = node.getSnapshot; - node.getSnapshot = function () { - return _this.postProcessSnapshot(oldGetSnapshot.call(node)); - }; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var processedInitialValue = isStateTreeNode(initialValue) - ? initialValue - : this.preProcessSnapshot(initialValue); - var node = this._subtype.instantiate(parent, subpath, environment, processedInitialValue); - this._fixNode(node); - return node; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - var node = this._subtype.reconcile(current, isStateTreeNode(newValue) ? newValue : this.preProcessSnapshot(newValue), parent, subpath); - if (node !== current) { - this._fixNode(node); - } - return node; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, applyPostProcess) { - if (applyPostProcess === void 0) { applyPostProcess = true; } - var sn = this._subtype.getSnapshot(node); - return applyPostProcess ? this.postProcessSnapshot(sn) : sn; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var processedSn = this.preProcessSnapshot(value); - return this._subtype.validate(processedSn, context); - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subtype; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "is", { - enumerable: false, - configurable: true, - writable: true, - value: function (thing) { - var value = isType(thing) - ? this._subtype - : isStateTreeNode(thing) - ? getSnapshot(thing, false) - : this.preProcessSnapshot(thing); - return this._subtype.validate(value, [{ path: "", type: this._subtype }]).length === 0; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this._subtype.isAssignableFrom(type); - } - }); - return SnapshotProcessor; -}(BaseType)); -function proxyNodeTypeMethods(nodeType, snapshotProcessorType) { - var e_1, _a; - var methods = []; - for (var _i = 2; _i < arguments.length; _i++) { - methods[_i - 2] = arguments[_i]; - } - try { - for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var method = methods_1_1.value; - nodeType[method] = snapshotProcessorType[method].bind(snapshotProcessorType); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1.return)) _a.call(methods_1); - } - finally { if (e_1) throw e_1.error; } - } -} -/** - * `types.snapshotProcessor` - Runs a pre/post snapshot processor before/after serializing a given type. - * - * Example: - * ```ts - * const Todo1 = types.model({ text: types.string }) - * // in the backend the text type must be null when empty - * interface BackendTodo { - * text: string | null - * } - * const Todo2 = types.snapshotProcessor(Todo1, { - * // from snapshot to instance - * preProcessor(sn: BackendTodo) { - * return { - * text: sn.text || ""; - * } - * }, - * // from instance to snapshot - * postProcessor(sn): BackendTodo { - * return { - * text: !sn.text ? null : sn.text - * } - * } - * }) - * ``` - * - * @param type Type to run the processors over. - * @param processors Processors to run. - * @param name Type name, or undefined to inherit the inner type one. - * @returns - */ -function snapshotProcessor(type, processors, name) { - return new SnapshotProcessor(type, processors, name); -} - -var needsIdentifierError = "Map.put can only be used to store complex values that have an identifier type attribute"; -function tryCollectModelTypes(type, modelTypes) { - var e_1, _a; - var subtypes = type.getSubTypes(); - if (subtypes === cannotDetermineSubtype) { - return false; - } - if (subtypes) { - var subtypesArray = asArray(subtypes); - try { - for (var subtypesArray_1 = __values(subtypesArray), subtypesArray_1_1 = subtypesArray_1.next(); !subtypesArray_1_1.done; subtypesArray_1_1 = subtypesArray_1.next()) { - var subtype = subtypesArray_1_1.value; - if (!tryCollectModelTypes(subtype, modelTypes)) - return false; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (subtypesArray_1_1 && !subtypesArray_1_1.done && (_a = subtypesArray_1.return)) _a.call(subtypesArray_1); - } - finally { if (e_1) throw e_1.error; } - } - } - if (type instanceof ModelType) { - modelTypes.push(type); - } - return true; -} -/** - * @internal - * @hidden - */ -var MapIdentifierMode; -(function (MapIdentifierMode) { - MapIdentifierMode[MapIdentifierMode["UNKNOWN"] = 0] = "UNKNOWN"; - MapIdentifierMode[MapIdentifierMode["YES"] = 1] = "YES"; - MapIdentifierMode[MapIdentifierMode["NO"] = 2] = "NO"; -})(MapIdentifierMode || (MapIdentifierMode = {})); -var MSTMap = /** @class */ (function (_super) { - __extends$1(MSTMap, _super); - function MSTMap(initialData) { - return _super.call(this, initialData, observable$1.ref.enhancer) || this; - } - Object.defineProperty(MSTMap.prototype, "get", { - enumerable: false, - configurable: true, - writable: true, - value: function (key) { - // maybe this is over-enthousiastic? normalize numeric keys to strings - return _super.prototype.get.call(this, "" + key); - } - }); - Object.defineProperty(MSTMap.prototype, "has", { - enumerable: false, - configurable: true, - writable: true, - value: function (key) { - return _super.prototype.has.call(this, "" + key); - } - }); - Object.defineProperty(MSTMap.prototype, "delete", { - enumerable: false, - configurable: true, - writable: true, - value: function (key) { - return _super.prototype.delete.call(this, "" + key); - } - }); - Object.defineProperty(MSTMap.prototype, "set", { - enumerable: false, - configurable: true, - writable: true, - value: function (key, value) { - return _super.prototype.set.call(this, "" + key, value); - } - }); - Object.defineProperty(MSTMap.prototype, "put", { - enumerable: false, - configurable: true, - writable: true, - value: function (value) { - if (!value) - throw fail$1("Map.put cannot be used to set empty values"); - if (isStateTreeNode(value)) { - var node = getStateTreeNode(value); - if (node.identifier === null) { - throw fail$1(needsIdentifierError); - } - this.set(node.identifier, value); - return value; - } - else if (!isMutable(value)) { - throw fail$1("Map.put can only be used to store complex values"); - } - else { - var mapNode = getStateTreeNode(this); - var mapType = mapNode.type; - if (mapType.identifierMode !== MapIdentifierMode.YES) { - throw fail$1(needsIdentifierError); - } - var idAttr = mapType.mapIdentifierAttribute; - var id = value[idAttr]; - if (!isValidIdentifier(id)) { - // try again but this time after creating a node for the value - // since it might be an optional identifier - var newNode = this.put(mapType.getChildType().create(value, mapNode.environment)); - return this.put(getSnapshot(newNode)); - } - var key = normalizeIdentifier(id); - this.set(key, value); - return this.get(key); - } - } - }); - return MSTMap; -}(ObservableMap)); -/** - * @internal - * @hidden - */ -var MapType = /** @class */ (function (_super) { - __extends$1(MapType, _super); - function MapType(name, _subType, hookInitializers) { - if (hookInitializers === void 0) { hookInitializers = []; } - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_subType", { - enumerable: true, - configurable: true, - writable: true, - value: _subType - }); - Object.defineProperty(_this, "identifierMode", { - enumerable: true, - configurable: true, - writable: true, - value: MapIdentifierMode.UNKNOWN - }); - Object.defineProperty(_this, "mapIdentifierAttribute", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Map - }); - Object.defineProperty(_this, "hookInitializers", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - _this._determineIdentifierMode(); - _this.hookInitializers = hookInitializers; - return _this; - } - Object.defineProperty(MapType.prototype, "hooks", { - enumerable: false, - configurable: true, - writable: true, - value: function (hooks) { - var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks]; - return new MapType(this.name, this._subType, hookInitializers); - } - }); - Object.defineProperty(MapType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - this._determineIdentifierMode(); - return createObjectNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(MapType.prototype, "_determineIdentifierMode", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this.identifierMode !== MapIdentifierMode.UNKNOWN) { - return; - } - var modelTypes = []; - if (tryCollectModelTypes(this._subType, modelTypes)) { - var identifierAttribute_1 = undefined; - modelTypes.forEach(function (type) { - if (type.identifierAttribute) { - if (identifierAttribute_1 && identifierAttribute_1 !== type.identifierAttribute) { - throw fail$1("The objects in a map should all have the same identifier attribute, expected '" + identifierAttribute_1 + "', but child of type '" + type.name + "' declared attribute '" + type.identifierAttribute + "' as identifier"); - } - identifierAttribute_1 = type.identifierAttribute; - } - }); - if (identifierAttribute_1) { - this.identifierMode = MapIdentifierMode.YES; - this.mapIdentifierAttribute = identifierAttribute_1; - } - else { - this.identifierMode = MapIdentifierMode.NO; - } - } - } - }); - Object.defineProperty(MapType.prototype, "initializeChildNodes", { - enumerable: false, - configurable: true, - writable: true, - value: function (objNode, initialSnapshot) { - if (initialSnapshot === void 0) { initialSnapshot = {}; } - var subType = objNode.type._subType; - var result = {}; - Object.keys(initialSnapshot).forEach(function (name) { - result[name] = subType.instantiate(objNode, name, undefined, initialSnapshot[name]); - }); - return result; - } - }); - Object.defineProperty(MapType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - return new MSTMap(childNodes); - } - }); - Object.defineProperty(MapType.prototype, "finalizeNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, instance) { - interceptReads(instance, node.unbox); - var type = node.type; - type.hookInitializers.forEach(function (initializer) { - var hooks = initializer(instance); - Object.keys(hooks).forEach(function (name) { - var hook = hooks[name]; - var actionInvoker = createActionInvoker(instance, name, hook); - (addHiddenFinalProp )(instance, name, actionInvoker); - }); - }); - intercept(instance, this.willChange); - observe(instance, this.didChange); - } - }); - Object.defineProperty(MapType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "Map"; - } - }); - Object.defineProperty(MapType.prototype, "getChildren", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - // return (node.storedValue as ObservableMap).values() - return values(node.storedValue); - } - }); - Object.defineProperty(MapType.prototype, "getChildNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, key) { - var childNode = node.storedValue.get("" + key); - if (!childNode) - throw fail$1("Not a child " + key); - return childNode; - } - }); - Object.defineProperty(MapType.prototype, "willChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (change) { - var node = getStateTreeNode(change.object); - var key = change.name; - node.assertWritable({ subpath: key }); - var mapType = node.type; - var subType = mapType._subType; - switch (change.type) { - case "update": - { - var newValue = change.newValue; - var oldValue = change.object.get(key); - if (newValue === oldValue) - return null; - typecheckInternal(subType, newValue); - change.newValue = subType.reconcile(node.getChildNode(key), change.newValue, node, key); - mapType.processIdentifier(key, change.newValue); - } - break; - case "add": - { - typecheckInternal(subType, change.newValue); - change.newValue = subType.instantiate(node, key, undefined, change.newValue); - mapType.processIdentifier(key, change.newValue); - } - break; - } - return change; - } - }); - Object.defineProperty(MapType.prototype, "processIdentifier", { - enumerable: false, - configurable: true, - writable: true, - value: function (expected, node) { - if (this.identifierMode === MapIdentifierMode.YES && node instanceof ObjectNode) { - var identifier = node.identifier; - if (identifier !== expected) - throw fail$1("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '" + identifier + "', but expected: '" + expected + "'"); - } - } - }); - Object.defineProperty(MapType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var res = {}; - node.getChildren().forEach(function (childNode) { - res[childNode.subpath] = childNode.snapshot; - }); - return res; - } - }); - Object.defineProperty(MapType.prototype, "processInitialSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - var processed = {}; - Object.keys(childNodes).forEach(function (key) { - processed[key] = childNodes[key].getSnapshot(); - }); - return processed; - } - }); - Object.defineProperty(MapType.prototype, "didChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (change) { - var node = getStateTreeNode(change.object); - switch (change.type) { - case "update": - return void node.emitPatch({ - op: "replace", - path: escapeJsonPath(change.name), - value: change.newValue.snapshot, - oldValue: change.oldValue ? change.oldValue.snapshot : undefined - }, node); - case "add": - return void node.emitPatch({ - op: "add", - path: escapeJsonPath(change.name), - value: change.newValue.snapshot, - oldValue: undefined - }, node); - case "delete": - // a node got deleted, get the old snapshot and make the node die - var oldSnapshot = change.oldValue.snapshot; - change.oldValue.die(); - // emit the patch - return void node.emitPatch({ - op: "remove", - path: escapeJsonPath(change.name), - oldValue: oldSnapshot - }, node); - } - } - }); - Object.defineProperty(MapType.prototype, "applyPatchLocally", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath, patch) { - var target = node.storedValue; - switch (patch.op) { - case "add": - case "replace": - target.set(subpath, patch.value); - break; - case "remove": - target.delete(subpath); - break; - } - } - }); - Object.defineProperty(MapType.prototype, "applySnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, snapshot) { - typecheckInternal(this, snapshot); - var target = node.storedValue; - var currentKeys = {}; - Array.from(target.keys()).forEach(function (key) { - currentKeys[key] = false; - }); - if (snapshot) { - // Don't use target.replace, as it will throw away all existing items first - for (var key in snapshot) { - target.set(key, snapshot[key]); - currentKeys["" + key] = true; - } - } - Object.keys(currentKeys).forEach(function (key) { - if (currentKeys[key] === false) - target.delete(key); - }); - } - }); - Object.defineProperty(MapType.prototype, "getChildType", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subType; - } - }); - Object.defineProperty(MapType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var _this = this; - if (!isPlainObject(value)) { - return typeCheckFailure(context, value, "Value is not a plain object"); - } - return flattenTypeErrors(Object.keys(value).map(function (path) { - return _this._subType.validate(value[path], getContextForPath(context, path, _this._subType)); - })); - } - }); - Object.defineProperty(MapType.prototype, "getDefaultSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return EMPTY_OBJECT; - } - }); - Object.defineProperty(MapType.prototype, "removeChild", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath) { - node.storedValue.delete(subpath); - } - }); - return MapType; -}(ComplexType)); -MapType.prototype.applySnapshot = action(MapType.prototype.applySnapshot); -/** - * `types.map` - Creates a key based collection type who's children are all of a uniform declared type. - * If the type stored in a map has an identifier, it is mandatory to store the child under that identifier in the map. - * - * This type will always produce [observable maps](https://mobx.js.org/api.html#observablemap) - * - * Example: - * ```ts - * const Todo = types.model({ - * id: types.identifier, - * task: types.string - * }) - * - * const TodoStore = types.model({ - * todos: types.map(Todo) - * }) - * - * const s = TodoStore.create({ todos: {} }) - * unprotect(s) - * s.todos.set(17, { task: "Grab coffee", id: 17 }) - * s.todos.put({ task: "Grab cookie", id: 18 }) // put will infer key from the identifier - * console.log(s.todos.get(17).task) // prints: "Grab coffee" - * ``` - * - * @param subtype - * @returns - */ -function map$1(subtype) { - return new MapType("map", subtype); -} - -/** - * @internal - * @hidden - */ -var ArrayType = /** @class */ (function (_super) { - __extends$1(ArrayType, _super); - function ArrayType(name, _subType, hookInitializers) { - if (hookInitializers === void 0) { hookInitializers = []; } - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_subType", { - enumerable: true, - configurable: true, - writable: true, - value: _subType - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Array - }); - Object.defineProperty(_this, "hookInitializers", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - _this.hookInitializers = hookInitializers; - return _this; - } - Object.defineProperty(ArrayType.prototype, "hooks", { - enumerable: false, - configurable: true, - writable: true, - value: function (hooks) { - var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks]; - return new ArrayType(this.name, this._subType, hookInitializers); - } - }); - Object.defineProperty(ArrayType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - return createObjectNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(ArrayType.prototype, "initializeChildNodes", { - enumerable: false, - configurable: true, - writable: true, - value: function (objNode, snapshot) { - if (snapshot === void 0) { snapshot = []; } - var subType = objNode.type._subType; - var result = {}; - snapshot.forEach(function (item, index) { - var subpath = "" + index; - result[subpath] = subType.instantiate(objNode, subpath, undefined, item); - }); - return result; - } - }); - Object.defineProperty(ArrayType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - return observable$1.array(convertChildNodesToArray(childNodes), mobxShallow); - } - }); - Object.defineProperty(ArrayType.prototype, "finalizeNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, instance) { - getAdministration(instance).dehancer = node.unbox; - var type = node.type; - type.hookInitializers.forEach(function (initializer) { - var hooks = initializer(instance); - Object.keys(hooks).forEach(function (name) { - var hook = hooks[name]; - var actionInvoker = createActionInvoker(instance, name, hook); - (addHiddenFinalProp )(instance, name, actionInvoker); - }); - }); - intercept(instance, this.willChange); - observe(instance, this.didChange); - } - }); - Object.defineProperty(ArrayType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subType.describe() + "[]"; - } - }); - Object.defineProperty(ArrayType.prototype, "getChildren", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return node.storedValue.slice(); - } - }); - Object.defineProperty(ArrayType.prototype, "getChildNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, key) { - var index = Number(key); - if (index < node.storedValue.length) - return node.storedValue[index]; - throw fail$1("Not a child: " + key); - } - }); - Object.defineProperty(ArrayType.prototype, "willChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (change) { - var node = getStateTreeNode(change.object); - node.assertWritable({ subpath: "" + change.index }); - var subType = node.type._subType; - var childNodes = node.getChildren(); - switch (change.type) { - case "update": - { - if (change.newValue === change.object[change.index]) - return null; - var updatedNodes = reconcileArrayChildren(node, subType, [childNodes[change.index]], [change.newValue], [change.index]); - if (!updatedNodes) { - return null; - } - change.newValue = updatedNodes[0]; - } - break; - case "splice": - { - var index_1 = change.index, removedCount = change.removedCount, added = change.added; - var addedNodes = reconcileArrayChildren(node, subType, childNodes.slice(index_1, index_1 + removedCount), added, added.map(function (_, i) { return index_1 + i; })); - if (!addedNodes) { - return null; - } - change.added = addedNodes; - // update paths of remaining items - for (var i = index_1 + removedCount; i < childNodes.length; i++) { - childNodes[i].setParent(node, "" + (i + added.length - removedCount)); - } - } - break; - } - return change; - } - }); - Object.defineProperty(ArrayType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return node.getChildren().map(function (childNode) { return childNode.snapshot; }); - } - }); - Object.defineProperty(ArrayType.prototype, "processInitialSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - var processed = []; - Object.keys(childNodes).forEach(function (key) { - processed.push(childNodes[key].getSnapshot()); - }); - return processed; - } - }); - Object.defineProperty(ArrayType.prototype, "didChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (change) { - var node = getStateTreeNode(change.object); - switch (change.type) { - case "update": - return void node.emitPatch({ - op: "replace", - path: "" + change.index, - value: change.newValue.snapshot, - oldValue: change.oldValue ? change.oldValue.snapshot : undefined - }, node); - case "splice": - for (var i = change.removedCount - 1; i >= 0; i--) - node.emitPatch({ - op: "remove", - path: "" + (change.index + i), - oldValue: change.removed[i].snapshot - }, node); - for (var i = 0; i < change.addedCount; i++) - node.emitPatch({ - op: "add", - path: "" + (change.index + i), - value: node.getChildNode("" + (change.index + i)).snapshot, - oldValue: undefined - }, node); - return; - } - } - }); - Object.defineProperty(ArrayType.prototype, "applyPatchLocally", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath, patch) { - var target = node.storedValue; - var index = subpath === "-" ? target.length : Number(subpath); - switch (patch.op) { - case "replace": - target[index] = patch.value; - break; - case "add": - target.splice(index, 0, patch.value); - break; - case "remove": - target.splice(index, 1); - break; - } - } - }); - Object.defineProperty(ArrayType.prototype, "applySnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, snapshot) { - typecheckInternal(this, snapshot); - var target = node.storedValue; - target.replace(snapshot); - } - }); - Object.defineProperty(ArrayType.prototype, "getChildType", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subType; - } - }); - Object.defineProperty(ArrayType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var _this = this; - if (!isArray$2(value)) { - return typeCheckFailure(context, value, "Value is not an array"); - } - return flattenTypeErrors(value.map(function (item, index) { - return _this._subType.validate(item, getContextForPath(context, "" + index, _this._subType)); - })); - } - }); - Object.defineProperty(ArrayType.prototype, "getDefaultSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return EMPTY_ARRAY; - } - }); - Object.defineProperty(ArrayType.prototype, "removeChild", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath) { - node.storedValue.splice(Number(subpath), 1); - } - }); - return ArrayType; -}(ComplexType)); -ArrayType.prototype.applySnapshot = action(ArrayType.prototype.applySnapshot); -/** - * `types.array` - Creates an index based collection type who's children are all of a uniform declared type. - * - * This type will always produce [observable arrays](https://mobx.js.org/api.html#observablearray) - * - * Example: - * ```ts - * const Todo = types.model({ - * task: types.string - * }) - * - * const TodoStore = types.model({ - * todos: types.array(Todo) - * }) - * - * const s = TodoStore.create({ todos: [] }) - * unprotect(s) // needed to allow modifying outside of an action - * s.todos.push({ task: "Grab coffee" }) - * console.log(s.todos[0]) // prints: "Grab coffee" - * ``` - * - * @param subtype - * @returns - */ -function array(subtype) { - return new ArrayType(subtype.name + "[]", subtype); -} -function reconcileArrayChildren(parent, childType, oldNodes, newValues, newPaths) { - var nothingChanged = true; - for (var i = 0;; i++) { - var hasNewNode = i <= newValues.length - 1; - var oldNode = oldNodes[i]; - var newValue = hasNewNode ? newValues[i] : undefined; - var newPath = "" + newPaths[i]; - // for some reason, instead of newValue we got a node, fallback to the storedValue - // TODO: https://github.com/mobxjs/mobx-state-tree/issues/340#issuecomment-325581681 - if (isNode(newValue)) - newValue = newValue.storedValue; - if (!oldNode && !hasNewNode) { - // both are empty, end - break; - } - else if (!hasNewNode) { - // new one does not exists - nothingChanged = false; - oldNodes.splice(i, 1); - if (oldNode instanceof ObjectNode) { - // since it is going to be returned by pop/splice/shift better create it before killing it - // so it doesn't end up in an undead state - oldNode.createObservableInstanceIfNeeded(); - } - oldNode.die(); - i--; - } - else if (!oldNode) { - // there is no old node, create it - // check if already belongs to the same parent. if so, avoid pushing item in. only swapping can occur. - if (isStateTreeNode(newValue) && getStateTreeNode(newValue).parent === parent) { - // this node is owned by this parent, but not in the reconcilable set, so it must be double - throw fail$1("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 '" + parent.path + "/" + newPath + "', but it lives already at '" + getStateTreeNode(newValue).path + "'"); - } - nothingChanged = false; - var newNode = valueAsNode(childType, parent, newPath, newValue); - oldNodes.splice(i, 0, newNode); - } - else if (areSame(oldNode, newValue)) { - // both are the same, reconcile - oldNodes[i] = valueAsNode(childType, parent, newPath, newValue, oldNode); - } - else { - // nothing to do, try to reorder - var oldMatch = undefined; - // find a possible candidate to reuse - for (var j = i; j < oldNodes.length; j++) { - if (areSame(oldNodes[j], newValue)) { - oldMatch = oldNodes.splice(j, 1)[0]; - break; - } - } - nothingChanged = false; - var newNode = valueAsNode(childType, parent, newPath, newValue, oldMatch); - oldNodes.splice(i, 0, newNode); - } - } - return nothingChanged ? null : oldNodes; -} -/** - * Convert a value to a node at given parent and subpath. Attempts to reuse old node if possible and given. - */ -function valueAsNode(childType, parent, subpath, newValue, oldNode) { - // ensure the value is valid-ish - typecheckInternal(childType, newValue); - function getNewNode() { - // the new value has a MST node - if (isStateTreeNode(newValue)) { - var childNode = getStateTreeNode(newValue); - childNode.assertAlive(EMPTY_OBJECT); - // the node lives here - if (childNode.parent !== null && childNode.parent === parent) { - childNode.setParent(parent, subpath); - return childNode; - } - } - // there is old node and new one is a value/snapshot - if (oldNode) { - return childType.reconcile(oldNode, newValue, parent, subpath); - } - // nothing to do, create from scratch - return childType.instantiate(parent, subpath, undefined, newValue); - } - var newNode = getNewNode(); - if (oldNode && oldNode !== newNode) { - if (oldNode instanceof ObjectNode) { - // since it is going to be returned by pop/splice/shift better create it before killing it - // so it doesn't end up in an undead state - oldNode.createObservableInstanceIfNeeded(); - } - oldNode.die(); - } - return newNode; -} -/** - * Check if a node holds a value. - */ -function areSame(oldNode, newValue) { - // never consider dead old nodes for reconciliation - if (!oldNode.isAlive) { - return false; - } - // the new value has the same node - if (isStateTreeNode(newValue)) { - var newNode = getStateTreeNode(newValue); - return newNode.isAlive && newNode === oldNode; - } - // the provided value is the snapshot of the old node - if (oldNode.snapshot === newValue) { - return true; - } - // new value is a snapshot with the correct identifier - return (oldNode instanceof ObjectNode && - oldNode.identifier !== null && - oldNode.identifierAttribute && - isPlainObject(newValue) && - oldNode.identifier === normalizeIdentifier(newValue[oldNode.identifierAttribute]) && - oldNode.type.is(newValue)); -} - -var PRE_PROCESS_SNAPSHOT = "preProcessSnapshot"; -var POST_PROCESS_SNAPSHOT = "postProcessSnapshot"; -function objectTypeToString() { - return getStateTreeNode(this).toString(); -} -var defaultObjectOptions = { - name: "AnonymousModel", - properties: {}, - initializers: EMPTY_ARRAY -}; -function toPropertiesObject(declaredProps) { - // loop through properties and ensures that all items are types - return Object.keys(declaredProps).reduce(function (props, key) { - var _a, _b, _c; - // warn if user intended a HOOK - if (key in Hook) - throw fail$1("Hook '" + key + "' was defined as property. Hooks should be defined as part of the actions"); - // the user intended to use a view - var descriptor = Object.getOwnPropertyDescriptor(props, key); - if ("get" in descriptor) { - throw fail$1("Getters are not supported as properties. Please use views instead"); - } - // undefined and null are not valid - var value = descriptor.value; - if (value === null || value === undefined) { - throw fail$1("The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?"); - // its a primitive, convert to its type - } - else if (isPrimitive(value)) { - return Object.assign({}, props, (_a = {}, - _a[key] = optional(getPrimitiveFactoryFromValue(value), value), - _a)); - // map defaults to empty object automatically for models - } - else if (value instanceof MapType) { - return Object.assign({}, props, (_b = {}, - _b[key] = optional(value, {}), - _b)); - } - else if (value instanceof ArrayType) { - return Object.assign({}, props, (_c = {}, _c[key] = optional(value, []), _c)); - // its already a type - } - else if (isType(value)) { - return props; - // its a function, maybe the user wanted a view? - } - else { - throw fail$1("Invalid type definition for property '" + key + "', cannot infer a type from a value like '" + value + "' (" + typeof value + ")"); - } - }, declaredProps); -} -/** - * @internal - * @hidden - */ -var ModelType = /** @class */ (function (_super) { - __extends$1(ModelType, _super); - function ModelType(opts) { - var _this = _super.call(this, opts.name || defaultObjectOptions.name) || this; - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Object - }); - /* - * The original object definition - */ - Object.defineProperty(_this, "initializers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "properties", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "preProcessor", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "postProcessor", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "propertyNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "named", { - enumerable: true, - configurable: true, - writable: true, - value: function (name) { - return _this.cloneAndEnhance({ name: name }); - } - }); - Object.defineProperty(_this, "props", { - enumerable: true, - configurable: true, - writable: true, - value: function (properties) { - return _this.cloneAndEnhance({ properties: properties }); - } - }); - Object.defineProperty(_this, "preProcessSnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: function (preProcessor) { - var currentPreprocessor = _this.preProcessor; - if (!currentPreprocessor) - return _this.cloneAndEnhance({ preProcessor: preProcessor }); - else - return _this.cloneAndEnhance({ - preProcessor: function (snapshot) { return currentPreprocessor(preProcessor(snapshot)); } - }); - } - }); - Object.defineProperty(_this, "postProcessSnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: function (postProcessor) { - var currentPostprocessor = _this.postProcessor; - if (!currentPostprocessor) - return _this.cloneAndEnhance({ postProcessor: postProcessor }); - else - return _this.cloneAndEnhance({ - postProcessor: function (snapshot) { return postProcessor(currentPostprocessor(snapshot)); } - }); - } - }); - Object.assign(_this, defaultObjectOptions, opts); - // ensures that any default value gets converted to its related type - _this.properties = toPropertiesObject(_this.properties); - freeze(_this.properties); // make sure nobody messes with it - _this.propertyNames = Object.keys(_this.properties); - _this.identifierAttribute = _this._getIdentifierAttribute(); - return _this; - } - Object.defineProperty(ModelType.prototype, "_getIdentifierAttribute", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var identifierAttribute = undefined; - this.forAllProps(function (propName, propType) { - if (propType.flags & TypeFlags.Identifier) { - if (identifierAttribute) - throw fail$1("Cannot define property '" + propName + "' as object identifier, property '" + identifierAttribute + "' is already defined as identifier property"); - identifierAttribute = propName; - } - }); - return identifierAttribute; - } - }); - Object.defineProperty(ModelType.prototype, "cloneAndEnhance", { - enumerable: false, - configurable: true, - writable: true, - value: function (opts) { - return new ModelType({ - name: opts.name || this.name, - properties: Object.assign({}, this.properties, opts.properties), - initializers: this.initializers.concat(opts.initializers || []), - preProcessor: opts.preProcessor || this.preProcessor, - postProcessor: opts.postProcessor || this.postProcessor - }); - } - }); - Object.defineProperty(ModelType.prototype, "actions", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - var actionInitializer = function (self) { - _this.instantiateActions(self, fn(self)); - return self; - }; - return this.cloneAndEnhance({ initializers: [actionInitializer] }); - } - }); - Object.defineProperty(ModelType.prototype, "instantiateActions", { - enumerable: false, - configurable: true, - writable: true, - value: function (self, actions) { - // check if return is correct - if (!isPlainObject(actions)) - throw fail$1("actions initializer should return a plain object containing actions"); - // bind actions to the object created - Object.keys(actions).forEach(function (name) { - // warn if preprocessor was given - if (name === PRE_PROCESS_SNAPSHOT) - throw fail$1("Cannot define action '" + PRE_PROCESS_SNAPSHOT + "', it should be defined using 'type.preProcessSnapshot(fn)' instead"); - // warn if postprocessor was given - if (name === POST_PROCESS_SNAPSHOT) - throw fail$1("Cannot define action '" + POST_PROCESS_SNAPSHOT + "', it should be defined using 'type.postProcessSnapshot(fn)' instead"); - var action2 = actions[name]; - // apply hook composition - var baseAction = self[name]; - if (name in Hook && baseAction) { - var specializedAction_1 = action2; - action2 = function () { - baseAction.apply(null, arguments); - specializedAction_1.apply(null, arguments); - }; - } - // the goal of this is to make sure actions using "this" can call themselves, - // while still allowing the middlewares to register them - var middlewares = action2.$mst_middleware; // make sure middlewares are not lost - var boundAction = action2.bind(actions); - boundAction.$mst_middleware = middlewares; - var actionInvoker = createActionInvoker(self, name, boundAction); - actions[name] = actionInvoker; - (addHiddenFinalProp )(self, name, actionInvoker); - }); - } - }); - Object.defineProperty(ModelType.prototype, "volatile", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - if (typeof fn !== "function") { - throw fail$1("You passed an " + typeof fn + " to volatile state as an argument, when function is expected"); - } - var stateInitializer = function (self) { - _this.instantiateVolatileState(self, fn(self)); - return self; - }; - return this.cloneAndEnhance({ initializers: [stateInitializer] }); - } - }); - Object.defineProperty(ModelType.prototype, "instantiateVolatileState", { - enumerable: false, - configurable: true, - writable: true, - value: function (self, state) { - // check views return - if (!isPlainObject(state)) - throw fail$1("volatile state initializer should return a plain object containing state"); - set(self, state); - } - }); - Object.defineProperty(ModelType.prototype, "extend", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - var initializer = function (self) { - var _a = fn(self), actions = _a.actions, views = _a.views, state = _a.state, rest = __rest(_a, ["actions", "views", "state"]); - for (var key in rest) - throw fail$1("The `extend` function should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '" + key + "'"); - if (state) - _this.instantiateVolatileState(self, state); - if (views) - _this.instantiateViews(self, views); - if (actions) - _this.instantiateActions(self, actions); - return self; - }; - return this.cloneAndEnhance({ initializers: [initializer] }); - } - }); - Object.defineProperty(ModelType.prototype, "views", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - var viewInitializer = function (self) { - _this.instantiateViews(self, fn(self)); - return self; - }; - return this.cloneAndEnhance({ initializers: [viewInitializer] }); - } - }); - Object.defineProperty(ModelType.prototype, "instantiateViews", { - enumerable: false, - configurable: true, - writable: true, - value: function (self, views) { - // check views return - if (!isPlainObject(views)) - throw fail$1("views initializer should return a plain object containing views"); - Object.keys(views).forEach(function (key) { - var _a; - // is this a computed property? - var descriptor = Object.getOwnPropertyDescriptor(views, key); - if ("get" in descriptor) { - apiDefineProperty(self, key, descriptor); - makeObservable(self, (_a = {}, _a[key] = computed, _a)); - } - else if (typeof descriptor.value === "function") { - (addHiddenFinalProp )(self, key, descriptor.value); - } - else { - throw fail$1("A view member should either be a function or getter based property"); - } - }); - } - }); - Object.defineProperty(ModelType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var value = isStateTreeNode(initialValue) - ? initialValue - : this.applySnapshotPreProcessor(initialValue); - return createObjectNode(this, parent, subpath, environment, value); - // Optimization: record all prop- view- and action names after first construction, and generate an optimal base class - // that pre-reserves all these fields for fast object-member lookups - } - }); - Object.defineProperty(ModelType.prototype, "initializeChildNodes", { - enumerable: false, - configurable: true, - writable: true, - value: function (objNode, initialSnapshot) { - if (initialSnapshot === void 0) { initialSnapshot = {}; } - var type = objNode.type; - var result = {}; - type.forAllProps(function (name, childType) { - result[name] = childType.instantiate(objNode, name, undefined, initialSnapshot[name]); - }); - return result; - } - }); - Object.defineProperty(ModelType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - return observable$1.object(childNodes, EMPTY_OBJECT, mobxShallow); - } - }); - Object.defineProperty(ModelType.prototype, "finalizeNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, instance) { - addHiddenFinalProp(instance, "toString", objectTypeToString); - this.forAllProps(function (name) { - interceptReads(instance, name, node.unbox); - }); - this.initializers.reduce(function (self, fn) { return fn(self); }, instance); - intercept(instance, this.willChange); - observe(instance, this.didChange); - } - }); - Object.defineProperty(ModelType.prototype, "willChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (chg) { - // TODO: mobx typings don't seem to take into account that newValue can be set even when removing a prop - var change = chg; - var node = getStateTreeNode(change.object); - var subpath = change.name; - node.assertWritable({ subpath: subpath }); - var childType = node.type.properties[subpath]; - // only properties are typed, state are stored as-is references - if (childType) { - typecheckInternal(childType, change.newValue); - change.newValue = childType.reconcile(node.getChildNode(subpath), change.newValue, node, subpath); - } - return change; - } - }); - Object.defineProperty(ModelType.prototype, "didChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (chg) { - // TODO: mobx typings don't seem to take into account that newValue can be set even when removing a prop - var change = chg; - var childNode = getStateTreeNode(change.object); - var childType = childNode.type.properties[change.name]; - if (!childType) { - // don't emit patches for volatile state - return; - } - var oldChildValue = change.oldValue ? change.oldValue.snapshot : undefined; - childNode.emitPatch({ - op: "replace", - path: escapeJsonPath(change.name), - value: change.newValue.snapshot, - oldValue: oldChildValue - }, childNode); - } - }); - Object.defineProperty(ModelType.prototype, "getChildren", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var _this = this; - var res = []; - this.forAllProps(function (name) { - res.push(_this.getChildNode(node, name)); - }); - return res; - } - }); - Object.defineProperty(ModelType.prototype, "getChildNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, key) { - if (!(key in this.properties)) - throw fail$1("Not a value property: " + key); - var adm = getAdministration(node.storedValue, key); - var childNode = adm.raw(); - if (!childNode) - throw fail$1("Node not available for property " + key); - return childNode; - } - }); - Object.defineProperty(ModelType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, applyPostProcess) { - var _this = this; - if (applyPostProcess === void 0) { applyPostProcess = true; } - var res = {}; - this.forAllProps(function (name, type) { - getAtom(node.storedValue, name).reportObserved(); - res[name] = _this.getChildNode(node, name).snapshot; - }); - if (applyPostProcess) { - return this.applySnapshotPostProcessor(res); - } - return res; - } - }); - Object.defineProperty(ModelType.prototype, "processInitialSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - var processed = {}; - Object.keys(childNodes).forEach(function (key) { - processed[key] = childNodes[key].getSnapshot(); - }); - return this.applySnapshotPostProcessor(processed); - } - }); - Object.defineProperty(ModelType.prototype, "applyPatchLocally", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath, patch) { - if (!(patch.op === "replace" || patch.op === "add")) { - throw fail$1("object does not support operation " + patch.op); - } - node.storedValue[subpath] = patch.value; - } - }); - Object.defineProperty(ModelType.prototype, "applySnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, snapshot) { - var preProcessedSnapshot = this.applySnapshotPreProcessor(snapshot); - typecheckInternal(this, preProcessedSnapshot); - this.forAllProps(function (name) { - node.storedValue[name] = preProcessedSnapshot[name]; - }); - } - }); - Object.defineProperty(ModelType.prototype, "applySnapshotPreProcessor", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - var processor = this.preProcessor; - return processor ? processor.call(null, snapshot) : snapshot; - } - }); - Object.defineProperty(ModelType.prototype, "applySnapshotPostProcessor", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - var postProcessor = this.postProcessor; - if (postProcessor) - return postProcessor.call(null, snapshot); - return snapshot; - } - }); - Object.defineProperty(ModelType.prototype, "getChildType", { - enumerable: false, - configurable: true, - writable: true, - value: function (propertyName) { - return this.properties[propertyName]; - } - }); - Object.defineProperty(ModelType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var _this = this; - var snapshot = this.applySnapshotPreProcessor(value); - if (!isPlainObject(snapshot)) { - return typeCheckFailure(context, snapshot, "Value is not a plain object"); - } - return flattenTypeErrors(this.propertyNames.map(function (key) { - return _this.properties[key].validate(snapshot[key], getContextForPath(context, key, _this.properties[key])); - })); - } - }); - Object.defineProperty(ModelType.prototype, "forAllProps", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - this.propertyNames.forEach(function (key) { return fn(key, _this.properties[key]); }); - } - }); - Object.defineProperty(ModelType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var _this = this; - // optimization: cache - return ("{ " + - this.propertyNames - .map(function (key) { return key + ": " + _this.properties[key].describe(); }) - .join("; ") + - " }"); - } - }); - Object.defineProperty(ModelType.prototype, "getDefaultSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return EMPTY_OBJECT; - } - }); - Object.defineProperty(ModelType.prototype, "removeChild", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath) { - node.storedValue[subpath] = undefined; - } - }); - return ModelType; -}(ComplexType)); -ModelType.prototype.applySnapshot = action(ModelType.prototype.applySnapshot); -/** - * `types.model` - Creates a new model type by providing a name, properties, volatile state and actions. - * - * See the [model type](/concepts/trees#creating-models) description or the [getting started](intro/getting-started.md#getting-started-1) tutorial. - */ -function model() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var name = typeof args[0] === "string" ? args.shift() : "AnonymousModel"; - var properties = args.shift() || {}; - return new ModelType({ name: name, properties: properties }); -} -/** - * `types.compose` - Composes a new model from one or more existing model types. - * This method can be invoked in two forms: - * Given 2 or more model types, the types are composed into a new Type. - * Given first parameter as a string and 2 or more model types, - * the types are composed into a new Type with the given name - */ -function compose() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // TODO: just join the base type names if no name is provided - var hasTypename = typeof args[0] === "string"; - var typeName = hasTypename ? args[0] : "AnonymousModel"; - if (hasTypename) { - args.shift(); - } - return args - .reduce(function (prev, cur) { - return prev.cloneAndEnhance({ - name: prev.name + "_" + cur.name, - properties: cur.properties, - initializers: cur.initializers, - preProcessor: function (snapshot) { - return cur.applySnapshotPreProcessor(prev.applySnapshotPreProcessor(snapshot)); - }, - postProcessor: function (snapshot) { - return cur.applySnapshotPostProcessor(prev.applySnapshotPostProcessor(snapshot)); - } - }); - }) - .named(typeName); -} -/** - * Returns if a given value represents a model type. - * - * @param type - * @returns - */ -function isModelType(type) { - return isType(type) && (type.flags & TypeFlags.Object) > 0; -} - -// TODO: implement CoreType using types.custom ? -/** - * @internal - * @hidden - */ -var CoreType = /** @class */ (function (_super) { - __extends$1(CoreType, _super); - function CoreType(name, flags, checker, initializer) { - if (initializer === void 0) { initializer = identity$2; } - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: flags - }); - Object.defineProperty(_this, "checker", { - enumerable: true, - configurable: true, - writable: true, - value: checker - }); - Object.defineProperty(_this, "initializer", { - enumerable: true, - configurable: true, - writable: true, - value: initializer - }); - _this.flags = flags; - return _this; - } - Object.defineProperty(CoreType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.name; - } - }); - Object.defineProperty(CoreType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - return createScalarNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(CoreType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - return this.initializer(snapshot); - } - }); - Object.defineProperty(CoreType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (isPrimitive(value) && this.checker(value)) { - return typeCheckSuccess(); - } - var typeName = this.name === "Date" ? "Date or a unix milliseconds timestamp" : this.name; - return typeCheckFailure(context, value, "Value is not a " + typeName); - } - }); - return CoreType; -}(SimpleType)); -/** - * `types.string` - Creates a type that can only contain a string value. - * This type is used for string values by default - * - * Example: - * ```ts - * const Person = types.model({ - * firstName: types.string, - * lastName: "Doe" - * }) - * ``` - */ -// tslint:disable-next-line:variable-name -var string = new CoreType("string", TypeFlags.String, function (v) { return typeof v === "string"; }); -/** - * `types.number` - Creates a type that can only contain a numeric value. - * This type is used for numeric values by default - * - * Example: - * ```ts - * const Vector = types.model({ - * x: types.number, - * y: 1.5 - * }) - * ``` - */ -// tslint:disable-next-line:variable-name -var number = new CoreType("number", TypeFlags.Number, function (v) { return typeof v === "number"; }); -/** - * `types.integer` - Creates a type that can only contain an integer value. - * This type is used for integer values by default - * - * Example: - * ```ts - * const Size = types.model({ - * width: types.integer, - * height: 10 - * }) - * ``` - */ -// tslint:disable-next-line:variable-name -var integer = new CoreType("integer", TypeFlags.Integer, function (v) { return isInteger(v); }); -/** - * `types.boolean` - Creates a type that can only contain a boolean value. - * This type is used for boolean values by default - * - * Example: - * ```ts - * const Thing = types.model({ - * isCool: types.boolean, - * isAwesome: false - * }) - * ``` - */ -// tslint:disable-next-line:variable-name -var boolean = new CoreType("boolean", TypeFlags.Boolean, function (v) { return typeof v === "boolean"; }); -/** - * `types.null` - The type of the value `null` - */ -var nullType = new CoreType("null", TypeFlags.Null, function (v) { return v === null; }); -/** - * `types.undefined` - The type of the value `undefined` - */ -var undefinedType = new CoreType("undefined", TypeFlags.Undefined, function (v) { return v === undefined; }); -var _DatePrimitive = new CoreType("Date", TypeFlags.Date, function (v) { return typeof v === "number" || v instanceof Date; }, function (v) { return (v instanceof Date ? v : new Date(v)); }); -_DatePrimitive.getSnapshot = function (node) { - return node.storedValue.getTime(); -}; -/** - * `types.Date` - Creates a type that can only contain a javascript Date value. - * - * Example: - * ```ts - * const LogLine = types.model({ - * timestamp: types.Date, - * }) - * - * LogLine.create({ timestamp: new Date() }) - * ``` - */ -var DatePrimitive = _DatePrimitive; -/** - * @internal - * @hidden - */ -function getPrimitiveFactoryFromValue(value) { - switch (typeof value) { - case "string": - return string; - case "number": - return number; // In the future, isInteger(value) ? integer : number would be interesting, but would be too breaking for now - case "boolean": - return boolean; - case "object": - if (value instanceof Date) - return DatePrimitive; - } - throw fail$1("Cannot determine primitive type from value " + value); -} -/** - * Returns if a given value represents a primitive type. - * - * @param type - * @returns - */ -function isPrimitiveType(type) { - return (isType(type) && - (type.flags & - (TypeFlags.String | - TypeFlags.Number | - TypeFlags.Integer | - TypeFlags.Boolean | - TypeFlags.Date)) > - 0); -} - -/** - * @internal - * @hidden - */ -var Literal = /** @class */ (function (_super) { - __extends$1(Literal, _super); - function Literal(value) { - var _this = _super.call(this, JSON.stringify(value)) || this; - Object.defineProperty(_this, "value", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Literal - }); - _this.value = value; - return _this; - } - Object.defineProperty(Literal.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - return createScalarNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(Literal.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return JSON.stringify(this.value); - } - }); - Object.defineProperty(Literal.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (isPrimitive(value) && value === this.value) { - return typeCheckSuccess(); - } - return typeCheckFailure(context, value, "Value is not a literal " + JSON.stringify(this.value)); - } - }); - return Literal; -}(SimpleType)); -/** - * `types.literal` - The literal type will return a type that will match only the exact given type. - * The given value must be a primitive, in order to be serialized to a snapshot correctly. - * You can use literal to match exact strings for example the exact male or female string. - * - * Example: - * ```ts - * const Person = types.model({ - * name: types.string, - * gender: types.union(types.literal('male'), types.literal('female')) - * }) - * ``` - * - * @param value The value to use in the strict equal check - * @returns - */ -function literal(value) { - return new Literal(value); -} - -var Refinement = /** @class */ (function (_super) { - __extends$1(Refinement, _super); - function Refinement(name, _subtype, _predicate, _message) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_subtype", { - enumerable: true, - configurable: true, - writable: true, - value: _subtype - }); - Object.defineProperty(_this, "_predicate", { - enumerable: true, - configurable: true, - writable: true, - value: _predicate - }); - Object.defineProperty(_this, "_message", { - enumerable: true, - configurable: true, - writable: true, - value: _message - }); - return _this; - } - Object.defineProperty(Refinement.prototype, "flags", { - get: function () { - return this._subtype.flags | TypeFlags.Refinement; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Refinement.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.name; - } - }); - Object.defineProperty(Refinement.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - // create the child type - return this._subtype.instantiate(parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(Refinement.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this._subtype.isAssignableFrom(type); - } - }); - Object.defineProperty(Refinement.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var subtypeErrors = this._subtype.validate(value, context); - if (subtypeErrors.length > 0) - return subtypeErrors; - var snapshot = isStateTreeNode(value) ? getStateTreeNode(value).snapshot : value; - if (!this._predicate(snapshot)) { - return typeCheckFailure(context, value, this._message(value)); - } - return typeCheckSuccess(); - } - }); - Object.defineProperty(Refinement.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - return this._subtype.reconcile(current, newValue, parent, subpath); - } - }); - Object.defineProperty(Refinement.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subtype; - } - }); - return Refinement; -}(BaseType)); -/** - * `types.refinement` - Creates a type that is more specific than the base type, e.g. `types.refinement(types.string, value => value.length > 5)` to create a type of strings that can only be longer then 5. - * - * @param name - * @param type - * @param predicate - * @returns - */ -function refinement() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var name = typeof args[0] === "string" ? args.shift() : isType(args[0]) ? args[0].name : null; - var type = args[0]; - var predicate = args[1]; - var message = args[2] - ? args[2] - : function (v) { return "Value does not respect the refinement predicate"; }; - return new Refinement(name, type, predicate, message); -} - -/** - * `types.enumeration` - Can be used to create an string based enumeration. - * (note: this methods is just sugar for a union of string literals) - * - * Example: - * ```ts - * const TrafficLight = types.model({ - * color: types.enumeration("Color", ["Red", "Orange", "Green"]) - * }) - * ``` - * - * @param name descriptive name of the enumeration (optional) - * @param options possible values this enumeration can have - * @returns - */ -function enumeration(name, options) { - var realOptions = typeof name === "string" ? options : name; - var type = union.apply(void 0, __spread(realOptions.map(function (option) { return literal("" + option); }))); - if (typeof name === "string") - type.name = name; - return type; -} - -/** - * @internal - * @hidden - */ -var Union = /** @class */ (function (_super) { - __extends$1(Union, _super); - function Union(name, _types, options) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_types", { - enumerable: true, - configurable: true, - writable: true, - value: _types - }); - Object.defineProperty(_this, "_dispatcher", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_eager", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - options = __assign({ eager: true, dispatcher: undefined }, options); - _this._dispatcher = options.dispatcher; - if (!options.eager) - _this._eager = false; - return _this; - } - Object.defineProperty(Union.prototype, "flags", { - get: function () { - var result = TypeFlags.Union; - this._types.forEach(function (type) { - result |= type.flags; - }); - return result; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Union.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this._types.some(function (subType) { return subType.isAssignableFrom(type); }); - } - }); - Object.defineProperty(Union.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "(" + this._types.map(function (factory) { return factory.describe(); }).join(" | ") + ")"; - } - }); - Object.defineProperty(Union.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var type = this.determineType(initialValue, undefined); - if (!type) - throw fail$1("No matching type for union " + this.describe()); // can happen in prod builds - return type.instantiate(parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(Union.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - var type = this.determineType(newValue, current.type); - if (!type) - throw fail$1("No matching type for union " + this.describe()); // can happen in prod builds - return type.reconcile(current, newValue, parent, subpath); - } - }); - Object.defineProperty(Union.prototype, "determineType", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, reconcileCurrentType) { - // try the dispatcher, if defined - if (this._dispatcher) { - return this._dispatcher(value); - } - // find the most accomodating type - // if we are using reconciliation try the current node type first (fix for #1045) - if (reconcileCurrentType) { - if (reconcileCurrentType.is(value)) { - return reconcileCurrentType; - } - return this._types - .filter(function (t) { return t !== reconcileCurrentType; }) - .find(function (type) { return type.is(value); }); - } - else { - return this._types.find(function (type) { return type.is(value); }); - } - } - }); - Object.defineProperty(Union.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (this._dispatcher) { - return this._dispatcher(value).validate(value, context); - } - var allErrors = []; - var applicableTypes = 0; - for (var i = 0; i < this._types.length; i++) { - var type = this._types[i]; - var errors = type.validate(value, context); - if (errors.length === 0) { - if (this._eager) - return typeCheckSuccess(); - else - applicableTypes++; - } - else { - allErrors.push(errors); - } - } - if (applicableTypes === 1) - return typeCheckSuccess(); - return typeCheckFailure(context, value, "No type is applicable for the union").concat(flattenTypeErrors(allErrors)); - } - }); - Object.defineProperty(Union.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._types; - } - }); - return Union; -}(BaseType)); -/** - * `types.union` - Create a union of multiple types. If the correct type cannot be inferred unambiguously from a snapshot, provide a dispatcher function of the form `(snapshot) => Type`. - * - * @param optionsOrType - * @param otherTypes - * @returns - */ -function union(optionsOrType) { - var otherTypes = []; - for (var _i = 1; _i < arguments.length; _i++) { - otherTypes[_i - 1] = arguments[_i]; - } - var options = isType(optionsOrType) ? undefined : optionsOrType; - var types = isType(optionsOrType) ? __spread([optionsOrType], otherTypes) : otherTypes; - var name = "(" + types.map(function (type) { return type.name; }).join(" | ") + ")"; - return new Union(name, types, options); -} - -/** - * @hidden - * @internal - */ -var OptionalValue = /** @class */ (function (_super) { - __extends$1(OptionalValue, _super); - function OptionalValue(_subtype, _defaultValue, optionalValues) { - var _this = _super.call(this, _subtype.name) || this; - Object.defineProperty(_this, "_subtype", { - enumerable: true, - configurable: true, - writable: true, - value: _subtype - }); - Object.defineProperty(_this, "_defaultValue", { - enumerable: true, - configurable: true, - writable: true, - value: _defaultValue - }); - Object.defineProperty(_this, "optionalValues", { - enumerable: true, - configurable: true, - writable: true, - value: optionalValues - }); - return _this; - } - Object.defineProperty(OptionalValue.prototype, "flags", { - get: function () { - return this._subtype.flags | TypeFlags.Optional; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(OptionalValue.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subtype.describe() + "?"; - } - }); - Object.defineProperty(OptionalValue.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - if (this.optionalValues.indexOf(initialValue) >= 0) { - var defaultInstanceOrSnapshot = this.getDefaultInstanceOrSnapshot(); - return this._subtype.instantiate(parent, subpath, environment, defaultInstanceOrSnapshot); - } - return this._subtype.instantiate(parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(OptionalValue.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - return this._subtype.reconcile(current, this.optionalValues.indexOf(newValue) < 0 && this._subtype.is(newValue) - ? newValue - : this.getDefaultInstanceOrSnapshot(), parent, subpath); - } - }); - Object.defineProperty(OptionalValue.prototype, "getDefaultInstanceOrSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var defaultInstanceOrSnapshot = typeof this._defaultValue === "function" - ? this._defaultValue() - : this._defaultValue; - // while static values are already snapshots and checked on types.optional - // generator functions must always be rechecked just in case - if (typeof this._defaultValue === "function") { - typecheckInternal(this, defaultInstanceOrSnapshot); - } - return defaultInstanceOrSnapshot; - } - }); - Object.defineProperty(OptionalValue.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - // defaulted values can be skipped - if (this.optionalValues.indexOf(value) >= 0) { - return typeCheckSuccess(); - } - // bounce validation to the sub-type - return this._subtype.validate(value, context); - } - }); - Object.defineProperty(OptionalValue.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this._subtype.isAssignableFrom(type); - } - }); - Object.defineProperty(OptionalValue.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subtype; - } - }); - return OptionalValue; -}(BaseType)); -function checkOptionalPreconditions(type, defaultValueOrFunction) { - // make sure we never pass direct instances - if (typeof defaultValueOrFunction !== "function" && isStateTreeNode(defaultValueOrFunction)) { - throw fail$1("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead"); - } -} -/** - * `types.optional` - Can be used to create a property with a default value. - * - * Depending on the third argument (`optionalValues`) there are two ways of operation: - * - If the argument is not provided, then if a value is not provided in the snapshot (`undefined` or missing), - * it will default to the provided `defaultValue` - * - If the argument is provided, then if the value in the snapshot matches one of the optional values inside the array then it will - * default to the provided `defaultValue`. Additionally, if one of the optional values inside the array is `undefined` then a missing - * property is also valid. - * - * Note that it is also possible to include values of the same type as the intended subtype as optional values, - * in this case the optional value will be transformed into the `defaultValue` (e.g. `types.optional(types.string, "unnamed", [undefined, ""])` - * will transform the snapshot values `undefined` (and therefore missing) and empty strings into the string `"unnamed"` when it gets - * instantiated). - * - * If `defaultValue` is a function, the function will be invoked for every new instance. - * Applying a snapshot in which the optional value is one of the optional values (or `undefined`/_not_ present if none are provided) causes the - * value to be reset. - * - * Example: - * ```ts - * const Todo = types.model({ - * title: types.string, - * subtitle1: types.optional(types.string, "", [null]), - * subtitle2: types.optional(types.string, "", [null, undefined]), - * done: types.optional(types.boolean, false), - * created: types.optional(types.Date, () => new Date()), - * }) - * - * // if done is missing / undefined it will become false - * // if created is missing / undefined it will get a freshly generated timestamp - * // if subtitle1 is null it will default to "", but it cannot be missing or undefined - * // if subtitle2 is null or undefined it will default to ""; since it can be undefined it can also be missing - * const todo = Todo.create({ title: "Get coffee", subtitle1: null }) - * ``` - * - * @param type - * @param defaultValueOrFunction - * @param optionalValues an optional array with zero or more primitive values (string, number, boolean, null or undefined) - * that will be converted into the default. `[ undefined ]` is assumed when none is provided - * @returns - */ -function optional(type, defaultValueOrFunction, optionalValues) { - checkOptionalPreconditions(type, defaultValueOrFunction); - return new OptionalValue(type, defaultValueOrFunction, optionalValues ? optionalValues : undefinedAsOptionalValues); -} -var undefinedAsOptionalValues = [undefined]; - -var optionalUndefinedType = optional(undefinedType, undefined); -var optionalNullType = optional(nullType, null); -/** - * `types.maybe` - Maybe will make a type nullable, and also optional. - * The value `undefined` will be used to represent nullability. - * - * @param type - * @returns - */ -function maybe(type) { - return union(type, optionalUndefinedType); -} -/** - * `types.maybeNull` - Maybe will make a type nullable, and also optional. - * The value `null` will be used to represent no value. - * - * @param type - * @returns - */ -function maybeNull(type) { - return union(type, optionalNullType); -} - -var Late = /** @class */ (function (_super) { - __extends$1(Late, _super); - function Late(name, _definition) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_definition", { - enumerable: true, - configurable: true, - writable: true, - value: _definition - }); - Object.defineProperty(_this, "_subType", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - return _this; - } - Object.defineProperty(Late.prototype, "flags", { - get: function () { - return (this._subType ? this._subType.flags : 0) | TypeFlags.Late; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Late.prototype, "getSubType", { - enumerable: false, - configurable: true, - writable: true, - value: function (mustSucceed) { - if (!this._subType) { - var t = undefined; - try { - t = this._definition(); - } - catch (e) { - if (e instanceof ReferenceError) - // can happen in strict ES5 code when a definition is self refering - t = undefined; - else - throw e; - } - if (mustSucceed && t === undefined) - throw fail$1("Late type seems to be used too early, the definition (still) returns undefined"); - if (t) { - this._subType = t; - } - } - return this._subType; - } - }); - Object.defineProperty(Late.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - return this.getSubType(true).instantiate(parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(Late.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - return this.getSubType(true).reconcile(current, newValue, parent, subpath); - } - }); - Object.defineProperty(Late.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var t = this.getSubType(false); - return t ? t.name : ""; - } - }); - Object.defineProperty(Late.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var t = this.getSubType(false); - if (!t) { - // See #916; the variable the definition closure is pointing to wasn't defined yet, so can't be evaluted yet here - return typeCheckSuccess(); - } - return t.validate(value, context); - } - }); - Object.defineProperty(Late.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - var t = this.getSubType(false); - return t ? t.isAssignableFrom(type) : false; - } - }); - Object.defineProperty(Late.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var subtype = this.getSubType(false); - return subtype ? subtype : cannotDetermineSubtype; - } - }); - return Late; -}(BaseType)); -/** - * `types.late` - Defines a type that gets implemented later. This is useful when you have to deal with circular dependencies. - * Please notice that when defining circular dependencies TypeScript isn't smart enough to inference them. - * - * Example: - * ```ts - * // TypeScript isn't smart enough to infer self referencing types. - * const Node = types.model({ - * children: types.array(types.late((): IAnyModelType => Node)) // then typecast each array element to Instance - * }) - * ``` - * - * @param name The name to use for the type that will be returned. - * @param type A function that returns the type that will be defined. - * @returns - */ -function late(nameOrType, maybeType) { - var name = typeof nameOrType === "string" ? nameOrType : "late(" + nameOrType.toString() + ")"; - var type = typeof nameOrType === "string" ? maybeType : nameOrType; - return new Late(name, type); -} - -/** - * @internal - * @hidden - */ -var Frozen = /** @class */ (function (_super) { - __extends$1(Frozen, _super); - function Frozen(subType) { - var _this = _super.call(this, subType ? "frozen(" + subType.name + ")" : "frozen") || this; - Object.defineProperty(_this, "subType", { - enumerable: true, - configurable: true, - writable: true, - value: subType - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Frozen - }); - return _this; - } - Object.defineProperty(Frozen.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return ""; - } - }); - Object.defineProperty(Frozen.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, value) { - // create the node - return createScalarNode(this, parent, subpath, environment, deepFreeze(value)); - } - }); - Object.defineProperty(Frozen.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (!isSerializable(value)) { - return typeCheckFailure(context, value, "Value is not serializable and cannot be frozen"); - } - if (this.subType) - return this.subType.validate(value, context); - return typeCheckSuccess(); - } - }); - return Frozen; -}(SimpleType)); -var untypedFrozenInstance = new Frozen(); -/** - * `types.frozen` - Frozen can be used to store any value that is serializable in itself (that is valid JSON). - * Frozen values need to be immutable or treated as if immutable. They need be serializable as well. - * Values stored in frozen will snapshotted as-is by MST, and internal changes will not be tracked. - * - * This is useful to store complex, but immutable values like vectors etc. It can form a powerful bridge to parts of your application that should be immutable, or that assume data to be immutable. - * - * Note: if you want to store free-form state that is mutable, or not serializeable, consider using volatile state instead. - * - * Frozen properties can be defined in three different ways - * 1. `types.frozen(SubType)` - provide a valid MST type and frozen will check if the provided data conforms the snapshot for that type - * 2. `types.frozen({ someDefaultValue: true})` - provide a primitive value, object or array, and MST will infer the type from that object, and also make it the default value for the field - * 3. `types.frozen()` - provide a typescript type, to help in strongly typing the field (design time only) - * - * Example: - * ```ts - * const GameCharacter = types.model({ - * name: string, - * location: types.frozen({ x: 0, y: 0}) - * }) - * - * const hero = GameCharacter.create({ - * name: "Mario", - * location: { x: 7, y: 4 } - * }) - * - * hero.location = { x: 10, y: 2 } // OK - * hero.location.x = 7 // Not ok! - * ``` - * - * ```ts - * type Point = { x: number, y: number } - * const Mouse = types.model({ - * loc: types.frozen() - * }) - * ``` - * - * @param defaultValueOrType - * @returns - */ -function frozen(arg) { - if (arguments.length === 0) - return untypedFrozenInstance; - else if (isType(arg)) - return new Frozen(arg); - else - return optional(untypedFrozenInstance, arg); -} - -function getInvalidationCause(hook) { - switch (hook) { - case Hook.beforeDestroy: - return "destroy"; - case Hook.beforeDetach: - return "detach"; - default: - return undefined; - } -} -var StoredReference = /** @class */ (function () { - function StoredReference(value, targetType) { - Object.defineProperty(this, "targetType", { - enumerable: true, - configurable: true, - writable: true, - value: targetType - }); - Object.defineProperty(this, "identifier", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "node", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "resolvedReference", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (isValidIdentifier(value)) { - this.identifier = value; - } - else if (isStateTreeNode(value)) { - var targetNode = getStateTreeNode(value); - if (!targetNode.identifierAttribute) - throw fail$1("Can only store references with a defined identifier attribute."); - var id = targetNode.unnormalizedIdentifier; - if (id === null || id === undefined) { - throw fail$1("Can only store references to tree nodes with a defined identifier."); - } - this.identifier = id; - } - else { - throw fail$1("Can only store references to tree nodes or identifiers, got: '" + value + "'"); - } - } - Object.defineProperty(StoredReference.prototype, "updateResolvedReference", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var normalizedId = normalizeIdentifier(this.identifier); - var root = node.root; - var lastCacheModification = root.identifierCache.getLastCacheModificationPerId(normalizedId); - if (!this.resolvedReference || - this.resolvedReference.lastCacheModification !== lastCacheModification) { - var targetType = this.targetType; - // reference was initialized with the identifier of the target - var target = root.identifierCache.resolve(targetType, normalizedId); - if (!target) { - throw new InvalidReferenceError("[mobx-state-tree] Failed to resolve reference '" + this.identifier + "' to type '" + this.targetType.name + "' (from node: " + node.path + ")"); - } - this.resolvedReference = { - node: target, - lastCacheModification: lastCacheModification - }; - } - } - }); - Object.defineProperty(StoredReference.prototype, "resolvedValue", { - get: function () { - this.updateResolvedReference(this.node); - return this.resolvedReference.node.value; - }, - enumerable: false, - configurable: true - }); - return StoredReference; -}()); -/** - * @internal - * @hidden - */ -var InvalidReferenceError = /** @class */ (function (_super) { - __extends$1(InvalidReferenceError, _super); - function InvalidReferenceError(m) { - var _this = _super.call(this, m) || this; - Object.setPrototypeOf(_this, InvalidReferenceError.prototype); - return _this; - } - return InvalidReferenceError; -}(Error)); -/** - * @internal - * @hidden - */ -var BaseReferenceType = /** @class */ (function (_super) { - __extends$1(BaseReferenceType, _super); - function BaseReferenceType(targetType, onInvalidated) { - var _this = _super.call(this, "reference(" + targetType.name + ")") || this; - Object.defineProperty(_this, "targetType", { - enumerable: true, - configurable: true, - writable: true, - value: targetType - }); - Object.defineProperty(_this, "onInvalidated", { - enumerable: true, - configurable: true, - writable: true, - value: onInvalidated - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Reference - }); - return _this; - } - Object.defineProperty(BaseReferenceType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.name; - } - }); - Object.defineProperty(BaseReferenceType.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this.targetType.isAssignableFrom(type); - } - }); - Object.defineProperty(BaseReferenceType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - return isValidIdentifier(value) - ? typeCheckSuccess() - : typeCheckFailure(context, value, "Value is not a valid identifier, which is a string or a number"); - } - }); - Object.defineProperty(BaseReferenceType.prototype, "fireInvalidated", { - enumerable: false, - configurable: true, - writable: true, - value: function (cause, storedRefNode, referenceId, refTargetNode) { - // to actually invalidate a reference we need an alive parent, - // since it is a scalar value (immutable-ish) and we need to change it - // from the parent - var storedRefParentNode = storedRefNode.parent; - if (!storedRefParentNode || !storedRefParentNode.isAlive) { - return; - } - var storedRefParentValue = storedRefParentNode.storedValue; - if (!storedRefParentValue) { - return; - } - this.onInvalidated({ - cause: cause, - parent: storedRefParentValue, - invalidTarget: refTargetNode ? refTargetNode.storedValue : undefined, - invalidId: referenceId, - replaceRef: function (newRef) { - applyPatch(storedRefNode.root.storedValue, { - op: "replace", - value: newRef, - path: storedRefNode.path - }); - }, - removeRef: function () { - if (isModelType(storedRefParentNode.type)) { - this.replaceRef(undefined); - } - else { - applyPatch(storedRefNode.root.storedValue, { - op: "remove", - path: storedRefNode.path - }); - } - } - }); - } - }); - Object.defineProperty(BaseReferenceType.prototype, "addTargetNodeWatcher", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode, referenceId) { - var _this = this; - // this will make sure the target node becomes created - var refTargetValue = this.getValue(storedRefNode); - if (!refTargetValue) { - return undefined; - } - var refTargetNode = getStateTreeNode(refTargetValue); - var hookHandler = function (_, refTargetNodeHook) { - var cause = getInvalidationCause(refTargetNodeHook); - if (!cause) { - return; - } - _this.fireInvalidated(cause, storedRefNode, referenceId, refTargetNode); - }; - var refTargetDetachHookDisposer = refTargetNode.registerHook(Hook.beforeDetach, hookHandler); - var refTargetDestroyHookDisposer = refTargetNode.registerHook(Hook.beforeDestroy, hookHandler); - return function () { - refTargetDetachHookDisposer(); - refTargetDestroyHookDisposer(); - }; - } - }); - Object.defineProperty(BaseReferenceType.prototype, "watchTargetNodeForInvalidations", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode, identifier, customGetSet) { - var _this = this; - if (!this.onInvalidated) { - return; - } - var onRefTargetDestroyedHookDisposer; - // get rid of the watcher hook when the stored ref node is destroyed - // detached is ignored since scalar nodes (where the reference resides) cannot be detached - storedRefNode.registerHook(Hook.beforeDestroy, function () { - if (onRefTargetDestroyedHookDisposer) { - onRefTargetDestroyedHookDisposer(); - } - }); - var startWatching = function (sync) { - // re-create hook in case the stored ref gets reattached - if (onRefTargetDestroyedHookDisposer) { - onRefTargetDestroyedHookDisposer(); - } - // make sure the target node is actually there and initialized - var storedRefParentNode = storedRefNode.parent; - var storedRefParentValue = storedRefParentNode && storedRefParentNode.storedValue; - if (storedRefParentNode && storedRefParentNode.isAlive && storedRefParentValue) { - var refTargetNodeExists = void 0; - if (customGetSet) { - refTargetNodeExists = !!customGetSet.get(identifier, storedRefParentValue); - } - else { - refTargetNodeExists = storedRefNode.root.identifierCache.has(_this.targetType, normalizeIdentifier(identifier)); - } - if (!refTargetNodeExists) { - // we cannot change the reference in sync mode - // since we are in the middle of a reconciliation/instantiation and the change would be overwritten - // for those cases just let the wrong reference be assigned and fail upon usage - // (like current references do) - // this means that effectively this code will only run when it is created from a snapshot - if (!sync) { - _this.fireInvalidated("invalidSnapshotReference", storedRefNode, identifier, null); - } - } - else { - onRefTargetDestroyedHookDisposer = _this.addTargetNodeWatcher(storedRefNode, identifier); - } - } - }; - if (storedRefNode.state === NodeLifeCycle.FINALIZED) { - // already attached, so the whole tree is ready - startWatching(true); - } - else { - if (!storedRefNode.isRoot) { - // start watching once the whole tree is ready - storedRefNode.root.registerHook(Hook.afterCreationFinalization, function () { - // make sure to attach it so it can start listening - if (storedRefNode.parent) { - storedRefNode.parent.createObservableInstanceIfNeeded(); - } - }); - } - // start watching once the node is attached somewhere / parent changes - storedRefNode.registerHook(Hook.afterAttach, function () { - startWatching(false); - }); - } - } - }); - return BaseReferenceType; -}(SimpleType)); -/** - * @internal - * @hidden - */ -var IdentifierReferenceType = /** @class */ (function (_super) { - __extends$1(IdentifierReferenceType, _super); - function IdentifierReferenceType(targetType, onInvalidated) { - return _super.call(this, targetType, onInvalidated) || this; - } - Object.defineProperty(IdentifierReferenceType.prototype, "getValue", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode) { - if (!storedRefNode.isAlive) - return undefined; - var storedRef = storedRefNode.storedValue; - return storedRef.resolvedValue; - } - }); - Object.defineProperty(IdentifierReferenceType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode) { - var ref = storedRefNode.storedValue; - return ref.identifier; - } - }); - Object.defineProperty(IdentifierReferenceType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var identifier = isStateTreeNode(initialValue) - ? getIdentifier(initialValue) - : initialValue; - var storedRef = new StoredReference(initialValue, this.targetType); - var storedRefNode = createScalarNode(this, parent, subpath, environment, storedRef); - storedRef.node = storedRefNode; - this.watchTargetNodeForInvalidations(storedRefNode, identifier, undefined); - return storedRefNode; - } - }); - Object.defineProperty(IdentifierReferenceType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - if (!current.isDetaching && current.type === this) { - var compareByValue = isStateTreeNode(newValue); - var ref = current.storedValue; - if ((!compareByValue && ref.identifier === newValue) || - (compareByValue && ref.resolvedValue === newValue)) { - current.setParent(parent, subpath); - return current; - } - } - var newNode = this.instantiate(parent, subpath, undefined, newValue); - current.die(); // noop if detaching - return newNode; - } - }); - return IdentifierReferenceType; -}(BaseReferenceType)); -/** - * @internal - * @hidden - */ -var CustomReferenceType = /** @class */ (function (_super) { - __extends$1(CustomReferenceType, _super); - function CustomReferenceType(targetType, options, onInvalidated) { - var _this = _super.call(this, targetType, onInvalidated) || this; - Object.defineProperty(_this, "options", { - enumerable: true, - configurable: true, - writable: true, - value: options - }); - return _this; - } - Object.defineProperty(CustomReferenceType.prototype, "getValue", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode) { - if (!storedRefNode.isAlive) - return undefined; - var referencedNode = this.options.get(storedRefNode.storedValue, storedRefNode.parent ? storedRefNode.parent.storedValue : null); - return referencedNode; - } - }); - Object.defineProperty(CustomReferenceType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode) { - return storedRefNode.storedValue; - } - }); - Object.defineProperty(CustomReferenceType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, newValue) { - var identifier = isStateTreeNode(newValue) - ? this.options.set(newValue, parent ? parent.storedValue : null) - : newValue; - var storedRefNode = createScalarNode(this, parent, subpath, environment, identifier); - this.watchTargetNodeForInvalidations(storedRefNode, identifier, this.options); - return storedRefNode; - } - }); - Object.defineProperty(CustomReferenceType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - var newIdentifier = isStateTreeNode(newValue) - ? this.options.set(newValue, current ? current.storedValue : null) - : newValue; - if (!current.isDetaching && - current.type === this && - current.storedValue === newIdentifier) { - current.setParent(parent, subpath); - return current; - } - var newNode = this.instantiate(parent, subpath, undefined, newIdentifier); - current.die(); // noop if detaching - return newNode; - } - }); - return CustomReferenceType; -}(BaseReferenceType)); -/** - * `types.reference` - Creates a reference to another type, which should have defined an identifier. - * See also the [reference and identifiers](https://github.com/mobxjs/mobx-state-tree#references-and-identifiers) section. - */ -function reference(subType, options) { - var getSetOptions = options ? options : undefined; - var onInvalidated = options - ? options.onInvalidated - : undefined; - if (getSetOptions && (getSetOptions.get || getSetOptions.set)) { - return new CustomReferenceType(subType, { - get: getSetOptions.get, - set: getSetOptions.set - }, onInvalidated); - } - else { - return new IdentifierReferenceType(subType, onInvalidated); - } -} -/** - * `types.safeReference` - A safe reference is like a standard reference, except that it accepts the undefined value by default - * and automatically sets itself to undefined (when the parent is a model) / removes itself from arrays and maps - * when the reference it is pointing to gets detached/destroyed. - * - * The optional options parameter object accepts a parameter named `acceptsUndefined`, which is set to true by default, so it is suitable - * for model properties. - * When used inside collections (arrays/maps), it is recommended to set this option to false so it can't take undefined as value, - * which is usually the desired in those cases. - * Additionally, the optional options parameter object accepts a parameter named `onInvalidated`, which will be called when the reference target node that the reference is pointing to is about to be detached/destroyed - * - * Strictly speaking it is a `types.maybe(types.reference(X))` (when `acceptsUndefined` is set to true, the default) and - * `types.reference(X)` (when `acceptsUndefined` is set to false), both of them with a customized `onInvalidated` option. - * - * @param subType - * @param options - * @returns - */ -function safeReference(subType, options) { - var refType = reference(subType, __assign(__assign({}, options), { onInvalidated: function (ev) { - if (options && options.onInvalidated) { - options.onInvalidated(ev); - } - ev.removeRef(); - } })); - if (options && options.acceptsUndefined === false) { - return refType; - } - else { - return maybe(refType); - } -} - -var BaseIdentifierType = /** @class */ (function (_super) { - __extends$1(BaseIdentifierType, _super); - function BaseIdentifierType(name, validType) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "validType", { - enumerable: true, - configurable: true, - writable: true, - value: validType - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Identifier - }); - return _this; - } - Object.defineProperty(BaseIdentifierType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - if (!parent || !(parent.type instanceof ModelType)) - throw fail$1("Identifier types can only be instantiated as direct child of a model type"); - return createScalarNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(BaseIdentifierType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - // we don't consider detaching here since identifier are scalar nodes, and scalar nodes cannot be detached - if (current.storedValue !== newValue) - throw fail$1("Tried to change identifier from '" + current.storedValue + "' to '" + newValue + "'. Changing identifiers is not allowed."); - current.setParent(parent, subpath); - return current; - } - }); - Object.defineProperty(BaseIdentifierType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (typeof value !== this.validType) { - return typeCheckFailure(context, value, "Value is not a valid " + this.describe() + ", expected a " + this.validType); - } - return typeCheckSuccess(); - } - }); - return BaseIdentifierType; -}(SimpleType)); -/** - * @internal - * @hidden - */ -var IdentifierType = /** @class */ (function (_super) { - __extends$1(IdentifierType, _super); - function IdentifierType() { - var _this = _super.call(this, "identifier", "string") || this; - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Identifier - }); - return _this; - } - Object.defineProperty(IdentifierType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "identifier"; - } - }); - return IdentifierType; -}(BaseIdentifierType)); -/** - * @internal - * @hidden - */ -var IdentifierNumberType = /** @class */ (function (_super) { - __extends$1(IdentifierNumberType, _super); - function IdentifierNumberType() { - return _super.call(this, "identifierNumber", "number") || this; - } - Object.defineProperty(IdentifierNumberType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return node.storedValue; - } - }); - Object.defineProperty(IdentifierNumberType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "identifierNumber"; - } - }); - return IdentifierNumberType; -}(BaseIdentifierType)); -/** - * `types.identifier` - Identifiers are used to make references, lifecycle events and reconciling works. - * Inside a state tree, for each type can exist only one instance for each given identifier. - * For example there couldn't be 2 instances of user with id 1. If you need more, consider using references. - * Identifier can be used only as type property of a model. - * This type accepts as parameter the value type of the identifier field that can be either string or number. - * - * Example: - * ```ts - * const Todo = types.model("Todo", { - * id: types.identifier, - * title: types.string - * }) - * ``` - * - * @returns - */ -var identifier = new IdentifierType(); -/** - * `types.identifierNumber` - Similar to `types.identifier`. This one will serialize from / to a number when applying snapshots - * - * Example: - * ```ts - * const Todo = types.model("Todo", { - * id: types.identifierNumber, - * title: types.string - * }) - * ``` - * - * @returns - */ -var identifierNumber = new IdentifierNumberType(); -/** - * @internal - * @hidden - */ -function normalizeIdentifier(id) { - return "" + id; -} -/** - * @internal - * @hidden - */ -function isValidIdentifier(id) { - return typeof id === "string" || typeof id === "number"; -} - -/** - * `types.custom` - Creates a custom type. Custom types can be used for arbitrary immutable values, that have a serializable representation. For example, to create your own Date representation, Decimal type etc. - * - * The signature of the options is: - * ```ts - * export interface CustomTypeOptions { - * // Friendly name - * name: string - * // given a serialized value and environment, how to turn it into the target type - * fromSnapshot(snapshot: S, env: any): T - * // return the serialization of the current value - * toSnapshot(value: T): S - * // if true, this is a converted value, if false, it's a snapshot - * isTargetType(value: T | S): value is T - * // a non empty string is assumed to be a validation error - * getValidationMessage?(snapshot: S): string - * } - * ``` - * - * Example: - * ```ts - * const DecimalPrimitive = types.custom({ - * name: "Decimal", - * fromSnapshot(value: string) { - * return new Decimal(value) - * }, - * toSnapshot(value: Decimal) { - * return value.toString() - * }, - * isTargetType(value: string | Decimal): boolean { - * return value instanceof Decimal - * }, - * getValidationMessage(value: string): string { - * if (/^-?\d+\.\d+$/.test(value)) return "" // OK - * return `'${value}' doesn't look like a valid decimal number` - * } - * }) - * - * const Wallet = types.model({ - * balance: DecimalPrimitive - * }) - * ``` - * - * @param options - * @returns - */ -function custom(options) { - return new CustomType(options); -} -/** - * @internal - * @hidden - */ -var CustomType = /** @class */ (function (_super) { - __extends$1(CustomType, _super); - function CustomType(options) { - var _this = _super.call(this, options.name) || this; - Object.defineProperty(_this, "options", { - enumerable: true, - configurable: true, - writable: true, - value: options - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Custom - }); - return _this; - } - Object.defineProperty(CustomType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.name; - } - }); - Object.defineProperty(CustomType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (this.options.isTargetType(value)) - return typeCheckSuccess(); - var typeError = this.options.getValidationMessage(value); - if (typeError) { - return typeCheckFailure(context, value, "Invalid value for type '" + this.name + "': " + typeError); - } - return typeCheckSuccess(); - } - }); - Object.defineProperty(CustomType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return this.options.toSnapshot(node.storedValue); - } - }); - Object.defineProperty(CustomType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var valueToStore = this.options.isTargetType(initialValue) - ? initialValue - : this.options.fromSnapshot(initialValue, parent && parent.root.environment); - return createScalarNode(this, parent, subpath, environment, valueToStore); - } - }); - Object.defineProperty(CustomType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, value, parent, subpath) { - var isSnapshot = !this.options.isTargetType(value); - // in theory customs use scalar nodes which cannot be detached, but still... - if (!current.isDetaching) { - var unchanged = current.type === this && - (isSnapshot ? value === current.snapshot : value === current.storedValue); - if (unchanged) { - current.setParent(parent, subpath); - return current; - } - } - var valueToStore = isSnapshot - ? this.options.fromSnapshot(value, parent.root.environment) - : value; - var newNode = this.instantiate(parent, subpath, undefined, valueToStore); - current.die(); // noop if detaching - return newNode; - } - }); - return CustomType; -}(SimpleType)); - -// we import the types to re-export them inside types. -var types = { - enumeration: enumeration, - model: model, - compose: compose, - custom: custom, - reference: reference, - safeReference: safeReference, - union: union, - optional: optional, - literal: literal, - maybe: maybe, - maybeNull: maybeNull, - refinement: refinement, - string: string, - boolean: boolean, - number: number, - integer: integer, - Date: DatePrimitive, - map: map$1, - array: array, - frozen: frozen, - identifier: identifier, - identifierNumber: identifierNumber, - late: late, - undefined: undefinedType, - null: nullType, - snapshotProcessor: snapshotProcessor -}; - -// Unique ID creation requires a high quality random # generator. In the browser we therefore -// require the crypto API and do not support built-in fallback to lower quality random number -// generators (like Math.random()). -var getRandomValues; -var rnds8 = new Uint8Array(16); -function rng() { - // lazy load so that environments that need to polyfill have a chance to do so - if (!getRandomValues) { - // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, - // find the complete implementation of crypto (msCrypto) on IE11. - getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); - - if (!getRandomValues) { - throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); - } - } - - return getRandomValues(rnds8); -} - -var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; - -function validate(uuid) { - return typeof uuid === 'string' && REGEX.test(uuid); -} - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ - -var byteToHex = []; - -for (var i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); -} - -function stringify(arr) { - var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!validate(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; -} - -function parse(uuid) { - if (!validate(uuid)) { - throw TypeError('Invalid UUID'); - } - - var v; - var arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} - -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - var bytes = []; - - for (var i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - - return bytes; -} - -var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -var URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35 (name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } - - if (typeof namespace === 'string') { - namespace = parse(namespace); - } - - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - - - var bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - - return buf; - } - - return stringify(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL$1; - return generateUUID; -} - -function v4(options, buf, offset) { - options = options || {}; - var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - - return buf; - } - - return stringify(rnds); -} - -// Adapted from Chris Veness' SHA1 code at -// http://www.movable-type.co.uk/scripts/sha1.html -function f(s, x, y, z) { - switch (s) { - case 0: - return x & y ^ ~x & z; - - case 1: - return x ^ y ^ z; - - case 2: - return x & y ^ x & z ^ y & z; - - case 3: - return x ^ y ^ z; - } -} - -function ROTL(x, n) { - return x << n | x >>> 32 - n; -} - -function sha1(bytes) { - var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; - var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; - - if (typeof bytes === 'string') { - var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - - bytes = []; - - for (var i = 0; i < msg.length; ++i) { - bytes.push(msg.charCodeAt(i)); - } - } else if (!Array.isArray(bytes)) { - // Convert Array-like to Array - bytes = Array.prototype.slice.call(bytes); - } - - bytes.push(0x80); - var l = bytes.length / 4 + 2; - var N = Math.ceil(l / 16); - var M = new Array(N); - - for (var _i = 0; _i < N; ++_i) { - var arr = new Uint32Array(16); - - for (var j = 0; j < 16; ++j) { - arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; - } - - M[_i] = arr; - } - - M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); - M[N - 1][14] = Math.floor(M[N - 1][14]); - M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; - - for (var _i2 = 0; _i2 < N; ++_i2) { - var W = new Uint32Array(80); - - for (var t = 0; t < 16; ++t) { - W[t] = M[_i2][t]; - } - - for (var _t = 16; _t < 80; ++_t) { - W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); - } - - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - - for (var _t2 = 0; _t2 < 80; ++_t2) { - var s = Math.floor(_t2 / 20); - var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0; - e = d; - d = c; - c = ROTL(b, 30) >>> 0; - b = a; - a = T; - } - - H[0] = H[0] + a >>> 0; - H[1] = H[1] + b >>> 0; - H[2] = H[2] + c >>> 0; - H[3] = H[3] + d >>> 0; - H[4] = H[4] + e >>> 0; - } - - return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; -} - -var v5 = v35('v5', 0x50, sha1); - -/** - * @license - * Copyright 2021 KonghaYao 江夏尧 - * SPDX-License-Identifier: Apache-2.0 - */ -function createProps({ spiderUUID, originData }) { - // 创建初始化的参数 - return { - uuid: v4(), - spiderUUID, // JSpider 的实例的 UUID - createdAt: new Date(), - errorMessage: '', - status: 'free', // 这个位置是为了让 Plugin 能识别的一个标识 - updatedAt: new Date(), - dataSlideUUID: spiderUUID, - dataSlide: [], - originData, - output: null, // 每个中间件传出的数据 - }; -} - -/** - * @license - * Copyright 2021 KonghaYao 江夏尧 - * SPDX-License-Identifier: Apache-2.0 - */ -const TaskState = types.enumeration('TaskState', ['free', 'pending', 'complete', 'error', 'destroyed']); - -const AutoType = { - anyType: types.custom({ - name: 'any', - fromSnapshot(value) { - return value; - }, - toSnapshot(value) { - return value; - }, - isTargetType() { - return true; - }, - getValidationMessage() { - return ''; - }, - }), -}; - -/** - * @license - * Copyright 2021 KonghaYao 江夏尧 - * SPDX-License-Identifier: Apache-2.0 - */ - -const TaskStore = types - .model({ - uuid: types.string, - spiderUUID: types.string, // JSpider 的实例的 UUID - dataSlide: types.array(types.string), // 更改为存储 UUID - dataSlideUUID: types.string, // 上一次完成的 UUID - createdAt: types.Date, - errorMessage: types.optional(types.string, ''), - status: TaskState, // 这个位置是为了让 Plugin 能识别的一个标识 - updatedAt: types.Date, - // 记录完成过的 uuid 的信息,只有在 StaticEvent.js 中才能更改 - originData: types.maybe(AutoType.anyType), - - // 每个中间件传出的数据 - output: types.maybe(AutoType.anyType), - }) - .actions((self) => { - return { - $backup() { - return getSnapshot(self); - }, - $import(backup) { - return applySnapshot(backup); - }, - - start() { - if (self.status === 'pending') throw new Error('Task 处在 pending 状态'); - self.dataSlide = []; - self.dataSlideUUID = ''; - self.status = 'pending'; - return self.output || self.originData; - }, - success(output, uuid) { - self.status = 'free'; - self.output = output; - this._addUUIDToDataSlide(uuid); - }, - complete(uuid) { - self.status = 'complete'; - this._addUUIDToDataSlide(uuid); - }, - error(err = '', uuid) { - self.status = 'error'; - self.errorMessage = err; - this._addUUIDToDataSlide(uuid); - }, - destroy() { - destroy(self); - }, - _addUUIDToDataSlide(uuid) { - if (uuid) { - self.dataSlide.push(uuid); - self.dataSlideUUID = uuid; - } - }, - }; - }); -function createTaskStore(model) { - return TaskStore.create(createProps(model)); -} - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isFunction$1(x) { - return typeof x === 'function'; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var _enable_super_gross_mode_that_will_cause_bad_things = false; -var config = { - Promise: undefined, - set useDeprecatedSynchronousErrorHandling(value) { - if (value) { - var error = /*@__PURE__*/ new Error(); - /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); - } - _enable_super_gross_mode_that_will_cause_bad_things = value; - }, - get useDeprecatedSynchronousErrorHandling() { - return _enable_super_gross_mode_that_will_cause_bad_things; - }, -}; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function hostReportError(err) { - setTimeout(function () { throw err; }, 0); -} - -/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ -var empty = { - closed: true, - next: function (value) { }, - error: function (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - }, - complete: function () { } -}; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var isArray$1 = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isObject$1(x) { - return x !== null && typeof x === 'object'; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { - function UnsubscriptionErrorImpl(errors) { - Error.call(this); - this.message = errors ? - errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; - this.name = 'UnsubscriptionError'; - this.errors = errors; - return this; - } - UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return UnsubscriptionErrorImpl; -})(); -var UnsubscriptionError = UnsubscriptionErrorImpl; - -/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ -var Subscription = /*@__PURE__*/ (function () { - function Subscription(unsubscribe) { - this.closed = false; - this._parentOrParents = null; - this._subscriptions = null; - if (unsubscribe) { - this._ctorUnsubscribe = true; - this._unsubscribe = unsubscribe; - } - } - Subscription.prototype.unsubscribe = function () { - var errors; - if (this.closed) { - return; - } - var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; - this.closed = true; - this._parentOrParents = null; - this._subscriptions = null; - if (_parentOrParents instanceof Subscription) { - _parentOrParents.remove(this); - } - else if (_parentOrParents !== null) { - for (var index = 0; index < _parentOrParents.length; ++index) { - var parent_1 = _parentOrParents[index]; - parent_1.remove(this); - } - } - if (isFunction$1(_unsubscribe)) { - if (_ctorUnsubscribe) { - this._unsubscribe = undefined; - } - try { - _unsubscribe.call(this); - } - catch (e) { - errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; - } - } - if (isArray$1(_subscriptions)) { - var index = -1; - var len = _subscriptions.length; - while (++index < len) { - var sub = _subscriptions[index]; - if (isObject$1(sub)) { - try { - sub.unsubscribe(); - } - catch (e) { - errors = errors || []; - if (e instanceof UnsubscriptionError) { - errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); - } - else { - errors.push(e); - } - } - } - } - } - if (errors) { - throw new UnsubscriptionError(errors); - } - }; - Subscription.prototype.add = function (teardown) { - var subscription = teardown; - if (!teardown) { - return Subscription.EMPTY; - } - switch (typeof teardown) { - case 'function': - subscription = new Subscription(teardown); - case 'object': - if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { - return subscription; - } - else if (this.closed) { - subscription.unsubscribe(); - return subscription; - } - else if (!(subscription instanceof Subscription)) { - var tmp = subscription; - subscription = new Subscription(); - subscription._subscriptions = [tmp]; - } - break; - default: { - throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); - } - } - var _parentOrParents = subscription._parentOrParents; - if (_parentOrParents === null) { - subscription._parentOrParents = this; - } - else if (_parentOrParents instanceof Subscription) { - if (_parentOrParents === this) { - return subscription; - } - subscription._parentOrParents = [_parentOrParents, this]; - } - else if (_parentOrParents.indexOf(this) === -1) { - _parentOrParents.push(this); - } - else { - return subscription; - } - var subscriptions = this._subscriptions; - if (subscriptions === null) { - this._subscriptions = [subscription]; - } - else { - subscriptions.push(subscription); - } - return subscription; - }; - Subscription.prototype.remove = function (subscription) { - var subscriptions = this._subscriptions; - if (subscriptions) { - var subscriptionIndex = subscriptions.indexOf(subscription); - if (subscriptionIndex !== -1) { - subscriptions.splice(subscriptionIndex, 1); - } - } - }; - Subscription.EMPTY = (function (empty) { - empty.closed = true; - return empty; - }(new Subscription())); - return Subscription; -}()); -function flattenUnsubscriptionErrors(errors) { - return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var rxSubscriber = /*@__PURE__*/ (function () { - return typeof Symbol === 'function' - ? /*@__PURE__*/ Symbol('rxSubscriber') - : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); -})(); - -/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ -var Subscriber = /*@__PURE__*/ (function (_super) { - __extends(Subscriber, _super); - function Subscriber(destinationOrNext, error, complete) { - var _this = _super.call(this) || this; - _this.syncErrorValue = null; - _this.syncErrorThrown = false; - _this.syncErrorThrowable = false; - _this.isStopped = false; - switch (arguments.length) { - case 0: - _this.destination = empty; - break; - case 1: - if (!destinationOrNext) { - _this.destination = empty; - break; - } - if (typeof destinationOrNext === 'object') { - if (destinationOrNext instanceof Subscriber) { - _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; - _this.destination = destinationOrNext; - destinationOrNext.add(_this); - } - else { - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext); - } - break; - } - default: - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); - break; - } - return _this; - } - Subscriber.prototype[rxSubscriber] = function () { return this; }; - Subscriber.create = function (next, error, complete) { - var subscriber = new Subscriber(next, error, complete); - subscriber.syncErrorThrowable = false; - return subscriber; - }; - Subscriber.prototype.next = function (value) { - if (!this.isStopped) { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (!this.isStopped) { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (!this.isStopped) { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - this.destination.error(err); - this.unsubscribe(); - }; - Subscriber.prototype._complete = function () { - this.destination.complete(); - this.unsubscribe(); - }; - Subscriber.prototype._unsubscribeAndRecycle = function () { - var _parentOrParents = this._parentOrParents; - this._parentOrParents = null; - this.unsubscribe(); - this.closed = false; - this.isStopped = false; - this._parentOrParents = _parentOrParents; - return this; - }; - return Subscriber; -}(Subscription)); -var SafeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SafeSubscriber, _super); - function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { - var _this = _super.call(this) || this; - _this._parentSubscriber = _parentSubscriber; - var next; - var context = _this; - if (isFunction$1(observerOrNext)) { - next = observerOrNext; - } - else if (observerOrNext) { - next = observerOrNext.next; - error = observerOrNext.error; - complete = observerOrNext.complete; - if (observerOrNext !== empty) { - context = Object.create(observerOrNext); - if (isFunction$1(context.unsubscribe)) { - _this.add(context.unsubscribe.bind(context)); - } - context.unsubscribe = _this.unsubscribe.bind(_this); - } - } - _this._context = context; - _this._next = next; - _this._error = error; - _this._complete = complete; - return _this; - } - SafeSubscriber.prototype.next = function (value) { - if (!this.isStopped && this._next) { - var _parentSubscriber = this._parentSubscriber; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._next, value); - } - else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; - if (this._error) { - if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._error, err); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, this._error, err); - this.unsubscribe(); - } - } - else if (!_parentSubscriber.syncErrorThrowable) { - this.unsubscribe(); - if (useDeprecatedSynchronousErrorHandling) { - throw err; - } - hostReportError(err); - } - else { - if (useDeprecatedSynchronousErrorHandling) { - _parentSubscriber.syncErrorValue = err; - _parentSubscriber.syncErrorThrown = true; - } - else { - hostReportError(err); - } - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.complete = function () { - var _this = this; - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - if (this._complete) { - var wrappedComplete = function () { return _this._complete.call(_this._context); }; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(wrappedComplete); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, wrappedComplete); - this.unsubscribe(); - } - } - else { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { - try { - fn.call(this._context, value); - } - catch (err) { - this.unsubscribe(); - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - } - }; - SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { - if (!config.useDeprecatedSynchronousErrorHandling) { - throw new Error('bad call'); - } - try { - fn.call(this._context, value); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - parent.syncErrorValue = err; - parent.syncErrorThrown = true; - return true; - } - else { - hostReportError(err); - return true; - } - } - return false; - }; - SafeSubscriber.prototype._unsubscribe = function () { - var _parentSubscriber = this._parentSubscriber; - this._context = null; - this._parentSubscriber = null; - _parentSubscriber.unsubscribe(); - }; - return SafeSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ -function canReportError(observer) { - while (observer) { - var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; - if (closed_1 || isStopped) { - return false; - } - else if (destination && destination instanceof Subscriber) { - observer = destination; - } - else { - observer = null; - } - } - return true; -} - -/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ -function toSubscriber(nextOrObserver, error, complete) { - if (nextOrObserver) { - if (nextOrObserver instanceof Subscriber) { - return nextOrObserver; - } - if (nextOrObserver[rxSubscriber]) { - return nextOrObserver[rxSubscriber](); - } - } - if (!nextOrObserver && !error && !complete) { - return new Subscriber(empty); - } - return new Subscriber(nextOrObserver, error, complete); -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function identity$1(x) { - return x; -} - -/** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ -function pipe() { - var fns = []; - for (var _i = 0; _i < arguments.length; _i++) { - fns[_i] = arguments[_i]; - } - return pipeFromArray(fns); -} -function pipeFromArray(fns) { - if (fns.length === 0) { - return identity$1; - } - if (fns.length === 1) { - return fns[0]; - } - return function piped(input) { - return fns.reduce(function (prev, fn) { return fn(prev); }, input); - }; -} - -/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ -var Observable = /*@__PURE__*/ (function () { - function Observable(subscribe) { - this._isScalar = false; - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; - }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var operator = this.operator; - var sink = toSubscriber(observerOrNext, error, complete); - if (operator) { - sink.add(operator.call(sink, this.source)); - } - else { - sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? - this._subscribe(sink) : - this._trySubscribe(sink)); - } - if (config.useDeprecatedSynchronousErrorHandling) { - if (sink.syncErrorThrowable) { - sink.syncErrorThrowable = false; - if (sink.syncErrorThrown) { - throw sink.syncErrorValue; - } - } - } - return sink; - }; - Observable.prototype._trySubscribe = function (sink) { - try { - return this._subscribe(sink); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - sink.syncErrorThrown = true; - sink.syncErrorValue = err; - } - if (canReportError(sink)) { - sink.error(err); - } - else { - console.warn(err); - } - } - }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscription; - subscription = _this.subscribe(function (value) { - try { - next(value); - } - catch (err) { - reject(err); - if (subscription) { - subscription.unsubscribe(); - } - } - }, reject, resolve); - }); - }; - Observable.prototype._subscribe = function (subscriber) { - var source = this.source; - return source && source.subscribe(subscriber); - }; - Observable.prototype[observable] = function () { - return this; - }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - if (operations.length === 0) { - return this; - } - return pipeFromArray(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); - }; - return Observable; -}()); -function getPromiseCtor(promiseCtor) { - if (!promiseCtor) { - promiseCtor = Promise; - } - if (!promiseCtor) { - throw new Error('no Promise impl found'); - } - return promiseCtor; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { - function ObjectUnsubscribedErrorImpl() { - Error.call(this); - this.message = 'object unsubscribed'; - this.name = 'ObjectUnsubscribedError'; - return this; - } - ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return ObjectUnsubscribedErrorImpl; -})(); -var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; - -/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ -var SubjectSubscription = /*@__PURE__*/ (function (_super) { - __extends(SubjectSubscription, _super); - function SubjectSubscription(subject, subscriber) { - var _this = _super.call(this) || this; - _this.subject = subject; - _this.subscriber = subscriber; - _this.closed = false; - return _this; - } - SubjectSubscription.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.closed = true; - var subject = this.subject; - var observers = subject.observers; - this.subject = null; - if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { - return; - } - var subscriberIndex = observers.indexOf(this.subscriber); - if (subscriberIndex !== -1) { - observers.splice(subscriberIndex, 1); - } - }; - return SubjectSubscription; -}(Subscription)); - -/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ -var SubjectSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SubjectSubscriber, _super); - function SubjectSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - return _this; - } - return SubjectSubscriber; -}(Subscriber)); -var Subject = /*@__PURE__*/ (function (_super) { - __extends(Subject, _super); - function Subject() { - var _this = _super.call(this) || this; - _this.observers = []; - _this.closed = false; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; - } - Subject.prototype[rxSubscriber] = function () { - return new SubjectSubscriber(this); - }; - Subject.prototype.lift = function (operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject.prototype.next = function (value) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - if (!this.isStopped) { - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].next(value); - } - } - }; - Subject.prototype.error = function (err) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.hasError = true; - this.thrownError = err; - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].error(err); - } - this.observers.length = 0; - }; - Subject.prototype.complete = function () { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].complete(); - } - this.observers.length = 0; - }; - Subject.prototype.unsubscribe = function () { - this.isStopped = true; - this.closed = true; - this.observers = null; - }; - Subject.prototype._trySubscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else { - return _super.prototype._trySubscribe.call(this, subscriber); - } - }; - Subject.prototype._subscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else if (this.hasError) { - subscriber.error(this.thrownError); - return Subscription.EMPTY; - } - else if (this.isStopped) { - subscriber.complete(); - return Subscription.EMPTY; - } - else { - this.observers.push(subscriber); - return new SubjectSubscription(this, subscriber); - } - }; - Subject.prototype.asObservable = function () { - var observable = new Observable(); - observable.source = this; - return observable; - }; - Subject.create = function (destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject; -}(Observable)); -var AnonymousSubject = /*@__PURE__*/ (function (_super) { - __extends(AnonymousSubject, _super); - function AnonymousSubject(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; - } - AnonymousSubject.prototype.next = function (value) { - var destination = this.destination; - if (destination && destination.next) { - destination.next(value); - } - }; - AnonymousSubject.prototype.error = function (err) { - var destination = this.destination; - if (destination && destination.error) { - this.destination.error(err); - } - }; - AnonymousSubject.prototype.complete = function () { - var destination = this.destination; - if (destination && destination.complete) { - this.destination.complete(); - } - }; - AnonymousSubject.prototype._subscribe = function (subscriber) { - var source = this.source; - if (source) { - return this.source.subscribe(subscriber); - } - else { - return Subscription.EMPTY; - } - }; - return AnonymousSubject; -}(Subject)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function refCount() { - return function refCountOperatorFunction(source) { - return source.lift(new RefCountOperator(source)); - }; -} -var RefCountOperator = /*@__PURE__*/ (function () { - function RefCountOperator(connectable) { - this.connectable = connectable; - } - RefCountOperator.prototype.call = function (subscriber, source) { - var connectable = this.connectable; - connectable._refCount++; - var refCounter = new RefCountSubscriber(subscriber, connectable); - var subscription = source.subscribe(refCounter); - if (!refCounter.closed) { - refCounter.connection = connectable.connect(); - } - return subscription; - }; - return RefCountOperator; -}()); -var RefCountSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RefCountSubscriber, _super); - function RefCountSubscriber(destination, connectable) { - var _this = _super.call(this, destination) || this; - _this.connectable = connectable; - return _this; - } - RefCountSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (!connectable) { - this.connection = null; - return; - } - this.connectable = null; - var refCount = connectable._refCount; - if (refCount <= 0) { - this.connection = null; - return; - } - connectable._refCount = refCount - 1; - if (refCount > 1) { - this.connection = null; - return; - } - var connection = this.connection; - var sharedConnection = connectable._connection; - this.connection = null; - if (sharedConnection && (!connection || sharedConnection === connection)) { - sharedConnection.unsubscribe(); - } - }; - return RefCountSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */ -var ConnectableObservable = /*@__PURE__*/ (function (_super) { - __extends(ConnectableObservable, _super); - function ConnectableObservable(source, subjectFactory) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subjectFactory = subjectFactory; - _this._refCount = 0; - _this._isComplete = false; - return _this; - } - ConnectableObservable.prototype._subscribe = function (subscriber) { - return this.getSubject().subscribe(subscriber); - }; - ConnectableObservable.prototype.getSubject = function () { - var subject = this._subject; - if (!subject || subject.isStopped) { - this._subject = this.subjectFactory(); - } - return this._subject; - }; - ConnectableObservable.prototype.connect = function () { - var connection = this._connection; - if (!connection) { - this._isComplete = false; - connection = this._connection = new Subscription(); - connection.add(this.source - .subscribe(new ConnectableSubscriber(this.getSubject(), this))); - if (connection.closed) { - this._connection = null; - connection = Subscription.EMPTY; - } - } - return connection; - }; - ConnectableObservable.prototype.refCount = function () { - return refCount()(this); - }; - return ConnectableObservable; -}(Observable)); -var connectableObservableDescriptor = /*@__PURE__*/ (function () { - var connectableProto = ConnectableObservable.prototype; - return { - operator: { value: null }, - _refCount: { value: 0, writable: true }, - _subject: { value: null, writable: true }, - _connection: { value: null, writable: true }, - _subscribe: { value: connectableProto._subscribe }, - _isComplete: { value: connectableProto._isComplete, writable: true }, - getSubject: { value: connectableProto.getSubject }, - connect: { value: connectableProto.connect }, - refCount: { value: connectableProto.refCount } - }; -})(); -var ConnectableSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ConnectableSubscriber, _super); - function ConnectableSubscriber(destination, connectable) { - var _this = _super.call(this, destination) || this; - _this.connectable = connectable; - return _this; - } - ConnectableSubscriber.prototype._error = function (err) { - this._unsubscribe(); - _super.prototype._error.call(this, err); - }; - ConnectableSubscriber.prototype._complete = function () { - this.connectable._isComplete = true; - this._unsubscribe(); - _super.prototype._complete.call(this); - }; - ConnectableSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (connectable) { - this.connectable = null; - var connection = connectable._connection; - connectable._refCount = 0; - connectable._subject = null; - connectable._connection = null; - if (connection) { - connection.unsubscribe(); - } - } - }; - return ConnectableSubscriber; -}(SubjectSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ -var Action = /*@__PURE__*/ (function (_super) { - __extends(Action, _super); - function Action(scheduler, work) { - return _super.call(this) || this; - } - Action.prototype.schedule = function (state, delay) { - return this; - }; - return Action; -}(Subscription)); - -/** PURE_IMPORTS_START tslib,_Action PURE_IMPORTS_END */ -var AsyncAction = /*@__PURE__*/ (function (_super) { - __extends(AsyncAction, _super); - function AsyncAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.pending = false; - return _this; - } - AsyncAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - if (this.closed) { - return this; - } - this.state = state; - var id = this.id; - var scheduler = this.scheduler; - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay); - } - this.pending = true; - this.delay = delay; - this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); - return this; - }; - AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - return setInterval(scheduler.flush.bind(scheduler, this), delay); - }; - AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay !== null && this.delay === delay && this.pending === false) { - return id; - } - clearInterval(id); - return undefined; - }; - AsyncAction.prototype.execute = function (state, delay) { - if (this.closed) { - return new Error('executing a cancelled action'); - } - this.pending = false; - var error = this._execute(state, delay); - if (error) { - return error; - } - else if (this.pending === false && this.id != null) { - this.id = this.recycleAsyncId(this.scheduler, this.id, null); - } - }; - AsyncAction.prototype._execute = function (state, delay) { - var errored = false; - var errorValue = undefined; - try { - this.work(state); - } - catch (e) { - errored = true; - errorValue = !!e && e || new Error(e); - } - if (errored) { - this.unsubscribe(); - return errorValue; - } - }; - AsyncAction.prototype._unsubscribe = function () { - var id = this.id; - var scheduler = this.scheduler; - var actions = scheduler.actions; - var index = actions.indexOf(this); - this.work = null; - this.state = null; - this.pending = false; - this.scheduler = null; - if (index !== -1) { - actions.splice(index, 1); - } - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); - } - this.delay = null; - }; - return AsyncAction; -}(Action)); - -var Scheduler = /*@__PURE__*/ (function () { - function Scheduler(SchedulerAction, now) { - if (now === void 0) { - now = Scheduler.now; - } - this.SchedulerAction = SchedulerAction; - this.now = now; - } - Scheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { - delay = 0; - } - return new this.SchedulerAction(this, work).schedule(state, delay); - }; - Scheduler.now = function () { return Date.now(); }; - return Scheduler; -}()); - -/** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */ -var AsyncScheduler = /*@__PURE__*/ (function (_super) { - __extends(AsyncScheduler, _super); - function AsyncScheduler(SchedulerAction, now) { - if (now === void 0) { - now = Scheduler.now; - } - var _this = _super.call(this, SchedulerAction, function () { - if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) { - return AsyncScheduler.delegate.now(); - } - else { - return now(); - } - }) || this; - _this.actions = []; - _this.active = false; - _this.scheduled = undefined; - return _this; - } - AsyncScheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { - delay = 0; - } - if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) { - return AsyncScheduler.delegate.schedule(work, delay, state); - } - else { - return _super.prototype.schedule.call(this, work, delay, state); - } - }; - AsyncScheduler.prototype.flush = function (action) { - var actions = this.actions; - if (this.active) { - actions.push(action); - return; - } - var error; - this.active = true; - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (action = actions.shift()); - this.active = false; - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - return AsyncScheduler; -}(Scheduler)); - -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -var EMPTY = /*@__PURE__*/ new Observable(function (subscriber) { return subscriber.complete(); }); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isScheduler(value) { - return value && typeof value.schedule === 'function'; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var subscribeToArray = function (array) { - return function (subscriber) { - for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { - subscriber.next(array[i]); - } - subscriber.complete(); - }; -}; - -/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ -function scheduleArray(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - var i = 0; - sub.add(scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - return; - } - subscriber.next(input[i++]); - if (!subscriber.closed) { - sub.add(this.schedule()); - } - })); - return sub; - }); -} - -/** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */ -function fromArray(input, scheduler) { - if (!scheduler) { - return new Observable(subscribeToArray(input)); - } - else { - return scheduleArray(input, scheduler); - } -} - -/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */ -function of() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = args[args.length - 1]; - if (isScheduler(scheduler)) { - args.pop(); - return scheduleArray(args, scheduler); - } - else { - return fromArray(args); - } -} - -/** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ -var asyncScheduler = /*@__PURE__*/ new AsyncScheduler(AsyncAction); -var async = asyncScheduler; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function noop() { } - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function map(project, thisArg) { - return function mapOperation(source) { - if (typeof project !== 'function') { - throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); - } - return source.lift(new MapOperator(project, thisArg)); - }; -} -var MapOperator = /*@__PURE__*/ (function () { - function MapOperator(project, thisArg) { - this.project = project; - this.thisArg = thisArg; - } - MapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); - }; - return MapOperator; -}()); -var MapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MapSubscriber, _super); - function MapSubscriber(destination, project, thisArg) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.count = 0; - _this.thisArg = thisArg || _this; - return _this; - } - MapSubscriber.prototype._next = function (value) { - var result; - try { - result = this.project.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return MapSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -var OuterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(OuterSubscriber, _super); - function OuterSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); - }; - OuterSubscriber.prototype.notifyError = function (error, innerSub) { - this.destination.error(error); - }; - OuterSubscriber.prototype.notifyComplete = function (innerSub) { - this.destination.complete(); - }; - return OuterSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -var InnerSubscriber = /*@__PURE__*/ (function (_super) { - __extends(InnerSubscriber, _super); - function InnerSubscriber(parent, outerValue, outerIndex) { - var _this = _super.call(this) || this; - _this.parent = parent; - _this.outerValue = outerValue; - _this.outerIndex = outerIndex; - _this.index = 0; - return _this; - } - InnerSubscriber.prototype._next = function (value) { - this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this); - }; - InnerSubscriber.prototype._error = function (error) { - this.parent.notifyError(error, this); - this.unsubscribe(); - }; - InnerSubscriber.prototype._complete = function () { - this.parent.notifyComplete(this); - this.unsubscribe(); - }; - return InnerSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ -var subscribeToPromise = function (promise) { - return function (subscriber) { - promise.then(function (value) { - if (!subscriber.closed) { - subscriber.next(value); - subscriber.complete(); - } - }, function (err) { return subscriber.error(err); }) - .then(null, hostReportError); - return subscriber; - }; -}; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function getSymbolIterator() { - if (typeof Symbol !== 'function' || !Symbol.iterator) { - return '@@iterator'; - } - return Symbol.iterator; -} -var iterator = /*@__PURE__*/ getSymbolIterator(); - -/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ -var subscribeToIterable = function (iterable) { - return function (subscriber) { - var iterator$1 = iterable[iterator](); - do { - var item = void 0; - try { - item = iterator$1.next(); - } - catch (err) { - subscriber.error(err); - return subscriber; - } - if (item.done) { - subscriber.complete(); - break; - } - subscriber.next(item.value); - if (subscriber.closed) { - break; - } - } while (true); - if (typeof iterator$1.return === 'function') { - subscriber.add(function () { - if (iterator$1.return) { - iterator$1.return(); - } - }); - } - return subscriber; - }; -}; - -/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ -var subscribeToObservable = function (obj) { - return function (subscriber) { - var obs = obj[observable](); - if (typeof obs.subscribe !== 'function') { - throw new TypeError('Provided object does not correctly implement Symbol.observable'); - } - else { - return obs.subscribe(subscriber); - } - }; -}; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var isArrayLike$1 = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isPromise(value) { - return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; -} - -/** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ -var subscribeTo = function (result) { - if (!!result && typeof result[observable] === 'function') { - return subscribeToObservable(result); - } - else if (isArrayLike$1(result)) { - return subscribeToArray(result); - } - else if (isPromise(result)) { - return subscribeToPromise(result); - } - else if (!!result && typeof result[iterator] === 'function') { - return subscribeToIterable(result); - } - else { - var value = isObject$1(result) ? 'an invalid object' : "'" + result + "'"; - var msg = "You provided " + value + " where a stream was expected." - + ' You can provide an Observable, Promise, Array, or Iterable.'; - throw new TypeError(msg); - } -}; - -/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */ -function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber) { - if (innerSubscriber === void 0) { - innerSubscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex); - } - if (innerSubscriber.closed) { - return undefined; - } - if (result instanceof Observable) { - return result.subscribe(innerSubscriber); - } - return subscribeTo(result)(innerSubscriber); -} - -/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ -function scheduleObservable(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - var observable$1 = input[observable](); - sub.add(observable$1.subscribe({ - next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, - error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, - complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, - })); - })); - return sub; - }); -} - -/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ -function schedulePromise(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - return input.then(function (value) { - sub.add(scheduler.schedule(function () { - subscriber.next(value); - sub.add(scheduler.schedule(function () { return subscriber.complete(); })); - })); - }, function (err) { - sub.add(scheduler.schedule(function () { return subscriber.error(err); })); - }); - })); - return sub; - }); -} - -/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ -function scheduleIterable(input, scheduler) { - if (!input) { - throw new Error('Iterable cannot be null'); - } - return new Observable(function (subscriber) { - var sub = new Subscription(); - var iterator$1; - sub.add(function () { - if (iterator$1 && typeof iterator$1.return === 'function') { - iterator$1.return(); - } - }); - sub.add(scheduler.schedule(function () { - iterator$1 = input[iterator](); - sub.add(scheduler.schedule(function () { - if (subscriber.closed) { - return; - } - var value; - var done; - try { - var result = iterator$1.next(); - value = result.value; - done = result.done; - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - this.schedule(); - } - })); - })); - return sub; - }); -} - -/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ -function isInteropObservable(input) { - return input && typeof input[observable] === 'function'; -} - -/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ -function isIterable(input) { - return input && typeof input[iterator] === 'function'; -} - -/** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ -function scheduled(input, scheduler) { - if (input != null) { - if (isInteropObservable(input)) { - return scheduleObservable(input, scheduler); - } - else if (isPromise(input)) { - return schedulePromise(input, scheduler); - } - else if (isArrayLike$1(input)) { - return scheduleArray(input, scheduler); - } - else if (isIterable(input) || typeof input === 'string') { - return scheduleIterable(input, scheduler); - } - } - throw new TypeError((input !== null && typeof input || input) + ' is not observable'); -} - -/** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ -function from$1(input, scheduler) { - if (!scheduler) { - if (input instanceof Observable) { - return input; - } - return new Observable(subscribeTo(input)); - } - else { - return scheduled(input, scheduler); - } -} - -/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_util_subscribeTo PURE_IMPORTS_END */ -var SimpleInnerSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SimpleInnerSubscriber, _super); - function SimpleInnerSubscriber(parent) { - var _this = _super.call(this) || this; - _this.parent = parent; - return _this; - } - SimpleInnerSubscriber.prototype._next = function (value) { - this.parent.notifyNext(value); - }; - SimpleInnerSubscriber.prototype._error = function (error) { - this.parent.notifyError(error); - this.unsubscribe(); - }; - SimpleInnerSubscriber.prototype._complete = function () { - this.parent.notifyComplete(); - this.unsubscribe(); - }; - return SimpleInnerSubscriber; -}(Subscriber)); -var SimpleOuterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SimpleOuterSubscriber, _super); - function SimpleOuterSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - SimpleOuterSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - SimpleOuterSubscriber.prototype.notifyError = function (err) { - this.destination.error(err); - }; - SimpleOuterSubscriber.prototype.notifyComplete = function () { - this.destination.complete(); - }; - return SimpleOuterSubscriber; -}(Subscriber)); -function innerSubscribe(result, innerSubscriber) { - if (innerSubscriber.closed) { - return undefined; - } - if (result instanceof Observable) { - return result.subscribe(innerSubscriber); - } - return subscribeTo(result)(innerSubscriber); -} - -/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ -function mergeMap(project, resultSelector, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(mergeMap(function (a, i) { return from$1(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); }; - } - else if (typeof resultSelector === 'number') { - concurrent = resultSelector; - } - return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); }; -} -var MergeMapOperator = /*@__PURE__*/ (function () { - function MergeMapOperator(project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - this.project = project; - this.concurrent = concurrent; - } - MergeMapOperator.prototype.call = function (observer, source) { - return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent)); - }; - return MergeMapOperator; -}()); -var MergeMapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MergeMapSubscriber, _super); - function MergeMapSubscriber(destination, project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.concurrent = concurrent; - _this.hasCompleted = false; - _this.buffer = []; - _this.active = 0; - _this.index = 0; - return _this; - } - MergeMapSubscriber.prototype._next = function (value) { - if (this.active < this.concurrent) { - this._tryNext(value); - } - else { - this.buffer.push(value); - } - }; - MergeMapSubscriber.prototype._tryNext = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this.active++; - this._innerSub(result); - }; - MergeMapSubscriber.prototype._innerSub = function (ish) { - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - var innerSubscription = innerSubscribe(ish, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - destination.add(innerSubscription); - } - }; - MergeMapSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - this.destination.complete(); - } - this.unsubscribe(); - }; - MergeMapSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - MergeMapSubscriber.prototype.notifyComplete = function () { - var buffer = this.buffer; - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); - } - else if (this.active === 0 && this.hasCompleted) { - this.destination.complete(); - } - }; - return MergeMapSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ -function fromEventPattern(addHandler, removeHandler, resultSelector) { - if (resultSelector) { - return fromEventPattern(addHandler, removeHandler).pipe(map(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - } - return new Observable(function (subscriber) { - var handler = function () { - var e = []; - for (var _i = 0; _i < arguments.length; _i++) { - e[_i] = arguments[_i]; - } - return subscriber.next(e.length === 1 ? e[0] : e); - }; - var retValue; - try { - retValue = addHandler(handler); - } - catch (err) { - subscriber.error(err); - return undefined; - } - if (!isFunction$1(removeHandler)) { - return undefined; - } - return function () { return removeHandler(handler, retValue); }; - }); -} - -/** PURE_IMPORTS_START _isArray PURE_IMPORTS_END */ -function isNumeric(val) { - return !isArray$1(val) && (val - parseFloat(val) + 1) >= 0; -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function filter(predicate, thisArg) { - return function filterOperatorFunction(source) { - return source.lift(new FilterOperator(predicate, thisArg)); - }; -} -var FilterOperator = /*@__PURE__*/ (function () { - function FilterOperator(predicate, thisArg) { - this.predicate = predicate; - this.thisArg = thisArg; - } - FilterOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); - }; - return FilterOperator; -}()); -var FilterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(FilterSubscriber, _super); - function FilterSubscriber(destination, predicate, thisArg) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.thisArg = thisArg; - _this.count = 0; - return _this; - } - FilterSubscriber.prototype._next = function (value) { - var result; - try { - result = this.predicate.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - this.destination.next(value); - } - }; - return FilterSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ -function timer(dueTime, periodOrScheduler, scheduler) { - if (dueTime === void 0) { - dueTime = 0; - } - var period = -1; - if (isNumeric(periodOrScheduler)) { - period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler); - } - else if (isScheduler(periodOrScheduler)) { - scheduler = periodOrScheduler; - } - if (!isScheduler(scheduler)) { - scheduler = async; - } - return new Observable(function (subscriber) { - var due = isNumeric(dueTime) - ? dueTime - : (+dueTime - scheduler.now()); - return scheduler.schedule(dispatch, due, { - index: 0, period: period, subscriber: subscriber - }); - }); -} -function dispatch(state) { - var index = state.index, period = state.period, subscriber = state.subscriber; - subscriber.next(index); - if (subscriber.closed) { - return; - } - else if (period === -1) { - return subscriber.complete(); - } - state.index = index + 1; - this.schedule(state, period); -} - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** Built-in value references. */ -var Symbol$1 = root.Symbol; - -/** Used for built-in method references. */ -var objectProto$6 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$5 = objectProto$6.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$6.toString; - -/** Built-in value references. */ -var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; - -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty$5.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; - - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString$1.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto$5.toString; - -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString.call(value); -} - -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} - -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** Used as references for various `Number` constants. */ -var INFINITY$1 = 1 / 0; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; -} - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -/** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ -function identity(value) { - return value; -} - -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} - -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; - -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); - -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} - -/** Used for built-in method references. */ -var funcProto$1 = Function.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString$1 = funcProto$1.toString; - -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString$1.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; -} - -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; - -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto$4 = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty$4 = objectProto$4.hasOwnProperty; - -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty$4).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); - -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); -} - -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} - -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; -} - -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} - -/** Used to detect hot functions by number of calls within a span of milliseconds. */ -var HOT_COUNT = 800, - HOT_SPAN = 16; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeNow = Date.now; - -/** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ -function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; -} - -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ -function constant(value) { - return function() { - return value; - }; -} - -var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} -}()); - -/** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); -}; - -/** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var setToString = shortOut(baseSetToString); - -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} - -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); -} - -/** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; -} - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$1 : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } -} - -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} - -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$3.hasOwnProperty; - -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$3.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ -function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; -} - -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); -} - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; - -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; -} - -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$2.hasOwnProperty; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$2.propertyIsEnumerable; - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; - -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} - -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; - -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports && freeGlobal.process; - -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); - -/** Used to match property names within property paths. */ -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - -/** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ -function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); -} - -/* Built-in method references that are verified to be native. */ -var nativeCreate = getNative(Object, 'create'); - -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; -} - -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; -} - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$1.hasOwnProperty; - -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED$2 ? undefined : result; - } - return hasOwnProperty$1.call(data, key) ? data[key] : undefined; -} - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); -} - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; -} - -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; - this.size = 0; -} - -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; -} - -/** Used for built-in method references. */ -var arrayProto = Array.prototype; - -/** Built-in value references. */ -var splice = arrayProto.splice; - -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; -} - -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; -} - -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} - -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} - -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; - -/* Built-in method references that are verified to be native. */ -var Map$1 = getNative(root, 'Map'); - -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; -} - -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} - -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} - -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; -} - -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); -} - -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); -} - -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; -} - -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; - -/** Error message constants. */ -var FUNC_ERROR_TEXT = 'Expected a function'; - -/** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ -function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; -} - -// Expose `MapCache`. -memoize.Cache = MapCache; - -/** Used as the maximum memoize cache size. */ -var MAX_MEMOIZE_SIZE = 500; - -/** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ -function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; -} - -/** Used to match property names within property paths. */ -var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - -/** Used to match backslashes in property paths. */ -var reEscapeChar = /\\(\\)?/g; - -/** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ -var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; -}); - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} - -/** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ -function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); -} - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ -function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -/** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ -function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; -} - -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} - -/** Built-in value references. */ -var spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : undefined; - -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); -} - -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; -} - -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ -function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; -} - -/** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ -function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); -} - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; - -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; -} - -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); -} - -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } -} - -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; - -/** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); -} - -/** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ -function baseHasIn(object, key) { - return object != null && key in Object(object); -} - -/** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ -function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); -} - -/** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ -function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); -} - -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} - -/** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; -} - -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; - -/** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ -function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; -} - -/** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ -var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; -}); - -/** `Object#toString` result references. */ -var stringTag = '[object String]'; - -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); -} - -/** `Object#toString` result references. */ -var regexpTag = '[object RegExp]'; - -/** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ -function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; -} - -/* Node.js helper references. */ -var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; - -/** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ -var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - -/** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ -function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; -} - -/** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ -function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; -} - -/** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ -function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); -} - /** - * Creates an object composed of the picked `object` properties. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ -var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); -}); - -/** PURE_IMPORTS_START tslib,_scheduler_async,_Subscriber,_util_isScheduler PURE_IMPORTS_END */ -function bufferTime(bufferTimeSpan) { - var length = arguments.length; - var scheduler = async; - if (isScheduler(arguments[arguments.length - 1])) { - scheduler = arguments[arguments.length - 1]; - length--; - } - var bufferCreationInterval = null; - if (length >= 2) { - bufferCreationInterval = arguments[1]; - } - var maxBufferSize = Number.POSITIVE_INFINITY; - if (length >= 3) { - maxBufferSize = arguments[2]; - } - return function bufferTimeOperatorFunction(source) { - return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler)); - }; -} -var BufferTimeOperator = /*@__PURE__*/ (function () { - function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { - this.bufferTimeSpan = bufferTimeSpan; - this.bufferCreationInterval = bufferCreationInterval; - this.maxBufferSize = maxBufferSize; - this.scheduler = scheduler; - } - BufferTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler)); - }; - return BufferTimeOperator; -}()); -var Context = /*@__PURE__*/ (function () { - function Context() { - this.buffer = []; - } - return Context; -}()); -var BufferTimeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(BufferTimeSubscriber, _super); - function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { - var _this = _super.call(this, destination) || this; - _this.bufferTimeSpan = bufferTimeSpan; - _this.bufferCreationInterval = bufferCreationInterval; - _this.maxBufferSize = maxBufferSize; - _this.scheduler = scheduler; - _this.contexts = []; - var context = _this.openContext(); - _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0; - if (_this.timespanOnly) { - var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan }; - _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); - } - else { - var closeState = { subscriber: _this, context: context }; - var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler }; - _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState)); - _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState)); - } - return _this; - } - BufferTimeSubscriber.prototype._next = function (value) { - var contexts = this.contexts; - var len = contexts.length; - var filledBufferContext; - for (var i = 0; i < len; i++) { - var context_1 = contexts[i]; - var buffer = context_1.buffer; - buffer.push(value); - if (buffer.length == this.maxBufferSize) { - filledBufferContext = context_1; - } - } - if (filledBufferContext) { - this.onBufferFull(filledBufferContext); - } - }; - BufferTimeSubscriber.prototype._error = function (err) { - this.contexts.length = 0; - _super.prototype._error.call(this, err); - }; - BufferTimeSubscriber.prototype._complete = function () { - var _a = this, contexts = _a.contexts, destination = _a.destination; - while (contexts.length > 0) { - var context_2 = contexts.shift(); - destination.next(context_2.buffer); - } - _super.prototype._complete.call(this); - }; - BufferTimeSubscriber.prototype._unsubscribe = function () { - this.contexts = null; - }; - BufferTimeSubscriber.prototype.onBufferFull = function (context) { - this.closeContext(context); - var closeAction = context.closeAction; - closeAction.unsubscribe(); - this.remove(closeAction); - if (!this.closed && this.timespanOnly) { - context = this.openContext(); - var bufferTimeSpan = this.bufferTimeSpan; - var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan }; - this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); - } - }; - BufferTimeSubscriber.prototype.openContext = function () { - var context = new Context(); - this.contexts.push(context); - return context; - }; - BufferTimeSubscriber.prototype.closeContext = function (context) { - this.destination.next(context.buffer); - var contexts = this.contexts; - var spliceIndex = contexts ? contexts.indexOf(context) : -1; - if (spliceIndex >= 0) { - contexts.splice(contexts.indexOf(context), 1); - } - }; - return BufferTimeSubscriber; -}(Subscriber)); -function dispatchBufferTimeSpanOnly(state) { - var subscriber = state.subscriber; - var prevContext = state.context; - if (prevContext) { - subscriber.closeContext(prevContext); - } - if (!subscriber.closed) { - state.context = subscriber.openContext(); - state.context.closeAction = this.schedule(state, state.bufferTimeSpan); - } -} -function dispatchBufferCreation(state) { - var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler; - var context = subscriber.openContext(); - var action = this; - if (!subscriber.closed) { - subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context })); - action.schedule(state, bufferCreationInterval); - } -} -function dispatchBufferClose(arg) { - var subscriber = arg.subscriber, context = arg.context; - subscriber.closeContext(context); -} - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function catchError(selector) { - return function catchErrorOperatorFunction(source) { - var operator = new CatchOperator(selector); - var caught = source.lift(operator); - return (operator.caught = caught); - }; -} -var CatchOperator = /*@__PURE__*/ (function () { - function CatchOperator(selector) { - this.selector = selector; - } - CatchOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught)); - }; - return CatchOperator; -}()); -var CatchSubscriber = /*@__PURE__*/ (function (_super) { - __extends(CatchSubscriber, _super); - function CatchSubscriber(destination, selector, caught) { - var _this = _super.call(this, destination) || this; - _this.selector = selector; - _this.caught = caught; - return _this; - } - CatchSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var result = void 0; - try { - result = this.selector(err, this.caught); - } - catch (err2) { - _super.prototype.error.call(this, err2); - return; - } - this._unsubscribeAndRecycle(); - var innerSubscriber = new SimpleInnerSubscriber(this); - this.add(innerSubscriber); - var innerSubscription = innerSubscribe(result, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - this.add(innerSubscription); - } - } - }; - return CatchSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ -function concatMap(project, resultSelector) { - return mergeMap(project, resultSelector, 1); -} - -/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function delayWhen(delayDurationSelector, subscriptionDelay) { - if (subscriptionDelay) { - return function (source) { - return new SubscriptionDelayObservable(source, subscriptionDelay) - .lift(new DelayWhenOperator(delayDurationSelector)); - }; - } - return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); }; -} -var DelayWhenOperator = /*@__PURE__*/ (function () { - function DelayWhenOperator(delayDurationSelector) { - this.delayDurationSelector = delayDurationSelector; - } - DelayWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector)); - }; - return DelayWhenOperator; -}()); -var DelayWhenSubscriber = /*@__PURE__*/ (function (_super) { - __extends(DelayWhenSubscriber, _super); - function DelayWhenSubscriber(destination, delayDurationSelector) { - var _this = _super.call(this, destination) || this; - _this.delayDurationSelector = delayDurationSelector; - _this.completed = false; - _this.delayNotifierSubscriptions = []; - _this.index = 0; - return _this; - } - DelayWhenSubscriber.prototype.notifyNext = function (outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) { - this.destination.next(outerValue); - this.removeSubscription(innerSub); - this.tryComplete(); - }; - DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) { - this._error(error); - }; - DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) { - var value = this.removeSubscription(innerSub); - if (value) { - this.destination.next(value); - } - this.tryComplete(); - }; - DelayWhenSubscriber.prototype._next = function (value) { - var index = this.index++; - try { - var delayNotifier = this.delayDurationSelector(value, index); - if (delayNotifier) { - this.tryDelay(delayNotifier, value); - } - } - catch (err) { - this.destination.error(err); - } - }; - DelayWhenSubscriber.prototype._complete = function () { - this.completed = true; - this.tryComplete(); - this.unsubscribe(); - }; - DelayWhenSubscriber.prototype.removeSubscription = function (subscription) { - subscription.unsubscribe(); - var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription); - if (subscriptionIdx !== -1) { - this.delayNotifierSubscriptions.splice(subscriptionIdx, 1); - } - return subscription.outerValue; - }; - DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) { - var notifierSubscription = subscribeToResult(this, delayNotifier, value); - if (notifierSubscription && !notifierSubscription.closed) { - var destination = this.destination; - destination.add(notifierSubscription); - this.delayNotifierSubscriptions.push(notifierSubscription); - } - }; - DelayWhenSubscriber.prototype.tryComplete = function () { - if (this.completed && this.delayNotifierSubscriptions.length === 0) { - this.destination.complete(); - } - }; - return DelayWhenSubscriber; -}(OuterSubscriber)); -var SubscriptionDelayObservable = /*@__PURE__*/ (function (_super) { - __extends(SubscriptionDelayObservable, _super); - function SubscriptionDelayObservable(source, subscriptionDelay) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subscriptionDelay = subscriptionDelay; - return _this; - } - SubscriptionDelayObservable.prototype._subscribe = function (subscriber) { - this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source)); - }; - return SubscriptionDelayObservable; -}(Observable)); -var SubscriptionDelaySubscriber = /*@__PURE__*/ (function (_super) { - __extends(SubscriptionDelaySubscriber, _super); - function SubscriptionDelaySubscriber(parent, source) { - var _this = _super.call(this) || this; - _this.parent = parent; - _this.source = source; - _this.sourceSubscribed = false; - return _this; - } - SubscriptionDelaySubscriber.prototype._next = function (unused) { - this.subscribeToSource(); - }; - SubscriptionDelaySubscriber.prototype._error = function (err) { - this.unsubscribe(); - this.parent.error(err); - }; - SubscriptionDelaySubscriber.prototype._complete = function () { - this.unsubscribe(); - this.subscribeToSource(); - }; - SubscriptionDelaySubscriber.prototype.subscribeToSource = function () { - if (!this.sourceSubscribed) { - this.sourceSubscribed = true; - this.unsubscribe(); - this.source.subscribe(this.parent); - } - }; - return SubscriptionDelaySubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function scan(accumulator, seed) { - var hasSeed = false; - if (arguments.length >= 2) { - hasSeed = true; - } - return function scanOperatorFunction(source) { - return source.lift(new ScanOperator(accumulator, seed, hasSeed)); - }; -} -var ScanOperator = /*@__PURE__*/ (function () { - function ScanOperator(accumulator, seed, hasSeed) { - if (hasSeed === void 0) { - hasSeed = false; - } - this.accumulator = accumulator; - this.seed = seed; - this.hasSeed = hasSeed; - } - ScanOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); - }; - return ScanOperator; -}()); -var ScanSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ScanSubscriber, _super); - function ScanSubscriber(destination, accumulator, _seed, hasSeed) { - var _this = _super.call(this, destination) || this; - _this.accumulator = accumulator; - _this._seed = _seed; - _this.hasSeed = hasSeed; - _this.index = 0; - return _this; - } - Object.defineProperty(ScanSubscriber.prototype, "seed", { - get: function () { - return this._seed; - }, - set: function (value) { - this.hasSeed = true; - this._seed = value; - }, - enumerable: true, - configurable: true - }); - ScanSubscriber.prototype._next = function (value) { - if (!this.hasSeed) { - this.seed = value; - this.destination.next(value); - } - else { - return this._tryNext(value); - } - }; - ScanSubscriber.prototype._tryNext = function (value) { - var index = this.index++; - var result; - try { - result = this.accumulator(this.seed, value, index); - } - catch (err) { - this.destination.error(err); - } - this.seed = result; - this.destination.next(result); - }; - return ScanSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */ -function multicast(subjectOrSubjectFactory, selector) { - return function multicastOperatorFunction(source) { - var subjectFactory; - if (typeof subjectOrSubjectFactory === 'function') { - subjectFactory = subjectOrSubjectFactory; - } - else { - subjectFactory = function subjectFactory() { - return subjectOrSubjectFactory; - }; - } - if (typeof selector === 'function') { - return source.lift(new MulticastOperator(subjectFactory, selector)); - } - var connectable = Object.create(source, connectableObservableDescriptor); - connectable.source = source; - connectable.subjectFactory = subjectFactory; - return connectable; - }; -} -var MulticastOperator = /*@__PURE__*/ (function () { - function MulticastOperator(subjectFactory, selector) { - this.subjectFactory = subjectFactory; - this.selector = selector; - } - MulticastOperator.prototype.call = function (subscriber, source) { - var selector = this.selector; - var subject = this.subjectFactory(); - var subscription = selector(subject).subscribe(subscriber); - subscription.add(source.subscribe(subject)); - return subscription; - }; - return MulticastOperator; -}()); - -/** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */ -function retryWhen(notifier) { - return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); }; -} -var RetryWhenOperator = /*@__PURE__*/ (function () { - function RetryWhenOperator(notifier, source) { - this.notifier = notifier; - this.source = source; - } - RetryWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source)); - }; - return RetryWhenOperator; -}()); -var RetryWhenSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RetryWhenSubscriber, _super); - function RetryWhenSubscriber(destination, notifier, source) { - var _this = _super.call(this, destination) || this; - _this.notifier = notifier; - _this.source = source; - return _this; - } - RetryWhenSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var errors = this.errors; - var retries = this.retries; - var retriesSubscription = this.retriesSubscription; - if (!retries) { - errors = new Subject(); - try { - var notifier = this.notifier; - retries = notifier(errors); - } - catch (e) { - return _super.prototype.error.call(this, e); - } - retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this)); - } - else { - this.errors = undefined; - this.retriesSubscription = undefined; - } - this._unsubscribeAndRecycle(); - this.errors = errors; - this.retries = retries; - this.retriesSubscription = retriesSubscription; - errors.next(err); - } - }; - RetryWhenSubscriber.prototype._unsubscribe = function () { - var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription; - if (errors) { - errors.unsubscribe(); - this.errors = undefined; - } - if (retriesSubscription) { - retriesSubscription.unsubscribe(); - this.retriesSubscription = undefined; - } - this.retries = undefined; - }; - RetryWhenSubscriber.prototype.notifyNext = function () { - var _unsubscribe = this._unsubscribe; - this._unsubscribe = null; - this._unsubscribeAndRecycle(); - this._unsubscribe = _unsubscribe; - this.source.subscribe(this); - }; - return RetryWhenSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */ -function shareSubjectFactory() { - return new Subject(); -} -function share() { - return function (source) { return refCount()(multicast(shareSubjectFactory)(source)); }; -} - -/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ -function switchMap(project, resultSelector) { - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(switchMap(function (a, i) { return from$1(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; - } - return function (source) { return source.lift(new SwitchMapOperator(project)); }; -} -var SwitchMapOperator = /*@__PURE__*/ (function () { - function SwitchMapOperator(project) { - this.project = project; - } - SwitchMapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SwitchMapSubscriber(subscriber, this.project)); - }; - return SwitchMapOperator; -}()); -var SwitchMapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SwitchMapSubscriber, _super); - function SwitchMapSubscriber(destination, project) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.index = 0; - return _this; - } - SwitchMapSubscriber.prototype._next = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (error) { - this.destination.error(error); - return; - } - this._innerSub(result); - }; - SwitchMapSubscriber.prototype._innerSub = function (result) { - var innerSubscription = this.innerSubscription; - if (innerSubscription) { - innerSubscription.unsubscribe(); - } - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - this.innerSubscription = innerSubscribe(result, innerSubscriber); - if (this.innerSubscription !== innerSubscriber) { - destination.add(this.innerSubscription); - } - }; - SwitchMapSubscriber.prototype._complete = function () { - var innerSubscription = this.innerSubscription; - if (!innerSubscription || innerSubscription.closed) { - _super.prototype._complete.call(this); - } - this.unsubscribe(); - }; - SwitchMapSubscriber.prototype._unsubscribe = function () { - this.innerSubscription = undefined; - }; - SwitchMapSubscriber.prototype.notifyComplete = function () { - this.innerSubscription = undefined; - if (this.isStopped) { - _super.prototype._complete.call(this); - } - }; - SwitchMapSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - return SwitchMapSubscriber; -}(SimpleOuterSubscriber)); + * Apache License + * Version 2.0, January 2004 + * http://www.apache.org/licenses/ + * + * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + * + * 1. Definitions. + * + * "License" shall mean the terms and conditions for use, reproduction, + * and distribution as defined by Sections 1 through 9 of this document. + * + * "Licensor" shall mean the copyright owner or entity authorized by + * the copyright owner that is granting the License. + * + * "Legal Entity" shall mean the union of the acting entity and all + * other entities that control, are controlled by, or are under common + * control with that entity. For the purposes of this definition, + * "control" means (i) the power, direct or indirect, to cause the + * direction or management of such entity, whether by contract or + * otherwise, or (ii) ownership of fifty percent (50%) or more of the + * outstanding shares, or (iii) beneficial ownership of such entity. + * + * "You" (or "Your") shall mean an individual or Legal Entity + * exercising permissions granted by this License. + * + * "Source" form shall mean the preferred form for making modifications, + * including but not limited to software source code, documentation + * source, and configuration files. + * + * "Object" form shall mean any form resulting from mechanical + * transformation or translation of a Source form, including but + * not limited to compiled object code, generated documentation, + * and conversions to other media types. + * + * "Work" shall mean the work of authorship, whether in Source or + * Object form, made available under the License, as indicated by a + * copyright notice that is included in or attached to the work + * (an example is provided in the Appendix below). + * + * "Derivative Works" shall mean any work, whether in Source or Object + * form, that is based on (or derived from) the Work and for which the + * editorial revisions, annotations, elaborations, or other modifications + * represent, as a whole, an original work of authorship. For the purposes + * of this License, Derivative Works shall not include works that remain + * separable from, or merely link (or bind by name) to the interfaces of, + * the Work and Derivative Works thereof. + * + * "Contribution" shall mean any work of authorship, including + * the original version of the Work and any modifications or additions + * to that Work or Derivative Works thereof, that is intentionally + * submitted to Licensor for inclusion in the Work by the copyright owner + * or by an individual or Legal Entity authorized to submit on behalf of + * the copyright owner. For the purposes of this definition, "submitted" + * means any form of electronic, verbal, or written communication sent + * to the Licensor or its representatives, including but not limited to + * communication on electronic mailing lists, source code control systems, + * and issue tracking systems that are managed by, or on behalf of, the + * Licensor for the purpose of discussing and improving the Work, but + * excluding communication that is conspicuously marked or otherwise + * designated in writing by the copyright owner as "Not a Contribution." + * + * "Contributor" shall mean Licensor and any individual or Legal Entity + * on behalf of whom a Contribution has been received by Licensor and + * subsequently incorporated within the Work. + * + * 2. Grant of Copyright License. Subject to the terms and conditions of + * this License, each Contributor hereby grants to You a perpetual, + * worldwide, non-exclusive, no-charge, royalty-free, irrevocable + * copyright license to reproduce, prepare Derivative Works of, + * publicly display, publicly perform, sublicense, and distribute the + * Work and such Derivative Works in Source or Object form. + * + * 3. Grant of Patent License. Subject to the terms and conditions of + * this License, each Contributor hereby grants to You a perpetual, + * worldwide, non-exclusive, no-charge, royalty-free, irrevocable + * (except as stated in this section) patent license to make, have made, + * use, offer to sell, sell, import, and otherwise transfer the Work, + * where such license applies only to those patent claims licensable + * by such Contributor that are necessarily infringed by their + * Contribution(s) alone or by combination of their Contribution(s) + * with the Work to which such Contribution(s) was submitted. If You + * institute patent litigation against any entity (including a + * cross-claim or counterclaim in a lawsuit) alleging that the Work + * or a Contribution incorporated within the Work constitutes direct + * or contributory patent infringement, then any patent licenses + * granted to You under this License for that Work shall terminate + * as of the date such litigation is filed. + * + * 4. Redistribution. You may reproduce and distribute copies of the + * Work or Derivative Works thereof in any medium, with or without + * modifications, and in Source or Object form, provided that You + * meet the following conditions: + * + * (a) You must give any other recipients of the Work or + * Derivative Works a copy of this License; and + * + * (b) You must cause any modified files to carry prominent notices + * stating that You changed the files; and + * + * (c) You must retain, in the Source form of any Derivative Works + * that You distribute, all copyright, patent, trademark, and + * attribution notices from the Source form of the Work, + * excluding those notices that do not pertain to any part of + * the Derivative Works; and + * + * (d) If the Work includes a "NOTICE" text file as part of its + * distribution, then any Derivative Works that You distribute must + * include a readable copy of the attribution notices contained + * within such NOTICE file, excluding those notices that do not + * pertain to any part of the Derivative Works, in at least one + * of the following places: within a NOTICE text file distributed + * as part of the Derivative Works; within the Source form or + * documentation, if provided along with the Derivative Works; or, + * within a display generated by the Derivative Works, if and + * wherever such third-party notices normally appear. The contents + * of the NOTICE file are for informational purposes only and + * do not modify the License. You may add Your own attribution + * notices within Derivative Works that You distribute, alongside + * or as an addendum to the NOTICE text from the Work, provided + * that such additional attribution notices cannot be construed + * as modifying the License. + * + * You may add Your own copyright statement to Your modifications and + * may provide additional or different license terms and conditions + * for use, reproduction, or distribution of Your modifications, or + * for any such Derivative Works as a whole, provided Your use, + * reproduction, and distribution of the Work otherwise complies with + * the conditions stated in this License. + * + * 5. Submission of Contributions. Unless You explicitly state otherwise, + * any Contribution intentionally submitted for inclusion in the Work + * by You to the Licensor shall be under the terms and conditions of + * this License, without any additional terms or conditions. + * Notwithstanding the above, nothing herein shall supersede or modify + * the terms of any separate license agreement you may have executed + * with Licensor regarding such Contributions. + * + * 6. Trademarks. This License does not grant permission to use the trade + * names, trademarks, service marks, or product names of the Licensor, + * except as required for reasonable and customary use in describing the + * origin of the Work and reproducing the content of the NOTICE file. + * + * 7. Disclaimer of Warranty. Unless required by applicable law or + * agreed to in writing, Licensor provides the Work (and each + * Contributor provides its Contributions) on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied, including, without limitation, any warranties or conditions + * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + * PARTICULAR PURPOSE. You are solely responsible for determining the + * appropriateness of using or redistributing the Work and assume any + * risks associated with Your exercise of permissions under this License. + * + * 8. Limitation of Liability. In no event and under no legal theory, + * whether in tort (including negligence), contract, or otherwise, + * unless required by applicable law (such as deliberate and grossly + * negligent acts) or agreed to in writing, shall any Contributor be + * liable to You for damages, including any direct, indirect, special, + * incidental, or consequential damages of any character arising as a + * result of this License or out of the use or inability to use the + * Work (including but not limited to damages for loss of goodwill, + * work stoppage, computer failure or malfunction, or any and all + * other commercial damages or losses), even if such Contributor + * has been advised of the possibility of such damages. + * + * 9. Accepting Warranty or Additional Liability. While redistributing + * the Work or Derivative Works thereof, You may choose to offer, + * and charge a fee for, acceptance of support, warranty, indemnity, + * or other liability obligations and/or rights consistent with this + * License. However, in accepting such obligations, You may act only + * on Your own behalf and on Your sole responsibility, not on behalf + * of any other Contributor, and only if You agree to indemnify, + * defend, and hold each Contributor harmless for any liability + * incurred by, or claims asserted against, such Contributor by reason + * of your accepting any such warranty or additional liability. + * + * END OF TERMS AND CONDITIONS + * + * APPENDIX: How to apply the Apache License to your work. + * + * To apply the Apache License to your work, attach the following + * boilerplate notice, with the fields enclosed by brackets "[]" + * replaced with your own identifying information. (Don't include + * the brackets!) The text should be enclosed in the appropriate + * comment syntax for the file format. We also recommend that a + * file or class name and description of purpose be included on the + * same "printed page" as the copyright notice for easier + * identification within third-party archives. + * + * Copyright 2021 KonghaYao 江夏尧 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function e(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;ne.length)&&(t=e.length);for(var r=0,n=new Array(t);r=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=e[Symbol.iterator]()).next.bind(r)}var R=Symbol("mobx-stored-annotations");function U(e){return Object.assign((function(t,r){M(t,r,e)}),e)}function M(e,t,r){x(e,R)||m(e,R,C({},e[R])),function(e){return"override"===e.annotationType_}(r)||(e[R][t]=r)}var z=Symbol("mobx administration"),F=function(){function e(e){void 0===e&&(e="Atom"),this.name_=void 0,this.isPendingUnobservation_=!1,this.isBeingObserved_=!1,this.observers_=new Set,this.diffValue_=0,this.lastAccessedBy_=0,this.lowestObserverState_=Ue.NOT_TRACKING_,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return at(this)},t.reportChanged=function(){it(),st(this),ot()},t.toString=function(){return this.name_},e}(),L=w("Atom",F);function $(e,t,r){void 0===t&&(t=h),void 0===r&&(r=h);var n,i=new F(e);return t!==h&&St("onBO",i,t,n),r!==h&&Pt(i,r),i}var H={identity:function(e,t){return e===t},structural:function(e,t){return zr(e,t)},default:function(e,t){return Object.is(e,t)},shallow:function(e,t){return zr(e,t,1)}};function B(e,t,r){return Vt(e)?e:Array.isArray(e)?we.array(e,{name:r}):y(e)?we.object(e,void 0,{name:r}):O(e)?we.map(e,{name:r}):j(e)?we.set(e,{name:r}):"function"!=typeof e||_t(e)||kt(e)?e:g(e)?It(e):gt(r,e)}function G(e){return e}function K(e,t){return{annotationType_:e,options_:t,make_:q,extend_:W}}function q(e,t,r,n){var i;if(null==(i=this.options_)?void 0:i.bound)return null===this.extend_(e,t,r,!1)?0:1;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if(_t(r.value))return 1;var a=Y(e,this,t,r,!1);return o(n,t,a),2}function W(e,t,r,n){var i=Y(e,this,t,r);return e.defineProperty_(t,i,n)}function Y(e,t,r,n,i){var o,a,s,u,c,l;void 0===i&&(i=et.safeDescriptors),l=n,t.annotationType_,l.value;var f,p=n.value;(null==(o=t.options_)?void 0:o.bound)&&(p=p.bind(null!=(f=e.proxy_)?f:e.target_));return{value:Ie(null!=(a=null==(s=t.options_)?void 0:s.name)?a:r.toString(),p,null!=(u=null==(c=t.options_)?void 0:c.autoAction)&&u),configurable:!i||e.isPlainObject_,enumerable:!1,writable:!i}}function Q(e,t){return{annotationType_:e,options_:t,make_:X,extend_:Z}}function X(e,t,r,n){var i;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if((null==(i=this.options_)?void 0:i.bound)&&!kt(e.target_[t])&&null===this.extend_(e,t,r,!1))return 0;if(kt(r.value))return 1;var a=J(e,this,t,r,!1,!1);return o(n,t,a),2}function Z(e,t,r,n){var i,o=J(e,this,t,r,null==(i=this.options_)?void 0:i.bound);return e.defineProperty_(t,o,n)}function J(e,t,r,n,i,o){var a;void 0===o&&(o=et.safeDescriptors),a=n,t.annotationType_,a.value;var s,u=n.value;i&&(u=u.bind(null!=(s=e.proxy_)?s:e.target_));return{value:It(u),configurable:!o||e.isPlainObject_,enumerable:!1,writable:!o}}function ee(e,t){return{annotationType_:e,options_:t,make_:te,extend_:re}}function te(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function re(e,t,r,n){var i;return i=r,this.annotationType_,i.get,e.defineComputedProperty_(t,C({},this.options_,{get:r.get,set:r.set}),n)}function ne(e,t){return{annotationType_:e,options_:t,make_:ie,extend_:oe}}function ie(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function oe(e,t,r,n){var i,o;return this.annotationType_,e.defineObservableProperty_(t,r.value,null!=(i=null==(o=this.options_)?void 0:o.enhancer)?i:B,n)}var ae=se();function se(e){return{annotationType_:"true",options_:e,make_:ue,extend_:ce}}function ue(e,t,r,n){var i,a,s,u;if(r.get)return Pe.make_(e,t,r,n);if(r.set){var c=Ie(t.toString(),r.set);return n===e.target_?null===e.defineProperty_(t,{configurable:!et.safeDescriptors||e.isPlainObject_,set:c})?0:2:(o(n,t,{configurable:!0,set:c}),2)}if(n!==e.target_&&"function"==typeof r.value)return g(r.value)?((null==(u=this.options_)?void 0:u.autoBind)?It.bound:It).make_(e,t,r,n):((null==(s=this.options_)?void 0:s.autoBind)?gt.bound:gt).make_(e,t,r,n);var l,f=!1===(null==(i=this.options_)?void 0:i.deep)?we.ref:we;"function"==typeof r.value&&(null==(a=this.options_)?void 0:a.autoBind)&&(r.value=r.value.bind(null!=(l=e.proxy_)?l:e.target_));return f.make_(e,t,r,n)}function ce(e,t,r,n){var i,o,a;if(r.get)return Pe.extend_(e,t,r,n);if(r.set)return e.defineProperty_(t,{configurable:!et.safeDescriptors||e.isPlainObject_,set:Ie(t.toString(),r.set)},n);"function"==typeof r.value&&(null==(i=this.options_)?void 0:i.autoBind)&&(r.value=r.value.bind(null!=(a=e.proxy_)?a:e.target_));return(!1===(null==(o=this.options_)?void 0:o.deep)?we.ref:we).extend_(e,t,r,n)}var le={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function fe(e){return e||le}Object.freeze(le);var pe=ne("observable"),he=ne("observable.ref",{enhancer:G}),be=ne("observable.shallow",{enhancer:function(e,t,r){return null==e||Sr(e)||lr(e)||vr(e)||mr(e)?e:Array.isArray(e)?we.array(e,{name:r,deep:!1}):y(e)?we.object(e,void 0,{name:r,deep:!1}):O(e)?we.map(e,{name:r,deep:!1}):j(e)?we.set(e,{name:r,deep:!1}):void 0}}),de=ne("observable.struct",{enhancer:function(e,t){return zr(e,t)?t:e}}),ve=U(pe);function ye(e){return!0===e.deep?B:!1===e.deep?G:(t=e.defaultDecorator)&&null!=(r=null==(n=t.options_)?void 0:n.enhancer)?r:B;var t,r,n}function ge(e,t,r){if(!d(t))return Vt(e)?e:y(e)?we.object(e,t,r):Array.isArray(e)?we.array(e,t):O(e)?we.map(e,t):j(e)?we.set(e,t):"object"==typeof e&&null!==e?e:we.box(e,t);M(e,t,pe)}Object.assign(ge,ve);var me,_e,we=n(ge,{box:function(e,t){var r=fe(t);return new Ve(e,ye(r),r.name,!0,r.equals)},array:function(e,t){var r=fe(t);return(!1===et.useProxies||!1===r.proxy?Nr:tr)(e,ye(r),r.name)},map:function(e,t){var r=fe(t);return new dr(e,ye(r),r.name)},set:function(e,t){var r=fe(t);return new gr(e,ye(r),r.name)},object:function(e,t,r){return function(e,t,r,n){var i=E(t),o=Or(e,n)[z];it();try{S(i).forEach((function(e){o.extend_(e,i[e],!r||(!(e in r)||r[e]))}))}finally{ot()}return e}(!1===et.useProxies||!1===(null==r?void 0:r.proxy)?Or({},r):function(e,t){var r,n;return f(),e=Or(e,t),null!=(n=(r=e[z]).proxy_)?n:r.proxy_=new Proxy(e,Bt)}({},r),e,t)},ref:U(he),shallow:U(be),deep:ve,struct:U(de)}),Oe=ee("computed"),je=ee("computed.struct",{equals:H.structural}),Pe=function(e,t){if(d(t))return M(e,t,Oe);if(y(e))return U(ee("computed",e));var r=y(t)?t:{};return r.get=e,r.name||(r.name=e.name||""),new ze(r)};Object.assign(Pe,Oe),Pe.struct=U(je);var Se,Ae=0,xe=1,Ee=null!=(me=null==(_e=i((function(){}),"name"))?void 0:_e.configurable)&&me,Te={value:"action",configurable:!0,writable:!1,enumerable:!1};function Ie(e,t,r,n){function i(){return Ce(e,r,t,n||this,arguments)}return void 0===r&&(r=!1),i.isMobxAction=!0,Ee&&(Te.value=e,Object.defineProperty(i,"name",Te)),i}function Ce(t,r,n,i,o){var a=function(e,t,r,n){var i=!1,o=0,a=et.trackingDerivation,s=!t||!a;it();var u=et.allowStateChanges;s&&(qe(),u=ke(!0));var c=Ye(!0),l={runAsAction_:s,prevDerivation_:a,prevAllowStateChanges_:u,prevAllowStateReads_:c,notifySpy_:i,startTime_:o,actionId_:xe++,parentActionId_:Ae};return Ae=l.actionId_,l}(0,r);try{return n.apply(i,o)}catch(e){throw a.error_=e,e}finally{!function(t){Ae!==t.actionId_&&e(30);Ae=t.parentActionId_,void 0!==t.error_&&(et.suppressReactionErrors=!0);De(t.prevAllowStateChanges_),Qe(t.prevAllowStateReads_),ot(),t.runAsAction_&&We(t.prevDerivation_);et.suppressReactionErrors=!1}(a)}}function ke(e){var t=et.allowStateChanges;return et.allowStateChanges=e,t}function De(e){et.allowStateChanges=e}Se=Symbol.toPrimitive;var Ne,Ve=function(e){function t(t,r,n,i,o){var a;return void 0===n&&(n="ObservableValue"),void 0===o&&(o=H.default),(a=e.call(this,n)||this).enhancer=void 0,a.name_=void 0,a.equals=void 0,a.hasUnreportedChange_=!1,a.interceptors_=void 0,a.changeListeners_=void 0,a.value_=void 0,a.dehancer=void 0,a.enhancer=r,a.name_=n,a.equals=o,a.value_=r(t,void 0,n),a}k(t,e);var r=t.prototype;return r.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.set=function(e){this.value_,(e=this.prepareNewValue_(e))!==et.UNCHANGED&&this.setNewValue_(e)},r.prepareNewValue_=function(e){if(Gt(this)){var t=qt(this,{object:this,type:Zt,newValue:e});if(!t)return et.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value_,this.name_),this.equals(this.value_,e)?et.UNCHANGED:e},r.setNewValue_=function(e){var t=this.value_;this.value_=e,this.reportChanged(),Wt(this)&&Qt(this,{type:Zt,object:this,newValue:e,oldValue:t})},r.get=function(){return this.reportObserved(),this.dehanceValue(this.value_)},r.intercept_=function(e){return Kt(this,e)},r.observe_=function(e,t){return t&&e({observableKind:"value",debugObjectName:this.name_,object:this,type:Zt,newValue:this.value_,oldValue:void 0}),Yt(this,e)},r.raw=function(){return this.value_},r.toJSON=function(){return this.get()},r.toString=function(){return this.name_+"["+this.value_+"]"},r.valueOf=function(){return A(this.get())},r[Se]=function(){return this.valueOf()},t}(F),Re=w("ObservableValue",Ve);Ne=Symbol.toPrimitive;var Ue,Me,ze=function(){function t(t){this.dependenciesState_=Ue.NOT_TRACKING_,this.observing_=[],this.newObserving_=null,this.isBeingObserved_=!1,this.isPendingUnobservation_=!1,this.observers_=new Set,this.diffValue_=0,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=Ue.UP_TO_DATE_,this.unboundDepsCount_=0,this.value_=new Le(null),this.name_=void 0,this.triggeredBy_=void 0,this.isComputing_=!1,this.isRunningSetter_=!1,this.derivation=void 0,this.setter_=void 0,this.isTracing_=Me.NONE,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,t.get||e(31),this.derivation=t.get,this.name_=t.name||"ComputedValue",t.set&&(this.setter_=Ie("ComputedValue-setter",t.set)),this.equals_=t.equals||(t.compareStructural||t.struct?H.structural:H.default),this.scope_=t.context,this.requiresReaction_=!!t.requiresReaction,this.keepAlive_=!!t.keepAlive}var r=t.prototype;return r.onBecomeStale_=function(){!function(e){if(e.lowestObserverState_!==Ue.UP_TO_DATE_)return;e.lowestObserverState_=Ue.POSSIBLY_STALE_,e.observers_.forEach((function(e){e.dependenciesState_===Ue.UP_TO_DATE_&&(e.dependenciesState_=Ue.POSSIBLY_STALE_,e.onBecomeStale_())}))}(this)},r.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},r.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},r.get=function(){if(this.isComputing_&&e(32,this.name_,this.derivation),0!==et.inBatch||0!==this.observers_.size||this.keepAlive_){if(at(this),He(this)){var t=et.trackingContext;this.keepAlive_&&!t&&(et.trackingContext=this),this.trackAndCompute()&&function(e){if(e.lowestObserverState_===Ue.STALE_)return;e.lowestObserverState_=Ue.STALE_,e.observers_.forEach((function(t){t.dependenciesState_===Ue.POSSIBLY_STALE_?t.dependenciesState_=Ue.STALE_:t.dependenciesState_===Ue.UP_TO_DATE_&&(e.lowestObserverState_=Ue.UP_TO_DATE_)}))}(this),et.trackingContext=t}}else He(this)&&(this.warnAboutUntrackedRead_(),it(),this.value_=this.computeValue_(!1),ot());var r=this.value_;if($e(r))throw r.cause;return r},r.set=function(t){if(this.setter_){this.isRunningSetter_&&e(33,this.name_),this.isRunningSetter_=!0;try{this.setter_.call(this.scope_,t)}finally{this.isRunningSetter_=!1}}else e(34,this.name_)},r.trackAndCompute=function(){var e=this.value_,t=this.dependenciesState_===Ue.NOT_TRACKING_,r=this.computeValue_(!0),n=t||$e(e)||$e(r)||!this.equals_(e,r);return n&&(this.value_=r),n},r.computeValue_=function(e){this.isComputing_=!0;var t,r=ke(!1);if(e)t=Be(this,this.derivation,this.scope_);else if(!0===et.disableErrorBoundaries)t=this.derivation.call(this.scope_);else try{t=this.derivation.call(this.scope_)}catch(e){t=new Le(e)}return De(r),this.isComputing_=!1,t},r.suspend_=function(){this.keepAlive_||(Ge(this),this.value_=void 0)},r.observe_=function(e,t){var r=this,n=!0,i=void 0;return function(e,t){var r,n;void 0===t&&(t=u);var i,o=null!=(r=null==(n=t)?void 0:n.name)?r:"Autorun";if(t.scheduler||t.delay){var a=Ot(t),s=!1;i=new ut(o,(function(){s||(s=!0,a((function(){s=!1,i.isDisposed_||i.track(c)})))}),t.onError,t.requiresObservable)}else i=new ut(o,(function(){this.track(c)}),t.onError,t.requiresObservable);function c(){e(i)}return i.schedule_(),i.getDisposer_()}((function(){var o=r.get();if(!n||t){var a=qe();e({observableKind:"computed",debugObjectName:r.name_,type:Zt,object:r,newValue:o,oldValue:i}),We(a)}n=!1,i=o}))},r.warnAboutUntrackedRead_=function(){},r.toString=function(){return this.name_+"["+this.derivation.toString()+"]"},r.valueOf=function(){return A(this.get())},r[Ne]=function(){return this.valueOf()},t}(),Fe=w("ComputedValue",ze);!function(e){e[e.NOT_TRACKING_=-1]="NOT_TRACKING_",e[e.UP_TO_DATE_=0]="UP_TO_DATE_",e[e.POSSIBLY_STALE_=1]="POSSIBLY_STALE_",e[e.STALE_=2]="STALE_"}(Ue||(Ue={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(Me||(Me={}));var Le=function(e){this.cause=void 0,this.cause=e};function $e(e){return e instanceof Le}function He(e){switch(e.dependenciesState_){case Ue.UP_TO_DATE_:return!1;case Ue.NOT_TRACKING_:case Ue.STALE_:return!0;case Ue.POSSIBLY_STALE_:for(var t=Ye(!0),r=qe(),n=e.observing_,i=n.length,o=0;on&&(n=s.dependenciesState_)}r.length=i,e.newObserving_=null,o=t.length;for(;o--;){var u=t[o];0===u.diffValue_&&rt(u,e),u.diffValue_=0}for(;i--;){var c=r[i];1===c.diffValue_&&(c.diffValue_=0,tt(c,e))}n!==Ue.UP_TO_DATE_&&(e.dependenciesState_=n,e.onBecomeStale_())}(e),Qe(n),i}function Ge(e){var t=e.observing_;e.observing_=[];for(var r=t.length;r--;)rt(t[r],e);e.dependenciesState_=Ue.NOT_TRACKING_}function Ke(e){var t=qe();try{return e()}finally{We(t)}}function qe(){var e=et.trackingDerivation;return et.trackingDerivation=null,e}function We(e){et.trackingDerivation=e}function Ye(e){var t=et.allowStateReads;return et.allowStateReads=e,t}function Qe(e){et.allowStateReads=e}function Xe(e){if(e.dependenciesState_!==Ue.UP_TO_DATE_){e.dependenciesState_=Ue.UP_TO_DATE_;for(var t=e.observing_,r=t.length;r--;)t[r].lowestObserverState_=Ue.UP_TO_DATE_}}var Ze=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},Je=!0,et=function(){var t=r();return t.__mobxInstanceCount>0&&!t.__mobxGlobals&&(Je=!1),t.__mobxGlobals&&t.__mobxGlobals.version!==(new Ze).version&&(Je=!1),Je?t.__mobxGlobals?(t.__mobxInstanceCount+=1,t.__mobxGlobals.UNCHANGED||(t.__mobxGlobals.UNCHANGED={}),t.__mobxGlobals):(t.__mobxInstanceCount=1,t.__mobxGlobals=new Ze):(setTimeout((function(){e(35)}),1),new Ze)}();function tt(e,t){e.observers_.add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function rt(e,t){e.observers_.delete(t),0===e.observers_.size&&nt(e)}function nt(e){!1===e.isPendingUnobservation_&&(e.isPendingUnobservation_=!0,et.pendingUnobservations.push(e))}function it(){et.inBatch++}function ot(){if(0==--et.inBatch){ct();for(var e=et.pendingUnobservations,t=0;t0&&nt(e),!1)}function st(e){e.lowestObserverState_!==Ue.STALE_&&(e.lowestObserverState_=Ue.STALE_,e.observers_.forEach((function(e){e.dependenciesState_===Ue.UP_TO_DATE_&&e.onBecomeStale_(),e.dependenciesState_=Ue.STALE_})))}var ut=function(){function t(e,t,r,n){void 0===e&&(e="Reaction"),void 0===n&&(n=!1),this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=Ue.NOT_TRACKING_,this.diffValue_=0,this.runId_=0,this.unboundDepsCount_=0,this.isDisposed_=!1,this.isScheduled_=!1,this.isTrackPending_=!1,this.isRunning_=!1,this.isTracing_=Me.NONE,this.name_=e,this.onInvalidate_=t,this.errorHandler_=r,this.requiresObservable_=n}var r=t.prototype;return r.onBecomeStale_=function(){this.schedule_()},r.schedule_=function(){this.isScheduled_||(this.isScheduled_=!0,et.pendingReactions.push(this),ct())},r.isScheduled=function(){return this.isScheduled_},r.runReaction_=function(){if(!this.isDisposed_){it(),this.isScheduled_=!1;var e=et.trackingContext;if(et.trackingContext=this,He(this)){this.isTrackPending_=!0;try{this.onInvalidate_()}catch(e){this.reportExceptionInDerivation_(e)}}et.trackingContext=e,ot()}},r.track=function(e){if(!this.isDisposed_){it(),this.isRunning_=!0;var t=et.trackingContext;et.trackingContext=this;var r=Be(this,e,void 0);et.trackingContext=t,this.isRunning_=!1,this.isTrackPending_=!1,this.isDisposed_&&Ge(this),$e(r)&&this.reportExceptionInDerivation_(r.cause),ot()}},r.reportExceptionInDerivation_=function(e){var t=this;if(this.errorHandler_)this.errorHandler_(e,this);else{if(et.disableErrorBoundaries)throw e;var r="[mobx] uncaught error in '"+this+"'";et.suppressReactionErrors||console.error(r,e),et.globalReactionErrorHandlers.forEach((function(r){return r(e,t)}))}},r.dispose=function(){this.isDisposed_||(this.isDisposed_=!0,this.isRunning_||(it(),Ge(this),ot()))},r.getDisposer_=function(){var e=this.dispose.bind(this);return e[z]=this,e},r.toString=function(){return"Reaction["+this.name_+"]"},r.trace=function(t){void 0===t&&(t=!1),function(){e("trace() is not available in production builds");for(var t=!1,r=arguments.length,n=new Array(r),i=0;i0||et.isRunningReactions||function(e){e()}(lt)}function lt(){et.isRunningReactions=!0;for(var e=et.pendingReactions,t=0;e.length>0;){100==++t&&(console.error("[mobx] cycle in reaction: "+e[0]),e.splice(0));for(var r=e.splice(0),n=0,i=r.length;n",t,e):b(r)?Ie(t,r,e):d(r)?M(t,r,e?bt:pt):d(t)?U(K(e?"autoAction":"action",{name:t,autoAction:e})):void 0}}var yt=vt(!1);Object.assign(yt,pt);var gt=vt(!0);function mt(e){return Ce(e.name,!1,e,this,void 0)}function _t(e){return b(e)&&!0===e.isMobxAction}Object.assign(gt,bt),yt.bound=U(ht),gt.bound=U(dt);var wt=function(e){return e()};function Ot(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:wt}function jt(e,t,r){var n;void 0===r&&(r=u);var i,o,a,s=null!=(n=r.name)?n:"Reaction",c=yt(s,r.onError?(i=r.onError,o=t,function(){try{return o.apply(this,arguments)}catch(e){i.call(this,e)}}):t),l=!r.scheduler&&!r.delay,f=Ot(r),p=!0,h=!1,b=void 0,d=r.compareStructural?H.structural:r.equals||H.default,v=new ut(s,(function(){p||l?y():h||(h=!0,f(y))}),r.onError,r.requiresObservable);function y(){if(h=!1,!v.isDisposed_){var t=!1;v.track((function(){var r=function(e,t){var r=ke(e);try{return t()}finally{De(r)}}(!1,(function(){return e(v)}));t=p||!d(a,r),b=a,a=r})),(p&&r.fireImmediately||!p&&t)&&c(a,b,v),p=!1}}return v.schedule_(),v.getDisposer_()}function Pt(e,t,r){return St("onBUO",e,t,r)}function St(e,t,r,n){var i="function"==typeof n?Vr(t,r):Vr(t),o=b(n)?n:r,a=e+"L";return i[a]?i[a].add(o):i[a]=new Set([o]),function(){var e=i[a];e&&(e.delete(o),0===e.size&&delete i[a])}}var At=0;function xt(){this.message="FLOW_CANCELLED"}xt.prototype=Object.create(Error.prototype);var Et=Q("flow"),Tt=Q("flow.bound",{bound:!0}),It=Object.assign((function(e,t){if(d(t))return M(e,t,Et);var r=e,n=r.name||"",i=function(){var e,t=this,i=arguments,o=++At,a=yt(n+" - runid: "+o+" - init",r).apply(t,i),s=void 0,u=new Promise((function(t,r){var i=0;function u(e){var t;s=void 0;try{t=yt(n+" - runid: "+o+" - yield "+i++,a.next).call(a,e)}catch(e){return r(e)}l(t)}function c(e){var t;s=void 0;try{t=yt(n+" - runid: "+o+" - yield "+i++,a.throw).call(a,e)}catch(e){return r(e)}l(t)}function l(e){if(!b(null==e?void 0:e.then))return e.done?t(e.value):(s=Promise.resolve(e.value)).then(u,c);e.then(l,r)}e=r,u(void 0)}));return u.cancel=yt(n+" - runid: "+o+" - cancel",(function(){try{s&&Ct(s);var t=a.return(void 0),r=Promise.resolve(t.value);r.then(h,h),Ct(r),e(new xt)}catch(t){e(t)}})),u};return i.isMobXFlow=!0,i}),Et);function Ct(e){b(e.cancel)&&e.cancel()}function kt(e){return!0===(null==e?void 0:e.isMobXFlow)}function Dt(e,t,r){var n;return vr(e)||lr(e)||Re(e)?n=Rr(e):Sr(e)&&(n=Rr(e,t)),n.dehancer="function"==typeof t?t:r,function(){n.dehancer=void 0}}function Nt(e,t,r){return b(r)?function(e,t,r){return Rr(e,t).intercept_(r)}(e,t,r):function(e,t){return Rr(e).intercept_(t)}(e,t)}function Vt(e){return function(e,t){return!!e&&(void 0!==t?!!Sr(e)&&e[z].values_.has(t):Sr(e)||!!e[z]||L(e)||ft(e)||Fe(e))}(e)}function Rt(t){return Sr(t)?t[z].keys_():vr(t)||mr(t)?Array.from(t.keys()):lr(t)?t.map((function(e,t){return t})):void e(5)}function Ut(t){return Sr(t)?Rt(t).map((function(e){return t[e]})):vr(t)?Rt(t).map((function(e){return t.get(e)})):mr(t)?Array.from(t.values()):lr(t)?t.slice():void e(6)}function Mt(t,r,n){if(2!==arguments.length||mr(t))Sr(t)?t[z].set_(r,n):vr(t)?t.set(r,n):mr(t)?t.add(r):lr(t)?("number"!=typeof r&&(r=parseInt(r,10)),r<0&&e("Invalid index: '"+r+"'"),it(),r>=t.length&&(t.length=r+1),t[r]=n,ot()):e(8);else{it();var i=r;try{for(var o in i)Mt(t,o,i[o])}finally{ot()}}}function zt(t,r,n){if(Sr(t))return t[z].defineProperty_(r,n);e(39)}function Ft(e,t,r,n){return b(r)?function(e,t,r,n){return Rr(e,t).observe_(r,n)}(e,t,r,n):function(e,t,r){return Rr(e).observe_(t,r)}(e,t,r)}function Lt(e){switch(e.length){case 0:return et.trackingDerivation;case 1:return Vr(e[0]);case 2:return Vr(e[0],e[1])}}function $t(e,t){void 0===t&&(t=void 0),it();try{return e.apply(t)}finally{ot()}}function Ht(e){return e[z]}It.bound=U(Tt);var Bt={has:function(e,t){return Ht(e).has_(t)},get:function(e,t){return Ht(e).get_(t)},set:function(e,t,r){var n;return!!d(t)&&(null==(n=Ht(e).set_(t,r,!0))||n)},deleteProperty:function(e,t){var r;return!!d(t)&&(null==(r=Ht(e).delete_(t,!0))||r)},defineProperty:function(e,t,r){var n;return null==(n=Ht(e).defineProperty_(t,r))||n},ownKeys:function(e){return Ht(e).ownKeys_()},preventExtensions:function(t){e(13)}};function Gt(e){return void 0!==e.interceptors_&&e.interceptors_.length>0}function Kt(e,t){var r=e.interceptors_||(e.interceptors_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function qt(t,r){var n=qe();try{for(var i=[].concat(t.interceptors_||[]),o=0,a=i.length;o0}function Yt(e,t){var r=e.changeListeners_||(e.changeListeners_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function Qt(e,t){var r=qe(),n=e.changeListeners_;if(n){for(var i=0,o=(n=n.slice()).length;i0?e.map(this.dehancer):e},r.intercept_=function(e){return Kt(this,e)},r.observe_=function(e,t){return void 0===t&&(t=!1),t&&e({observableKind:"array",object:this.proxy_,debugObjectName:this.atom_.name_,type:"splice",index:0,added:this.values_.slice(),addedCount:this.values_.length,removed:[],removedCount:0}),Yt(this,e)},r.getArrayLength_=function(){return this.atom_.reportObserved(),this.values_.length},r.setArrayLength_=function(t){("number"!=typeof t||t<0)&&e("Out of range: "+t);var r=this.values_.length;if(t!==r)if(t>r){for(var n=new Array(t-r),i=0;i0&&Dr(t+r+1)},r.spliceWithArray_=function(e,t,r){var n=this;this.atom_;var i=this.values_.length;if(void 0===e?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=1===arguments.length?i-e:null==t?0:Math.max(0,Math.min(t,i-e)),void 0===r&&(r=s),Gt(this)){var o=qt(this,{object:this.proxy_,type:"splice",index:e,removedCount:t,added:r});if(!o)return s;t=o.removedCount,r=o.added}if(r=0===r.length?r:r.map((function(e){return n.enhancer_(e,void 0)})),this.legacyMode_){var a=r.length-t;this.updateArrayLength_(i,a)}var u=this.spliceItemsIntoValues_(e,t,r);return 0===t&&0===r.length||this.notifyArraySplice_(e,r,u),this.dehanceValues_(u)},r.spliceItemsIntoValues_=function(e,t,r){var n;if(r.length<1e4)return(n=this.values_).splice.apply(n,[e,t].concat(r));var i=this.values_.slice(e,e+t),o=this.values_.slice(e+t);this.values_.length=e+r.length-t;for(var a=0;a2?r-2:0),i=2;i-1&&(this.splice(r,1),!0)}};function nr(e,t){"function"==typeof Array.prototype[e]&&(rr[e]=t(e))}function ir(e){return function(){var t=this[z];t.atom_.reportObserved();var r=t.dehanceValues_(t.values_);return r[e].apply(r,arguments)}}function or(e){return function(t,r){var n=this,i=this[z];return i.atom_.reportObserved(),i.dehanceValues_(i.values_)[e]((function(e,i){return t.call(r,e,i,n)}))}}function ar(e){return function(){var t=this,r=this[z];r.atom_.reportObserved();var n=r.dehanceValues_(r.values_),i=arguments[0];return arguments[0]=function(e,r,n){return i(e,r,n,t)},n[e].apply(n,arguments)}}nr("concat",ir),nr("flat",ir),nr("includes",ir),nr("indexOf",ir),nr("join",ir),nr("lastIndexOf",ir),nr("slice",ir),nr("toString",ir),nr("toLocaleString",ir),nr("every",or),nr("filter",or),nr("find",or),nr("findIndex",or),nr("flatMap",or),nr("forEach",or),nr("map",or),nr("some",or),nr("reduce",ar),nr("reduceRight",ar);var sr,ur,cr=w("ObservableArrayAdministration",er);function lr(e){return v(e)&&cr(e[z])}var fr={},pr="add";sr=Symbol.iterator,ur=Symbol.toStringTag;var hr,br,dr=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableMap"),this.enhancer_=void 0,this.name_=void 0,this[z]=fr,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=r,this.name_=n,b(Map)||e(18),this.keysAtom_=$("ObservableMap.keys()"),this.data_=new Map,this.hasMap_=new Map,this.merge(t)}var r=t.prototype;return r.has_=function(e){return this.data_.has(e)},r.has=function(e){var t=this;if(!et.trackingDerivation)return this.has_(e);var r=this.hasMap_.get(e);if(!r){var n=r=new Ve(this.has_(e),G,"ObservableMap.key?",!1);this.hasMap_.set(e,n),Pt(n,(function(){return t.hasMap_.delete(e)}))}return r.get()},r.set=function(e,t){var r=this.has_(e);if(Gt(this)){var n=qt(this,{type:r?Zt:pr,object:this,newValue:t,name:e});if(!n)return this;t=n.newValue}return r?this.updateValue_(e,t):this.addValue_(e,t),this},r.delete=function(e){var t=this;if((this.keysAtom_,Gt(this))&&!qt(this,{type:"delete",object:this,name:e}))return!1;if(this.has_(e)){var r=Wt(this),n=r?{observableKind:"map",debugObjectName:this.name_,type:"delete",object:this,oldValue:this.data_.get(e).value_,name:e}:null;return $t((function(){t.keysAtom_.reportChanged(),t.updateHasMapEntry_(e,!1),t.data_.get(e).setNewValue_(void 0),t.data_.delete(e)})),r&&Qt(this,n),!0}return!1},r.updateHasMapEntry_=function(e,t){var r=this.hasMap_.get(e);r&&r.setNewValue_(t)},r.updateValue_=function(e,t){var r=this.data_.get(e);if((t=r.prepareNewValue_(t))!==et.UNCHANGED){var n=Wt(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:Zt,object:this,oldValue:r.value_,name:e,newValue:t}:null;r.setNewValue_(t),n&&Qt(this,i)}},r.addValue_=function(e,t){var r=this;this.keysAtom_,$t((function(){var n=new Ve(t,r.enhancer_,"ObservableMap.key",!1);r.data_.set(e,n),t=n.value_,r.updateHasMapEntry_(e,!0),r.keysAtom_.reportChanged()}));var n=Wt(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:pr,object:this,name:e,newValue:t}:null;n&&Qt(this,i)},r.get=function(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)},r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.keys=function(){return this.keysAtom_.reportObserved(),this.data_.keys()},r.values=function(){var e=this,t=this.keys();return $r({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:e.get(i)}}})},r.entries=function(){var e=this,t=this.keys();return $r({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:[i,e.get(i)]}}})},r[sr]=function(){return this.entries()},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value,o=i[0],a=i[1];e.call(t,a,o,this)}},r.merge=function(t){var r=this;return vr(t)&&(t=new Map(t)),$t((function(){y(t)?function(e){var t=Object.keys(e);if(!P)return t;var r=Object.getOwnPropertySymbols(e);return r.length?[].concat(t,r.filter((function(t){return a.propertyIsEnumerable.call(e,t)}))):t}(t).forEach((function(e){return r.set(e,t[e])})):Array.isArray(t)?t.forEach((function(e){var t=e[0],n=e[1];return r.set(t,n)})):O(t)?(t.constructor!==Map&&e(19,t),t.forEach((function(e,t){return r.set(t,e)}))):null!=t&&e(20,t)})),this},r.clear=function(){var e=this;$t((function(){Ke((function(){for(var t,r=V(e.keys());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.replace=function(t){var r=this;return $t((function(){for(var n,i=function(t){if(O(t)||vr(t))return t;if(Array.isArray(t))return new Map(t);if(y(t)){var r=new Map;for(var n in t)r.set(n,t[n]);return r}return e(21,t)}(t),o=new Map,a=!1,s=V(r.data_.keys());!(n=s()).done;){var u=n.value;if(!i.has(u))if(r.delete(u))a=!0;else{var c=r.data_.get(u);o.set(u,c)}}for(var l,f=V(i.entries());!(l=f()).done;){var p=l.value,h=p[0],b=p[1],d=r.data_.has(h);if(r.set(h,b),r.data_.has(h)){var v=r.data_.get(h);o.set(h,v),d||(a=!0)}}if(!a)if(r.data_.size!==o.size)r.keysAtom_.reportChanged();else for(var g=r.data_.keys(),m=o.keys(),_=g.next(),w=m.next();!_.done;){if(_.value!==w.value){r.keysAtom_.reportChanged();break}_=g.next(),w=m.next()}r.data_=o})),this},r.toString=function(){return"[object ObservableMap]"},r.toJSON=function(){return Array.from(this)},r.observe_=function(e,t){return Yt(this,e)},r.intercept_=function(e){return Kt(this,e)},I(t,[{key:"size",get:function(){return this.keysAtom_.reportObserved(),this.data_.size}},{key:ur,get:function(){return"Map"}}]),t}(),vr=w("ObservableMap",dr);var yr={};hr=Symbol.iterator,br=Symbol.toStringTag;var gr=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableSet"),this.name_=void 0,this[z]=yr,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,b(Set)||e(22),this.atom_=$(this.name_),this.enhancer_=function(e,t){return r(e,t,n)},t&&this.replace(t)}var r=t.prototype;return r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.clear=function(){var e=this;$t((function(){Ke((function(){for(var t,r=V(e.data_.values());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value;e.call(t,i,i,this)}},r.add=function(e){var t=this;if((this.atom_,Gt(this))&&!qt(this,{type:pr,object:this,newValue:e}))return this;if(!this.has(e)){$t((function(){t.data_.add(t.enhancer_(e,void 0)),t.atom_.reportChanged()}));var r=Wt(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:pr,object:this,newValue:e}:null;r&&Qt(this,n)}return this},r.delete=function(e){var t=this;if(Gt(this)&&!qt(this,{type:"delete",object:this,oldValue:e}))return!1;if(this.has(e)){var r=Wt(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:"delete",object:this,oldValue:e}:null;return $t((function(){t.atom_.reportChanged(),t.data_.delete(e)})),r&&Qt(this,n),!0}return!1},r.has=function(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))},r.entries=function(){var e=0,t=Array.from(this.keys()),r=Array.from(this.values());return $r({next:function(){var n=e;return e+=1,nTr){for(var t=Tr;t=0&&r++}e=Lr(e),t=Lr(t);var s="[object Array]"===a;if(!s){if("object"!=typeof e||"object"!=typeof t)return!1;var u=e.constructor,c=t.constructor;if(u!==c&&!(b(u)&&u instanceof u&&b(c)&&c instanceof c)&&"constructor"in e&&"constructor"in t)return!1}if(0===r)return!1;r<0&&(r=-1),i=i||[];for(var l=(n=n||[]).length;l--;)if(n[l]===e)return i[l]===t;if(n.push(e),i.push(t),s){if((l=e.length)!==t.length)return!1;for(;l--;)if(!Fr(e[l],t[l],r-1,n,i))return!1}else{var f,p=Object.keys(e);if(l=p.length,Object.keys(t).length!==l)return!1;for(;l--;)if(!x(t,f=p[l])||!Fr(e[f],t[f],r-1,n,i))return!1}return n.pop(),i.pop(),!0}function Lr(e){return lr(e)?e.slice():O(e)||vr(e)||j(e)||mr(e)?Array.from(e.entries()):e}function $r(e){return e[Symbol.iterator]=Hr,e}function Hr(){return this}["Symbol","Map","Set","Symbol"].forEach((function(t){void 0===r()[t]&&e("MobX requires global '"+t+"' to be available or polyfilled")})),"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:function(e){return console.warn("[mobx.spy] Is a no-op in production builds"),function(){}},extras:{getDebugName:Ur},$mobx:z});var Br;!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(Br||(Br={})); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. -/** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */ -function tap(nextOrObserver, error, complete) { - return function tapOperatorFunction(source) { - return source.lift(new DoOperator(nextOrObserver, error, complete)); - }; -} -var DoOperator = /*@__PURE__*/ (function () { - function DoOperator(nextOrObserver, error, complete) { - this.nextOrObserver = nextOrObserver; - this.error = error; - this.complete = complete; - } - DoOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); - }; - return DoOperator; -}()); -var TapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(TapSubscriber, _super); - function TapSubscriber(destination, observerOrNext, error, complete) { - var _this = _super.call(this, destination) || this; - _this._tapNext = noop; - _this._tapError = noop; - _this._tapComplete = noop; - _this._tapError = error || noop; - _this._tapComplete = complete || noop; - if (isFunction$1(observerOrNext)) { - _this._context = _this; - _this._tapNext = observerOrNext; - } - else if (observerOrNext) { - _this._context = observerOrNext; - _this._tapNext = observerOrNext.next || noop; - _this._tapError = observerOrNext.error || noop; - _this._tapComplete = observerOrNext.complete || noop; - } - return _this; - } - TapSubscriber.prototype._next = function (value) { - try { - this._tapNext.call(this._context, value); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(value); - }; - TapSubscriber.prototype._error = function (err) { - try { - this._tapError.call(this._context, err); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.error(err); - }; - TapSubscriber.prototype._complete = function () { - try { - this._tapComplete.call(this._context); - } - catch (err) { - this.destination.error(err); - return; - } - return this.destination.complete(); - }; - return TapSubscriber; -}(Subscriber)); +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +var Gr=function(e,t){return(Gr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function Kr(e,t){function r(){this.constructor=e}Gr(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var qr=function(){return(qr=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Yr(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function Qr(){for(var e=[],t=0;t";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==En.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeCreation()}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseAboutToDie()}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.fireInternalHook(e)}}),t}(tn);rn.prototype.die=yt(rn.prototype.die);var nn,on,an=1,sn={onError:function(e){throw e}},un=function(e){function t(t,r,n,i,o){var a=e.call(this,t,r,n,i)||this;if(Object.defineProperty(a,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:++an}),Object.defineProperty(a,"identifierAttribute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"unnormalizedIdentifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifierCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"isProtectionEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applyPatches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applySnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_autoUnbox",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"_isRunningAction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_hasSnapshotReaction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_observableInstanceState",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(a,"_childNodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_initialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshotCreated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_snapshotComputed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_snapshotUponDeath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_internalEvents",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),a._snapshotComputed=Pe((function(){return a.getSnapshot()})),a.unbox=a.unbox.bind(a),a._initialSnapshot=o,a.identifierAttribute=t.identifierAttribute,r||(a.identifierCache=new In),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 u=a._childNodes[a.identifierAttribute];u&&(s=u.value)}if("string"!=typeof s&&"number"!=typeof s)throw Hn("Instance identifier '"+a.identifierAttribute+"' for type '"+a.type.name+"' must be a string or a number");a.identifier=to(s),a.unnormalizedIdentifier=s}return r?r.root.identifierCache.addNodeToCache(a):a.identifierCache.addNodeToCache(a),a}return Kr(t,e),Object.defineProperty(t.prototype,"applyPatches",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)}}),Object.defineProperty(t.prototype,"createObservableInstanceIfNeeded",{enumerable:!1,configurable:!0,writable:!0,value:function(){0===this._observableInstanceState&&this.createObservableInstance()}}),Object.defineProperty(t.prototype,"createObservableInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e,t;this._observableInstanceState=1;for(var r=[],n=this.parent;n&&0===n._observableInstanceState;)r.unshift(n),n=n.parent;try{for(var i=Wr(r),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=En.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,this._snapshotComputed.trackAndCompute(),this.isRoot&&this._addSnapshotReaction(),this._childNodes=Ln,this.state=En.CREATED,this.fireHook(Br.afterCreate),this.finalizeCreation()}}),Object.defineProperty(t.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearParent",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.parent){this.fireHook(Br.beforeDetach);var e=this.state;this.state=En.DETACHING;var t=this.root,r=t.environment,n=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=r,this.identifierCache=n}finally{this.state=e}}}}),Object.defineProperty(t.prototype,"setParent",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e!==this.parent,n=t!==this.subpath;(r||n)&&(r?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(Br.afterAttach)):n&&this.baseSetParent(this.parent,t))}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;this.fireInternalHook(e);var r=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof r&&(mt?mt((function(){r.apply(t.storedValue)})):r.apply(this.storedValue))}}),Object.defineProperty(t.prototype,"snapshot",{get:function(){return this._snapshotComputed.get()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath}}),Object.defineProperty(t.prototype,"_getActualSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.type.getSnapshot(this)}}),Object.defineProperty(t.prototype,"_getCachedInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this._cachedInitialSnapshotCreated){var e=this.type,t=this._childNodes,r=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,r),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot}}),Object.defineProperty(t.prototype,"isRunningAction",{enumerable:!1,configurable:!0,writable:!0,value:function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()}}),Object.defineProperty(t.prototype,"assertAlive",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t;if(!this.isAlive){var r=this._getAssertAliveError(e);t=r,console.warn(new Error("[mobx-state-tree] "+t))}}}),Object.defineProperty(t.prototype,"_getAssertAliveError",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",r=e.subpath&&ii(e.subpath)||"",n=e.actionContext||bn;n&&"action"!==n.type&&n.parentActionEvent&&(n=n.parentActionEvent);var i="";n&&null!=n.name&&(i=(n&&n.context&&Nn(n.context).path||t)+"."+n.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: '"+r+"', Action: '"+i+"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value: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}}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.assertAlive(Ln),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):Mn(this._childNodes)}finally{this._autoUnbox=!0}}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.type.getChildType(e)}}),Object.defineProperty(t.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"assertWritable",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw Hn("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.type.removeChild(this,e)}}),Object.defineProperty(t.prototype,"unbox",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e}}),Object.defineProperty(t.prototype,"toString",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this.baseFinalizeCreation((function(){var t,r;try{for(var n=Wr(e.getChildren()),i=n.next();!i.done;i=n.next()){i.value.finalizeCreation()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}e.fireInternalHook(Br.afterCreationFinalization)}))}}),Object.defineProperty(t.prototype,"detach",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this.isAlive)throw Hn("Error while detaching, node is not alive.");this.clearParent()}}),Object.defineProperty(t.prototype,"preboot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this._applyPatches=mn(this.storedValue,"@APPLY_PATCHES",(function(t){t.forEach((function(t){if(t.path){var r=function(e){var t=e.split("/").map(oi);if(!(""===e||"."===e||".."===e||ti(e,"/")||ti(e,"./")||ti(e,"../")))throw Hn("a json path must be either rooted, empty or relative, but got '"+e+"'");""===t[0]&&t.shift();return t}(t.path);Un(e,r.slice(0,-1)).applyPatchLocally(r[r.length-1],t)}else e.type.applySnapshot(e,t.value)}))})),this._applySnapshot=mn(this.storedValue,"@APPLY_SNAPSHOT",(function(t){if(t!==e.snapshot)return e.type.applySnapshot(e,t)})),Xn(this.storedValue,"$treenode",this),Xn(this.storedValue,"toJSON",Rn)}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==En.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){0!==this._observableInstanceState&&(this.getChildren().forEach((function(e){e.aboutToDie()})),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.getChildren().forEach((function(e){e.finalizeDeath()})),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"onSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)}}),Object.defineProperty(t.prototype,"emitSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this._internalEventsEmit("snapshot",e)}}),Object.defineProperty(t.prototype,"onPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._internalEventsRegister("patch",e)}}),Object.defineProperty(t.prototype,"emitPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._internalEventsHasSubscribers("patch")){var r=Yr(function(e){if(!("oldValue"in e))throw Hn("Patches without `oldValue` field cannot be inversed");return[ri(e),ni(e)]}(function(e){for(var t=[],r=1;r=0&&this.middlewares.splice(t,1)}}}),Object.defineProperty(t.prototype,"addMiddleWare",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;void 0===t&&(t=!0);var n={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(n):this.middlewares=[n],function(){r.removeMiddleware(n)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)}}),Object.defineProperty(t.prototype,"_addSnapshotReaction",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;if(!this._hasSnapshotReaction){var t=jt((function(){return e.snapshot}),(function(t){return e.emitSnapshot(t)}),sn);this.addDisposer(t),this._hasSnapshotReaction=!0}}}),Object.defineProperty(t.prototype,"_internalEventsHasSubscribers",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)}}),Object.defineProperty(t.prototype,"_internalEventsRegister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){return void 0===r&&(r=!1),this._internalEvents||(this._internalEvents=new Jn),this._internalEvents.register(e,t,r)}}),Object.defineProperty(t.prototype,"_internalEventsHas",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsUnregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsEmit",{enumerable:!1,configurable:!0,writable:!0,value:function(e){for(var t,r=[],n=1;n0},enumerable:!1,configurable:!0})}();var bn,dn=1;function vn(){return dn++}function yn(e,t){var r=Nn(e.context);"action"===e.type&&r.assertAlive({actionContext:e});var n=r._isRunningAction;r._isRunningAction=!0;var i=bn;bn=e;try{return function(e,t,r){var n=new _n(e,r);if(n.isEmpty)return yt(r).apply(null,t.args);var i=null;function o(e){var t=n.getNextMiddleware(),a=t&&t.handler;if(!a)return yt(r).apply(null,e.args);if(!t.includeHooks&&Br[e.name])return o(e);function s(e,t){i=o(e),t&&(i=t(i))}function u(e){i=e}return a(e,s,u),i}return o(t)}(r,e,t)}finally{bn=i,r._isRunningAction=n}}function gn(e){if(e)return"action"===e.type?e:e.parentActionEvent}function mn(e,t,r){var n=function(){var n=vn(),i=bn,o=gn(i);return yn({type:"action",name:t,id:n,args:ei(arguments),context:e,tree:en(e),rootId:i?i.rootId:n,parentId:i?i.id:0,allParentIds:i?Qr(i.allParentIds,[i.id]):[],parentEvent:i,parentActionEvent:o},r)};return n._isMSTAction=!0,n}var _n=function(){function e(e,t){Object.defineProperty(this,"arrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"inArrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:[]}),t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);for(var r=e;r;)r.middlewares&&this.middlewares.push(r.middlewares),r=r.parent}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return this.middlewares.length<=0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"getNextMiddleware",{enumerable:!1,configurable:!0,writable:!0,value: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 wn(e){return"function"==typeof e?"":Dn(e)?"<"+e+">":"`"+function(e){try{return JSON.stringify(e)}catch(e){return""}}(e)+"`"}function On(e){var t=e.value,r=e.context[e.context.length-1].type,n=e.context.map((function(e){return e.path})).filter((function(e){return e.length>0})).join("/"),i=n.length>0?'at path "/'+n+'" ':"",o=Dn(t)?"value of type "+Nn(t).type.name+":":Qn(t)?"value":"snapshot",a=r&&Dn(t)&&r.is(Nn(t).snapshot);return""+i+o+" "+wn(t)+" is not assignable "+(r?"to type: `"+r.name+"`":"")+(e.message?" ("+e.message+")":"")+(r?function(e){return hn(e)&&(e.flags&(on.String|on.Number|on.Integer|on.Boolean|on.Date))>0}(r)||Qn(t)?".":", expected an instance of `"+r.name+"` or a snapshot like `"+r.describe()+"` instead."+(a?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".")}function jn(e,t,r){return e.concat([{path:t,type:r}])}function Pn(){return Fn}function Sn(e,t,r){return[{context:e,value:t,message:r}]}function An(e){return e.reduce((function(e,t){return e.concat(t)}),[])}function xn(e,t){"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK&&function(e,t){var r=e.validate(t,[{path:"",type:e}]);if(r.length>0)throw Hn(function(e,t,r){if(0===r.length)return;return"Error while converting "+(n=wn(t),(n.length<280?n:n.substring(0,272)+"......"+n.substring(n.length-8))+" to `")+e.name+"`:\n\n "+r.map(On).join("\n ");var n}(e,t,r))}(e,t)}var En,Tn=0,In=function(){function t(){Object.defineProperty(this,"cacheId",{enumerable:!0,configurable:!0,writable:!0,value:Tn++}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:we.map()}),Object.defineProperty(this,"lastCacheModificationPerId",{enumerable:!0,configurable:!0,writable:!0,value:we.map()})}return Object.defineProperty(t.prototype,"updateLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)}}),Object.defineProperty(t.prototype,"getLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t}}),Object.defineProperty(t.prototype,"addNodeToCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var r=e.identifier;this.cache.has(r)||this.cache.set(r,we.array([],$n));var n=this.cache.get(r);if(-1!==n.indexOf(e))throw Hn("Already registered");n.push(e),t&&this.updateLastCacheModificationPerId(r)}}}),Object.defineProperty(t.prototype,"mergeCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;Ut(e.identifierCache.cache).forEach((function(e){return e.forEach((function(e){t.addNodeToCache(e)}))}))}}),Object.defineProperty(t.prototype,"notifyDied",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.identifierAttribute){var t=e.identifier,r=this.cache.get(t);r&&(r.remove(e),r.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}}}),Object.defineProperty(t.prototype,"splitCache",{enumerable:!1,configurable:!0,writable:!0,value:function(r){var n,i=this,o=new t,a=r.path;return(n=this.cache,Sr(n)?Rt(n).map((function(e){return[e,n[e]]})):vr(n)?Rt(n).map((function(e){return[e,n.get(e)]})):mr(n)?Array.from(n.entries()):lr(n)?n.map((function(e,t){return[t,e]})):void e(7)).forEach((function(e){for(var t=Yr(e,2),r=t[0],n=t[1],s=!1,u=n.length-1;u>=0;u--)0===n[u].path.indexOf(a)&&(o.addNodeToCache(n[u],!1),n.splice(u,1),s=!0);s&&i.updateLastCacheModificationPerId(r)})),o}}),Object.defineProperty(t.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);return!!r&&r.some((function(t){return e.isAssignableFrom(t.type)}))}}),Object.defineProperty(t.prototype,"resolve",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);if(!r)return null;var n=r.filter((function(t){return e.isAssignableFrom(t.type)}));switch(n.length){case 0:return null;case 1:return n[0];default:throw Hn("Cannot resolve a reference to type '"+e.name+"' with id: '"+t+"' unambigously, there are multiple candidates: "+n.map((function(e){return e.path})).join(", "))}}}),t}();function Cn(e,t,r,n,i){var o=Vn(i);if(o){if(o.parent)throw Hn("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:"")+"/"+r+"', but it lives already at '"+o.path+"'");return t&&o.setParent(t,r),o}return new un(e,t,r,n,i)}function kn(e,t,r,n,i){return new rn(e,t,r,n,i)}function Dn(e){return!(!e||!e.$treenode)}function Nn(e){if(!Dn(e))throw Hn("Value "+e+" is no MST Node");return e.$treenode}function Vn(e){return e&&e.$treenode||null}function Rn(){return Nn(this).snapshot}function Un(e,t,r){void 0===r&&(r=!0);for(var n=e,i=0;i0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"register",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return void 0===t&&(t=!1),t?this.handlers.unshift(e):this.handlers.push(e),function(){r.unregister(e)}}}),Object.defineProperty(e.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.handlers.indexOf(e)>=0}}),Object.defineProperty(e.prototype,"unregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}),Object.defineProperty(e.prototype,"clear",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.handlers.length=0}}),Object.defineProperty(e.prototype,"emit",{enumerable:!1,configurable:!0,writable:!0,value:function(){for(var e=[],t=0;t0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._determineIdentifierMode(),Cn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"_determineIdentifierMode",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.identifierMode===ui.UNKNOWN){var e=[];if(li(this._subType,e)){var t=void 0;e.forEach((function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw Hn("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=ui.YES,this.mapIdentifierAttribute=t):this.identifierMode=ui.NO}}}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t={});var r=e.type._subType,n={};return Object.keys(t).forEach((function(i){n[i]=r.instantiate(e,i,void 0,t[i])})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return new fi(e)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Dt(t,e.unbox),e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=mn(t,e,n);Xn(t,e,i)}))})),Nt(t,this.willChange),Ft(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"Map"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Ut(e.storedValue)}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e.storedValue.get(""+t);if(!r)throw Hn("Not a child "+t);return r}}),Object.defineProperty(t.prototype,"willChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Nn(e.object),r=e.name;t.assertWritable({subpath:r});var n=t.type,i=n._subType;switch(e.type){case"update":var o=e.newValue;if(o===e.object.get(r))return null;xn(i,o),e.newValue=i.reconcile(t.getChildNode(r),e.newValue,t,r),n.processIdentifier(r,e.newValue);break;case"add":xn(i,e.newValue),e.newValue=i.instantiate(t,r,void 0,e.newValue),n.processIdentifier(r,e.newValue)}return e}}),Object.defineProperty(t.prototype,"processIdentifier",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.identifierMode===ui.YES&&t instanceof un){var r=t.identifier;if(r!==e)throw Hn("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '"+r+"', but expected: '"+e+"'")}}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return e.getChildren().forEach((function(e){t[e.subpath]=e.snapshot})),t}}),Object.defineProperty(t.prototype,"processInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return Object.keys(e).forEach((function(r){t[r]=e[r].getSnapshot()})),t}}),Object.defineProperty(t.prototype,"didChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Nn(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:ii(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:ii(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":var r=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:ii(e.name),oldValue:r},t)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=e.storedValue;switch(r.op){case"add":case"replace":n.set(t,r.value);break;case"remove":n.delete(t)}}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){xn(this,t);var r=e.storedValue,n={};if(Array.from(r.keys()).forEach((function(e){n[e]=!1})),t)for(var i in t)r.set(i,t[i]),n[""+i]=!0;Object.keys(n).forEach((function(e){!1===n[e]&&r.delete(e)}))}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return Wn(e)?An(Object.keys(e).map((function(n){return r._subType.validate(e[n],jn(t,n,r._subType))}))):Sn(t,e,"Value is not a plain object")}}),Object.defineProperty(t.prototype,"getDefaultSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return Ln}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){e.storedValue.delete(t)}}),t}(fn);pi.prototype.applySnapshot=yt(pi.prototype.applySnapshot);var hi=function(e){function t(t,r,n){void 0===n&&(n=[]);var i=e.call(this,t)||this;return Object.defineProperty(i,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Array}),Object.defineProperty(i,"hookInitializers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),i.hookInitializers=n,i}return Kr(t,e),Object.defineProperty(t.prototype,"hooks",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var r=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return Cn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t=[]);var r=e.type._subType,n={};return t.forEach((function(t,i){var o=""+i;n[o]=r.instantiate(e,o,void 0,t)})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return we.array(Mn(e),$n)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Rr(t).dehancer=e.unbox,e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=mn(t,e,n);Xn(t,e,i)}))})),Nt(t,this.willChange),Ft(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType.describe()+"[]"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.slice()}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=Number(t);if(r=0;r--)t.emitPatch({op:"remove",path:""+(e.index+r),oldValue:e.removed[r].snapshot},t);for(r=0;r0)return r;var n=Dn(e)?Nn(e).snapshot:e;return this._predicate(n)?Pn():Sn(t,e,this._message(e))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(ln);var Di=function(e){function t(t,r,n){var i=e.call(this,t)||this;return Object.defineProperty(i,"_types",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"_dispatcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"_eager",{enumerable:!0,configurable:!0,writable:!0,value:!0}),n=qr({eager:!0,dispatcher:void 0},n),i._dispatcher=n.dispatcher,n.eager||(i._eager=!1),i}return Kr(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){var e=on.Union;return this._types.forEach((function(t){e|=t.flags})),e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._types.some((function(t){return t.isAssignableFrom(e)}))}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"("+this._types.map((function(e){return e.describe()})).join(" | ")+")"}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(n,void 0);if(!i)throw Hn("No matching type for union "+this.describe());return i.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(t,e.type);if(!i)throw Hn("No matching type for union "+this.describe());return i.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"determineType",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter((function(e){return e!==t})).find((function(t){return t.is(e)})):this._types.find((function(t){return t.is(e)}))}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);for(var r=[],n=0,i=0;i=0){var i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,r,i)}return this._subtype.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),r,n)}}),Object.defineProperty(t.prototype,"getDefaultInstanceOrSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&xn(this,e),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this.optionalValues.indexOf(e)>=0?Pn():this._subtype.validate(e,t)}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._subtype.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(ln);function Ri(e,t,r){return function(e,t){if("function"!=typeof t&&Dn(t))throw Hn("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}(0,t),new Vi(e,t,r||Ui)}var Ui=[void 0],Mi=Ri(xi,void 0),zi=Ri(Ai,null);function Fi(e){return Ni(e,Mi)}var Li=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"_definition",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n}return Kr(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return(this._subType?this._subType.flags:0)|on.Late},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSubType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(!this._subType){var t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw Hn("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e?e.name:""}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.getSubType(!1);return r?r.validate(e,t):Pn()}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e||"cannotDetermine"}}),t}(ln);var $i=function(e){function t(t){var r=e.call(this,t?"frozen("+t.name+")":"frozen")||this;return Object.defineProperty(r,"subType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Frozen}),r}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return""}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return kn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return function(e){return"function"!=typeof e}(e)?this.subType?this.subType.validate(e,t):Pn():Sn(t,e,"Value is not serializable and cannot be frozen")}}),t}(pn),Hi=new $i;var Bi=function(){function e(e,t){if(Object.defineProperty(this,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolvedReference",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),ro(e))this.identifier=e;else{if(!Dn(e))throw Hn("Can only store references to tree nodes or identifiers, got: '"+e+"'");var r=Nn(e);if(!r.identifierAttribute)throw Hn("Can only store references with a defined identifier attribute.");var n=r.unnormalizedIdentifier;if(null==n)throw Hn("Can only store references to tree nodes with a defined identifier.");this.identifier=n}}return Object.defineProperty(e.prototype,"updateResolvedReference",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=to(this.identifier),r=e.root,n=r.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==n){var i=this.targetType,o=r.identifierCache.resolve(i,t);if(!o)throw new Gi("[mobx-state-tree] Failed to resolve reference '"+this.identifier+"' to type '"+this.targetType.name+"' (from node: "+e.path+")");this.resolvedReference={node:o,lastCacheModification:n}}}}),Object.defineProperty(e.prototype,"resolvedValue",{get:function(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value},enumerable:!1,configurable:!0}),e}(),Gi=function(e){function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return Kr(t,e),t}(Error),Ki=function(e){function t(t,r){var n=e.call(this,"reference("+t.name+")")||this;return Object.defineProperty(n,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"onInvalidated",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Reference}),n}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.targetType.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return ro(e)?Pn():Sn(t,e,"Value is not a valid identifier, which is a string or a number")}}),Object.defineProperty(t.prototype,"fireInvalidated",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=t.parent;if(i&&i.isAlive){var o=i.storedValue;o&&this.onInvalidated({cause:e,parent:o,invalidTarget:n?n.storedValue:void 0,invalidId:r,replaceRef:function(e){Zr(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef:function(){!function(e){return hn(e)&&(e.flags&on.Object)>0}(i.type)?Zr(t.root.storedValue,{op:"remove",path:t.path}):this.replaceRef(void 0)}})}}}),Object.defineProperty(t.prototype,"addTargetNodeWatcher",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this,n=this.getValue(e);if(n){var i=Nn(n),o=function(n,o){var a=function(e){switch(e){case Br.beforeDestroy:return"destroy";case Br.beforeDetach:return"detach";default:return}}(o);a&&r.fireInvalidated(a,e,t,i)},a=i.registerHook(Br.beforeDetach,o),s=i.registerHook(Br.beforeDestroy,o);return function(){a(),s()}}}}),Object.defineProperty(t.prototype,"watchTargetNodeForInvalidations",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=this;if(this.onInvalidated){var i;e.registerHook(Br.beforeDestroy,(function(){i&&i()}));var o=function(o){i&&i();var a=e.parent,s=a&&a.storedValue;if(a&&a.isAlive&&s){(r?!!r.get(t,s):e.root.identifierCache.has(n.targetType,to(t)))?i=n.addTargetNodeWatcher(e,t):o||n.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===En.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(Br.afterCreationFinalization,(function(){e.parent&&e.parent.createObservableInstanceIfNeeded()})),e.registerHook(Br.afterAttach,(function(){o(!1)})))}}}),t}(pn),qi=function(e){function t(t,r){return e.call(this,t,r)||this}return Kr(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return e.storedValue.resolvedValue}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.identifier}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(n)?Nn(n).identifier:n,o=new Bi(n,this.targetType),a=kn(this,e,t,r,o);return o.node=a,this.watchTargetNodeForInvalidations(a,i,void 0),a}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!e.isDetaching&&e.type===this){var i=Dn(t),o=e.storedValue;if(!i&&o.identifier===t||i&&o.resolvedValue===t)return e.setParent(r,n),e}var a=this.instantiate(r,n,void 0,t);return e.die(),a}}),t}(Ki),Wi=function(e){function t(t,r,n){var i=e.call(this,t,n)||this;return Object.defineProperty(i,"options",{enumerable:!0,configurable:!0,writable:!0,value:r}),i}return Kr(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(n)?this.options.set(n,e?e.storedValue:null):n,o=kn(this,e,t,r,i);return this.watchTargetNodeForInvalidations(o,i,this.options),o}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Dn(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===i)return e.setParent(r,n),e;var o=this.instantiate(r,n,void 0,i);return e.die(),o}}),t}(Ki);function Yi(e,t){var r=t||void 0,n=t?t.onInvalidated:void 0;return r&&(r.get||r.set)?new Wi(e,{get:r.get,set:r.set},n):new qi(e,n)}var Qi=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"validType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Identifier}),n}return Kr(t,e),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!(e&&e.type instanceof _i))throw Hn("Identifier types can only be instantiated as direct child of a model type");return kn(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(e.storedValue!==t)throw Hn("Tried to change identifier from '"+e.storedValue+"' to '"+t+"'. Changing identifiers is not allowed.");return e.setParent(r,n),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return typeof e!==this.validType?Sn(t,e,"Value is not a valid "+this.describe()+", expected a "+this.validType):Pn()}}),t}(pn),Xi=function(e){function t(){var t=e.call(this,"identifier","string")||this;return Object.defineProperty(t,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Identifier}),t}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifier"}}),t}(Qi),Zi=function(e){function t(){return e.call(this,"identifierNumber","number")||this}return Kr(t,e),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifierNumber"}}),t}(Qi),Ji=new Xi,eo=new Zi;function to(e){return""+e}function ro(e){return"string"==typeof e||"number"==typeof e}var no,io=function(e){function t(t){var r=e.call(this,t.name)||this;return Object.defineProperty(r,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:on.Custom}),r}return Kr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.options.isTargetType(e))return Pn();var r=this.options.getValidationMessage(e);return r?Sn(t,e,"Invalid value for type '"+this.name+"': "+r):Pn()}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.options.toSnapshot(e.storedValue)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return kn(this,e,t,r,this.options.isTargetType(n)?n:this.options.fromSnapshot(n,e&&e.root.environment))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=!this.options.isTargetType(t);if(!e.isDetaching&&(e.type===this&&(i?t===e.snapshot:t===e.storedValue)))return e.setParent(r,n),e;var o=i?this.options.fromSnapshot(t,r.root.environment):t,a=this.instantiate(r,n,void 0,o);return e.die(),a}}),t}(pn),oo={enumeration:function(e,t){var r="string"==typeof e?t:e,n=Ni.apply(void 0,Qr(r.map((function(e){return Ci(""+e)}))));return"string"==typeof e&&(n.name=e),n},model:function(){for(var e=[],t=0;t",e)},array:function(e){return new hi(e.name+"[]",e)},frozen:function(e){return 0===arguments.length?Hi:hn(e)?new $i(e):Ri(Hi,e)},identifier:Ji,identifierNumber:eo,late:function(e,t){var r="string"==typeof e?e:"late("+e.toString()+")";return new Li(r,"string"==typeof e?t:e)},undefined:xi,null:Ai,snapshotProcessor:function(e,t,r){return new si(e,t,r)}},ao=new Uint8Array(16);function so(){if(!no&&!(no="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return no(ao)}var uo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function co(e){return"string"==typeof e&&uo.test(e)}for(var lo=[],fo=0;fo<256;++fo)lo.push((fo+256).toString(16).substr(1));function po(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(lo[e[t+0]]+lo[e[t+1]]+lo[e[t+2]]+lo[e[t+3]]+"-"+lo[e[t+4]]+lo[e[t+5]]+"-"+lo[e[t+6]]+lo[e[t+7]]+"-"+lo[e[t+8]]+lo[e[t+9]]+"-"+lo[e[t+10]]+lo[e[t+11]]+lo[e[t+12]]+lo[e[t+13]]+lo[e[t+14]]+lo[e[t+15]]).toLowerCase();if(!co(r))throw TypeError("Stringified UUID is invalid");return r}function ho(e,t,r){var n=(e=e||{}).random||(e.rng||so)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return po(n)}function bo(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function vo(e,t){return e<>>32-t}var yo=function(e,t,r){function n(e,n,i,o){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}(n)),16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var a=new Uint8Array(16+e.length);if(a.set(n),a.set(e,n.length),(a=r(a))[6]=15&a[6]|t,a[8]=63&a[8]|128,i){o=o||0;for(var s=0;s<16;++s)i[o+s]=a[s];return i}return po(a)}try{n.name=e}catch(e){}return n.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",n.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",n}("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i>>0;m=g,g=y,y=vo(v,30)>>>0,v=d,d=O}r[0]=r[0]+d>>>0,r[1]=r[1]+v>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+g>>>0,r[4]=r[4]+m>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]})); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -/** - * EventHub 是一个事件处理中心,用于事件的接收与派发 - */ - -class EventHub { - all = new Map(); - constructor(eventMap = {}, bindThis = null) { - this.bindThis = bindThis || globalThis; - this.on(eventMap); - - // createSource$ 创建一个 rxjs 流的源头监听相应的事件 - this.createSource$ = memoize((eventName) => { - return fromEventPattern( - (handle) => this.on(eventName, handle), - (handle) => this.off(eventName, handle), - ).pipe(share()); - }); - } - - /** - * #on 是单个事件绑定函数,type 与 handle 函数一一对应 - */ - #on(type, handler) { - const handlers = this.all.get(type); - // ! 注意,栈的结构,这里要使用 unshift 将元素插入到头部,这样触发的时候才会最后执行最先声明的函数作为默认函数 - // 栈的结构可以保证 在 destroy 事件的时候,首先定义的 destroy 可以最后执行,保证后面绑定 destroy 事件的函数可以先触发,而在 destroy 的定义函数中可以最后 off('*') 解除事件 - handlers ? handlers.unshift(handler) : this.all.set(type, [handler]); - } - - /** - * on 函数重载,第一个参数可以为一个事件绑定对象, - * on({eventName: callback }) - * on({eventName: [callback] }) - * on(type,handle) - */ - on(type, handler) { - // 函数重载 - if (typeof type === 'string') { - this.#on(type, handler); - } else if (type instanceof Object) { - // 在直接赋值为一个 - Object.entries(type).forEach(([key, value]) => { - if (value instanceof Array) { - value.forEach((item) => this.#on(key, item)); - } else if (value instanceof Function) { - this.#on(key, value); - } - }); - } - } - - /** - * off 函数 type 设置为 '*' 时删除所有函数 - */ - off(type, handler) { - if (type === '*') { - return this.all.clear(); - } else { - const handlers = this.all.get(type); - if (handlers) { - return handler ? handlers.splice(handlers.indexOf(handler) >>> 0, 1) : this.all.set(type, []); - } - return false; - } - } - emit(type, ...eventParams) { - const handlers = this.all.get(type); - return handlers - ? handlers.map((handler) => { - return handler.apply(this.bindThis, eventParams); - }) - : []; - } -} - -class Task { - _belongTo = null; // 当有 TaskGroup 时,指向 Group - constructor(originData, spiderUUID) { - this.$EventHub = new EventHub({}, this); - // 由 store 验证相关的正确性 - this.$store = createTaskStore({ spiderUUID, originData }); - } - - // Plugin 的汇报口 - $commit(type, ...payload) { - // 遵循内先外后的函数触发 - - const result = this.$store[type](...payload); - this.$EventHub.emit(type, ...payload); - return result; - } - - // 外部系统的监控口 - $on(...args) { - return this.$EventHub.on(...args); - } - $off(...args) { - return this.$EventHub.off(...args); - } - $isSameTask(task) { - return task.$store.spiderUUID === this.$store.spiderUUID && task.$store.uuid === this.$store.uuid; - } - - $destroy() { - this._belongTo = null; - this.$commit('destroy'); // 先通知外部,该 Task 被销毁 - this.$EventHub.off('*'); // 后进行自身销毁 - } - get [Symbol.toStringTag]() { - return 'Task'; - } -} - /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -class TaskGroup extends Task { - constructor(TaskArray, spiderUUID = '00000') { - super({}, TaskArray?.[0]?.spiderUUID || spiderUUID); - this.member = new Set(TaskArray); - this.#linkTask(); - } - #linkTask() { - this.member.forEach((task) => { - task._belongTo = this; - task.$on('destroy', () => this.$removeLink(task)); - }); - } - - // 当第一次 start 的时候,返回的是完全不一样的 Task 的信息 - // 经过第一个 start 之后,所有 Task 中的数据被统一,这个标识改为 true - consume = false; - // Plugin 的汇报口 - $commit(type, ...payload) { - // 扩散事件 Set 类型不能 map - const result = []; - this.member.forEach((task) => result.push(task.$commit(type, ...payload))); - this.$EventHub.emit(type, ...payload); - - if (this.consume) return result[0]; - if (type === 'start') this.consume = true; - return result; - } - // 删除所有的 link - $destroy() { - this.$EventHub.emit('destroy'); // 不进行事件的扩散, 只是自身的报销的消息被传开 - this.$store.destroy(); - const tasks = this.member; - this.member = null; +const go=oo.enumeration("TaskState",["free","pending","complete","error","destroyed"]),mo={anyType:oo.custom({name:"any",fromSnapshot:e=>e,toSnapshot:e=>e,isTargetType:()=>!0,getValidationMessage:()=>""})},_o=oo.model({uuid:oo.string,spiderUUID:oo.string,dataSlide:oo.array(oo.string),dataSlideUUID:oo.string,createdAt:oo.Date,errorMessage:oo.optional(oo.string,""),status:go,updatedAt:oo.Date,originData:oo.maybe(mo.anyType),output:oo.maybe(mo.anyType)}).actions((e=>({$backup:()=>Jr(e),$import(e){return Nn(e).applySnapshot(t);var t},start(){if("pending"===e.status)throw new Error("Task 处在 pending 状态");return e.dataSlide=[],e.dataSlideUUID="",e.status="pending",e.output||e.originData},success(t,r){e.status="free",e.output=t,this._addUUIDToDataSlide(r)},complete(t){e.status="complete",this._addUUIDToDataSlide(t)},error(t="",r){e.status="error",e.errorMessage=t,this._addUUIDToDataSlide(r)},destroy(){var t;(t=Nn(e)).isRoot?t.die():t.parent.removeChild(t.subpath)},_addUUIDToDataSlide(t){t&&(e.dataSlide.push(t),e.dataSlideUUID=t)}})));function wo(e){return _o.create(function({spiderUUID:e,originData:t}){return{uuid:ho(),spiderUUID:e,createdAt:new Date,errorMessage:"",status:"free",updatedAt:new Date,dataSlideUUID:e,dataSlide:[],originData:t,output:null}}(e))} +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. - return tasks; - } - // 单独删除一个连接 - $removeLink(task) { - this.member.delete(task); - } - get [Symbol.toStringTag]() { - return 'TaskGroup'; - } -} +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */var Oo=function(e,t){return(Oo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function jo(e,t){function r(){this.constructor=e}Oo(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Po(e){return"function"==typeof e}var So=!1,Ao={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;So=e},get useDeprecatedSynchronousErrorHandling(){return So}};function xo(e){setTimeout((function(){throw e}),0)}var Eo={closed:!0,next:function(e){},error:function(e){if(Ao.useDeprecatedSynchronousErrorHandling)throw e;xo(e)},complete:function(){}},To=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function Io(e){return null!==e&&"object"==typeof e}var Co=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),ko=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var r=this,n=r._parentOrParents,i=r._ctorUnsubscribe,o=r._unsubscribe,a=r._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,n instanceof e)n.remove(this);else if(null!==n)for(var s=0;s1)this.connection=null;else{var r=this.connection,n=e._connection;this.connection=null,!n||r&&n!==r||n.unsubscribe()}}else this.connection=null},t}(Vo),Xo=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subjectFactory=r,n._refCount=0,n._isComplete=!1,n}return jo(t,e),t.prototype._subscribe=function(e){return this.getSubject().subscribe(e)},t.prototype.getSubject=function(){var e=this._subject;return e&&!e.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype.connect=function(){var e=this._connection;return e||(this._isComplete=!1,(e=this._connection=new ko).add(this.source.subscribe(new Jo(this.getSubject(),this))),e.closed&&(this._connection=null,e=ko.EMPTY)),e},t.prototype.refCount=function(){return Wo()(this)},t}(Lo),Zo=function(){var e=Xo.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:e._subscribe},_isComplete:{value:e._isComplete,writable:!0},getSubject:{value:e.getSubject},connect:{value:e.connect},refCount:{value:e.refCount}}}(),Jo=function(e){function t(t,r){var n=e.call(this,t)||this;return n.connectable=r,n}return jo(t,e),t.prototype._error=function(t){this._unsubscribe(),e.prototype._error.call(this,t)},t.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){var e=this.connectable;if(e){this.connectable=null;var t=e._connection;e._refCount=0,e._subject=null,e._connection=null,t&&t.unsubscribe()}},t}(Go),ea=function(e){function t(t,r){var n=e.call(this,t,r)||this;return n.scheduler=t,n.work=r,n.pending=!1,n}return jo(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var r=this.id,n=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(n,r,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(n,this.id,t),this},t.prototype.requestAsyncId=function(e,t,r){return void 0===r&&(r=0),setInterval(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,t,r){if(void 0===r&&(r=0),null!==r&&this.delay===r&&!1===this.pending)return t;clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,t);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var r=!1,n=void 0;try{this.work(e)}catch(e){r=!0,n=!!e&&e||new Error(e)}if(r)return this.unsubscribe(),n},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,r=t.actions,n=r.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==n&&r.splice(n,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,r){return e.call(this)||this}return jo(t,e),t.prototype.schedule=function(e,t){return this},t}(ko)),ta=function(){function e(t,r){void 0===r&&(r=e.now),this.SchedulerAction=t,this.now=r}return e.prototype.schedule=function(e,t,r){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(r,t)},e.now=function(){return Date.now()},e}(),ra=function(e){function t(r,n){void 0===n&&(n=ta.now);var i=e.call(this,r,(function(){return t.delegate&&t.delegate!==i?t.delegate.now():n()}))||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return jo(t,e),t.prototype.schedule=function(r,n,i){return void 0===n&&(n=0),t.delegate&&t.delegate!==this?t.delegate.schedule(r,n,i):e.prototype.schedule.call(this,r,n,i)},t.prototype.flush=function(e){var t=this.actions;if(this.active)t.push(e);else{var r;this.active=!0;do{if(r=e.execute(e.state,e.delay))break}while(e=t.shift());if(this.active=!1,r){for(;e=t.shift();)e.unsubscribe();throw r}}},t}(ta),na=new Lo((function(e){return e.complete()}));function ia(e){return e&&"function"==typeof e.schedule}var oa=function(e){return function(t){for(var r=0,n=e.length;r0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(Pa);function Ta(e,t,r){return r?Ta(e,t).pipe(fa((function(e){return To(e)?r.apply(void 0,e):r(e)}))):new Lo((function(r){var n,i=function(){for(var e=[],t=0;t=0}function Ca(e,t){return function(r){return r.lift(new ka(e,t))}}var ka=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Da(e,this.predicate,this.thisArg))},e}(),Da=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.predicate=r,i.thisArg=n,i.count=0,i}return jo(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(Vo);function Na(e,t,r){void 0===e&&(e=0);var n=-1;return Ia(t)?n=Number(t)<1?1:Number(t):ia(t)&&(r=t),ia(r)||(r=ca),new Lo((function(t){var i=Ia(e)?e:+e-r.now();return r.schedule(Va,i,{index:0,period:n,subscriber:t})}))}function Va(e){var t=e.index,r=e.period,n=e.subscriber;if(n.next(t),!n.closed){if(-1===r)return n.complete();e.index=t+1,this.schedule(e,r)}}var Ra="object"==typeof global&&global&&global.Object===Object&&global,Ua="object"==typeof self&&self&&self.Object===Object&&self,Ma=Ra||Ua||Function("return this")(),za=Ma.Symbol,Fa=Object.prototype,La=Fa.hasOwnProperty,$a=Fa.toString,Ha=za?za.toStringTag:void 0;var Ba=Object.prototype.toString;var Ga=za?za.toStringTag:void 0;function Ka(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Ga&&Ga in Object(e)?function(e){var t=La.call(e,Ha),r=e[Ha];try{e[Ha]=void 0;var n=!0}catch(e){}var i=$a.call(e);return n&&(t?e[Ha]=r:delete e[Ha]),i}(e):function(e){return Ba.call(e)}(e)}function qa(e){return null!=e&&"object"==typeof e}function Wa(e){return"symbol"==typeof e||qa(e)&&"[object Symbol]"==Ka(e)}function Ya(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r0){if(++gs>=800)return arguments[0]}else gs=0;return ys.apply(void 0,arguments)});function Os(e){return e!=e}function js(e,t){return!!(null==e?0:e.length)&&function(e,t,r){return t==t?function(e,t,r){for(var n=r-1,i=e.length;++n-1}var Ps=/^(?:0|[1-9]\d*)$/;function Ss(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&Ps.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}function ks(e){return qa(e)&&"[object Arguments]"==Ka(e)}var Ds=Object.prototype,Ns=Ds.hasOwnProperty,Vs=Ds.propertyIsEnumerable,Rs=ks(function(){return arguments}())?ks:function(e){return qa(e)&&Ns.call(e,"callee")&&!Vs.call(e,"callee")};function Us(e){return function(t){return e(t)}}var Ms="object"==typeof exports&&exports&&!exports.nodeType&&exports,zs=Ms&&"object"==typeof module&&module&&!module.nodeType&&module,Fs=zs&&zs.exports===Ms&&Ra.process,Ls=function(){try{var e=zs&&zs.require&&zs.require("util").types;return e||Fs&&Fs.binding&&Fs.binding("util")}catch(e){}}(),$s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Hs=/^\w*$/;var Bs=bs(Object,"create");var Gs=Object.prototype.hasOwnProperty;var Ks=Object.prototype.hasOwnProperty;function qs(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1},Qs.prototype.set=function(e,t){var r=this.__data__,n=Ws(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};var Xs=bs(Ma,"Map");function Zs(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function Js(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t0&&r(s)?t>1?lu(s,t-1,r,n,i):su(i,s):n||(i[i.length]=s)}return i}function fu(e){return(null==e?0:e.length)?lu(e,1):[]}function pu(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new Js;++t=200&&(o=hu,a=!1,t=new pu(t));e:for(;++i0;){var n=t.shift();r.next(n.buffer)}e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){this.contexts=null},t.prototype.onBufferFull=function(e){this.closeContext(e);var t=e.closeAction;if(t.unsubscribe(),this.remove(t),!this.closed&&this.timespanOnly){e=this.openContext();var r=this.bufferTimeSpan,n={subscriber:this,context:e,bufferTimeSpan:r};this.add(e.closeAction=this.scheduler.schedule(xu,r,n))}},t.prototype.openContext=function(){var e=new Su;return this.contexts.push(e),e},t.prototype.closeContext=function(e){this.destination.next(e.buffer);var t=this.contexts;(t?t.indexOf(e):-1)>=0&&t.splice(t.indexOf(e),1)},t}(Vo);function xu(e){var t=e.subscriber,r=e.context;r&&t.closeContext(r),t.closed||(e.context=t.openContext(),e.context.closeAction=this.schedule(e,e.bufferTimeSpan))}function Eu(e){var t=e.bufferCreationInterval,r=e.bufferTimeSpan,n=e.subscriber,i=e.scheduler,o=n.openContext();n.closed||(n.add(o.closeAction=i.schedule(Tu,r,{subscriber:n,context:o})),this.schedule(e,t))}function Tu(e){var t=e.subscriber,r=e.context;t.closeContext(r)}function Iu(e){return function(t){var r=new Cu(e),n=t.lift(r);return r.caught=n}}var Cu=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new ku(e,this.selector,this.caught))},e}(),ku=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.selector=r,i.caught=n,i}return jo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=void 0;try{r=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var n=new ja(this);this.add(n);var i=Sa(r,n);i!==n&&this.add(i)}},t}(Pa);function Du(e,t){return Aa(e,t,1)}function Nu(e,t){return t?function(r){return new Uu(r,t).lift(new Vu(e))}:function(t){return t.lift(new Vu(e))}}var Vu=function(){function e(e){this.delayDurationSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new Ru(e,this.delayDurationSelector))},e}(),Ru=function(e){function t(t,r){var n=e.call(this,t)||this;return n.delayDurationSelector=r,n.completed=!1,n.delayNotifierSubscriptions=[],n.index=0,n}return jo(t,e),t.prototype.notifyNext=function(e,t,r,n,i){this.destination.next(e),this.removeSubscription(i),this.tryComplete()},t.prototype.notifyError=function(e,t){this._error(e)},t.prototype.notifyComplete=function(e){var t=this.removeSubscription(e);t&&this.destination.next(t),this.tryComplete()},t.prototype._next=function(e){var t=this.index++;try{var r=this.delayDurationSelector(e,t);r&&this.tryDelay(r,e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){this.completed=!0,this.tryComplete(),this.unsubscribe()},t.prototype.removeSubscription=function(e){e.unsubscribe();var t=this.delayNotifierSubscriptions.indexOf(e);return-1!==t&&this.delayNotifierSubscriptions.splice(t,1),e.outerValue},t.prototype.tryDelay=function(e,t){var r=function(e,t,r,n,i){if(void 0===i&&(i=new da(e,r,n)),!i.closed)return t instanceof Lo?t.subscribe(i):_a(t)(i)}(this,e,t);r&&!r.closed&&(this.destination.add(r),this.delayNotifierSubscriptions.push(r))},t.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()},t}(ba),Uu=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subscriptionDelay=r,n}return jo(t,e),t.prototype._subscribe=function(e){this.subscriptionDelay.subscribe(new Mu(e,this.source))},t}(Lo),Mu=function(e){function t(t,r){var n=e.call(this)||this;return n.parent=t,n.source=r,n.sourceSubscribed=!1,n}return jo(t,e),t.prototype._next=function(e){this.subscribeToSource()},t.prototype._error=function(e){this.unsubscribe(),this.parent.error(e)},t.prototype._complete=function(){this.unsubscribe(),this.subscribeToSource()},t.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))},t}(Vo);var zu=function(){function e(e,t,r){void 0===r&&(r=!1),this.accumulator=e,this.seed=t,this.hasSeed=r}return e.prototype.call=function(e,t){return t.subscribe(new Fu(e,this.accumulator,this.seed,this.hasSeed))},e}(),Fu=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o.accumulator=r,o._seed=n,o.hasSeed=i,o.index=0,o}return jo(t,e),Object.defineProperty(t.prototype,"seed",{get:function(){return this._seed},set:function(e){this.hasSeed=!0,this._seed=e},enumerable:!0,configurable:!0}),t.prototype._next=function(e){if(this.hasSeed)return this._tryNext(e);this.seed=e,this.destination.next(e)},t.prototype._tryNext=function(e){var t,r=this.index++;try{t=this.accumulator(this.seed,e,r)}catch(e){this.destination.error(e)}this.seed=t,this.destination.next(t)},t}(Vo);var Lu=function(){function e(e,t){this.subjectFactory=e,this.selector=t}return e.prototype.call=function(e,t){var r=this.selector,n=this.subjectFactory(),i=r(n).subscribe(e);return i.add(t.subscribe(n)),i},e}();var $u=function(){function e(e,t){this.notifier=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new Hu(e,this.notifier,this.source))},e}(),Hu=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.notifier=r,i.source=n,i}return jo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=this.errors,n=this.retries,i=this.retriesSubscription;if(n)this.errors=void 0,this.retriesSubscription=void 0;else{r=new Ko;try{n=(0,this.notifier)(r)}catch(t){return e.prototype.error.call(this,t)}i=Sa(n,new ja(this))}this._unsubscribeAndRecycle(),this.errors=r,this.retries=n,this.retriesSubscription=i,r.next(t)}},t.prototype._unsubscribe=function(){var e=this.errors,t=this.retriesSubscription;e&&(e.unsubscribe(),this.errors=void 0),t&&(t.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},t.prototype.notifyNext=function(){var e=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=e,this.source.subscribe(this)},t}(Pa);function Bu(){return new Ko}function Gu(){return function(e){return Wo()((t=Bu,function(e){var n;if(n="function"==typeof t?t:function(){return t},"function"==typeof r)return e.lift(new Lu(n,r));var i=Object.create(e,Zo);return i.source=e,i.subjectFactory=n,i})(e));var t,r}}function Ku(e,t){return"function"==typeof t?function(r){return r.pipe(Ku((function(r,n){return Oa(e(r,n)).pipe(fa((function(e,i){return t(r,e,n,i)})))})))}:function(t){return t.lift(new qu(e))}}var qu=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new Wu(e,this.project))},e}(),Wu=function(e){function t(t,r){var n=e.call(this,t)||this;return n.project=r,n.index=0,n}return jo(t,e),t.prototype._next=function(e){var t,r=this.index++;try{t=this.project(e,r)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var r=new ja(this),n=this.destination;n.add(r),this.innerSubscription=Sa(e,r),this.innerSubscription!==r&&n.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(Pa);function Yu(e,t,r){return function(n){return n.lift(new Qu(e,t,r))}}var Qu=function(){function e(e,t,r){this.nextOrObserver=e,this.error=t,this.complete=r}return e.prototype.call=function(e,t){return t.subscribe(new Xu(e,this.nextOrObserver,this.error,this.complete))},e}(),Xu=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o._tapNext=la,o._tapError=la,o._tapComplete=la,o._tapError=n||la,o._tapComplete=i||la,Po(r)?(o._context=o,o._tapNext=r):r&&(o._context=r,o._tapNext=r.next||la,o._tapError=r.error||la,o._tapComplete=r.complete||la),o}return jo(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(Vo); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -/** - * Mirror 是 JSpider 中的数据外放接口 - * - * MessageHub 是集合所有事件的事件中心, - * 当 MessageHub 被 emit 时, MessageHub 发出相关的 Update 进行视图的更新 - * 所有的外放接口使用 rxjs 进行 subscribe - */ - -const MessageHub = new EventHub(); - -// 任何一个 Task 数据发生改变时 -const TaskUpdate = MessageHub.createSource$('TaskUpdate'); - -// ControlPanel 的状态发生改变 -/** - * ControlUpdate - * - * MessageHub.emit('ControlUpdate', payload); - * payload: { - * name:'your message token',// stateChange flowStart flowStop - * value:any, - * } - * - */ - -const ControlUpdate = MessageHub.createSource$('ControlUpdate'); - +class Zu{all=new Map;constructor(e={},t=null){this.bindThis=t||globalThis,this.on(e),this.createSource$=eu((e=>Ta((t=>this.on(e,t)),(t=>this.off(e,t))).pipe(Gu())))}#on(e,t){const r=this.all.get(e);r?r.unshift(t):this.all.set(e,[t])}on(e,t){"string"==typeof e?this.#on(e,t):e instanceof Object&&Object.entries(e).forEach((([e,t])=>{t instanceof Array?t.forEach((t=>this.#on(e,t))):t instanceof Function&&this.#on(e,t)}))}off(e,t){if("*"===e)return this.all.clear();{const r=this.all.get(e);return!!r&&(t?r.splice(r.indexOf(t)>>>0,1):this.all.set(e,[]))}}emit(e,...t){const r=this.all.get(e);return r?r.map((e=>e.apply(this.bindThis,t))):[]}}class Ju{_belongTo=null;constructor(e,t){this.$EventHub=new Zu({},this),this.$store=wo({spiderUUID:t,originData:e})}$commit(e,...t){const r=this.$store[e](...t);return this.$EventHub.emit(e,...t),r}$on(...e){return this.$EventHub.on(...e)}$off(...e){return this.$EventHub.off(...e)}$isSameTask(e){return e.$store.spiderUUID===this.$store.spiderUUID&&e.$store.uuid===this.$store.uuid}$destroy(){this._belongTo=null,this.$commit("destroy"),this.$EventHub.off("*")}get[Symbol.toStringTag](){return"Task"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -var staticEvent = { - // ! 即使这些函数不会被使用,也必须使用注释的方式写下 - stateChange(state) { - this.status = state; - MessageHub.emit('ControlUpdate', { - name: 'stateChange', - value: state, - }); - }, - 'Flow:stop'() { - this._stop = true; - MessageHub.emit('ControlUpdate', { - name: 'flowStop', - }); - }, - 'Flow:start'() { - console.log('jspider 开始运行'); - this.status = 'pending'; - this._stop = false; - MessageHub.emit('ControlUpdate', { - name: 'flowStart', - }); - }, - - // 'Flow:input'() {} - // 'Spider:clearFlow'(){} - 'Task:success'(task) { - task.$commit('complete'); - if (task instanceof TaskGroup) { - task.$destroy(); - } - MessageHub.emit('ControlUpdate', { - name: 'TaskSuccess', - }); - }, - 'Task:error'(error) { - console.log(error); - }, - // 'Flow:complete'() { - // console.log('线路完成'); - // }, -}; - + */class ec extends Ju{constructor(e,t="00000"){super({},e?.[0]?.spiderUUID||t),this.member=new Set(e),this.#linkTask()}#linkTask(){this.member.forEach((e=>{e._belongTo=this,e.$on("destroy",(()=>this.$removeLink(e)))}))}consume=!1;$commit(e,...t){const r=[];return this.member.forEach((n=>r.push(n.$commit(e,...t)))),this.$EventHub.emit(e,...t),this.consume?r[0]:("start"===e&&(this.consume=!0),r)}$destroy(){this.$EventHub.emit("destroy"),this.$store.destroy();const e=this.member;return this.member=null,e}$removeLink(e){this.member.delete(e)}get[Symbol.toStringTag](){return"TaskGroup"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -function bindUpdate() { - const backup = this.$store.$backup(); - - MessageHub.emit('TaskUpdate', backup); -} -// ! 用于维护全局 Task 数据的中心 -class TaskManager { - #Tasks = new Map(); // 用于维护所有的 Task - viewModel = []; // 这是放置所有的外部 Mirror 需要监听的对象 - - // 直接代理全局的 task 创建事件,TaskGroup 是不管的,因为 TaskGroup 具有编程场景临时性,一般在 plugin 阶段自己销毁 - // 这好比村长只管理村民人数和状况,但是不管理村民的组织 - createTask(data, pipelineUUID) { - const task = new Task(data, pipelineUUID); - this.#Tasks.set(task.uuid, task); - const that = this; - task.$on({ - start: bindUpdate, - success: bindUpdate, - complete: bindUpdate, - error: bindUpdate, - // 监听事件,并更新响应的 viewModel - destroy() { - that.#Tasks.delete(this.uuid); // this 绑定的是 task - }, - }); - - this.viewModel.push(task.$store); - return task; - } -} - + */const tc=new Zu,rc=tc.createSource$("TaskUpdate"),nc=tc.createSource$("ControlUpdate"); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -/** - * 函数用途描述 - * 这个是用于 async 函数队列 连续执行的函数,只要 enQueue 之后就会连续执行,直至完成 - */ -class functionQueue { - QueuePromise = Promise.resolve(); - enQueue(...args) { - this.QueuePromise = args.reduce((promise, current) => { - return promise.then(current); - }, this.QueuePromise); - return this; - } -} - +var ic={stateChange(e){this.status=e,tc.emit("ControlUpdate",{name:"stateChange",value:e})},"Flow:stop"(){this._stop=!0,tc.emit("ControlUpdate",{name:"flowStop"})},"Flow:start"(){console.log("jspider 开始运行"),this.status="pending",this._stop=!1,tc.emit("ControlUpdate",{name:"flowStart"})},"Task:success"(e){e.$commit("complete"),e instanceof ec&&e.$destroy(),tc.emit("ControlUpdate",{name:"TaskSuccess"})},"Task:error"(e){console.log(e)}}; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * pauseToggle - * @date 2021-07-20 - * @author KonghaYao - * @description 用于暂停的 operator, 改编自 bufferToggle 但也不同 - * @param {Observable} openings 发出时触发主流缓存 - * @param {Observable} closings 发出时放出缓存到主流 - * @return {function} - */ -function pauseToggle(openings, closings) { - return (observable) => - new Observable((subscriber) => { - const buffers = new Set(); - let closingSubscription = false; - const subscription = observable.subscribe( - (value) => { - closingSubscription ? buffers.add(value) : subscriber.next(value); - }, - noop, - () => { - buffers.forEach((item) => subscriber.next(item)); - subscriber.complete(); - }, - ); - const openingSubscription = openings.subscribe(() => { - // 输出所有的 buffer - const emitBuffer = () => { - buffers.forEach((item) => subscriber.next(item)); - buffers.clear(); - closingSubscription.unsubscribe(); - closingSubscription = false; - }; - closingSubscription = closings.subscribe(emitBuffer); - }); - return () => { - buffers.clear(); - subscription.unsubscribe(); - openingSubscription.unsubscribe(); - if (closingSubscription) closingSubscription.unsubscribe(); - }; - }); -} - + */function oc(){const e=this.$store.$backup();tc.emit("TaskUpdate",e)}class ac{#Tasks=new Map;viewModel=[];createTask(e,t){const r=new Ju(e,t);this.#Tasks.set(r.uuid,r);const n=this;return r.$on({start:oc,success:oc,complete:oc,error:oc,destroy(){n.#Tasks.delete(this.uuid)}}),this.viewModel.push(r.$store),r}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -function createUUID(string) { - return v5(string, v5.URL); -} - + */class sc{QueuePromise=Promise.resolve();enQueue(...e){return this.QueuePromise=e.reduce(((e,t)=>e.then(t)),this.QueuePromise),this}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -// Pipeline 是组合 Plugin 实例的工具类,用于创建一个可以不断提供 source 进行固定操作的功能对象。 -class Pipeline { - constructor(Plugins) { - this.Plugins = Plugins; - } - UUID = null; // 唯一的标识 - operator = null; // 组合起来的最终的 operator - pluginUUIDMap = new Map(); - - #PluginQueue = new functionQueue(); // 准备 Plugin 中的异步 init 事件 - preparePipeline() { - let uuidString = ''; - // ! 一次遍历实现取出 operator 和 导出 plugin init 函数的 promise 链,并延长 uuidString 用于创建 UUID - const pipeline = this.Plugins.map((plugin, index) => { - // main 属性和 operator 属性必须存在一个来保证能够生成 uuid - uuidString += (plugin?.main || plugin.operator).toString(); - - if (plugin.init instanceof Function) { - this.#PluginQueue.enQueue(plugin.init); - } - - // 需要注入 index 表示这个程序的位置 - plugin.initUUID(index); - - // 保存 uuid 的映射 - this.pluginUUIDMap.set(plugin.uuid, plugin?.name || plugin.uuid); - - // 将 plugin 中的 operator 注入 pipeline 中 - return plugin.operator(this); - }); - this.operator = pipe(...pipeline); - - this.UUID = createUUID(uuidString); - - return this.#PluginQueue.QueuePromise; - } -} - /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -// ControlPanel 是 JSpider 内部的事件和数据中心。 -// 全部 JSpider 涉及到的边界中,ControlPanel 只有一个,但是 View 可以有多个,而 Spider 就是 View 中的一个 -// 用于分发数据流,提供 Task 的状态变更。 -// TODO 并且可以提供数据的响应给类似于 UI 界面形成可视化 - -class ControlPanel$1 { - status = 'free'; // 'free' 'preparing' - #runningQueue = new functionQueue(); // 异步 Queue 队列 - _stop = false; // 用于直接切断 spiderSource$ 的流 - spiderSource$ = null; - _pipeline = null; - TaskManager = new TaskManager(); - constructor() { - this.$EventHub = new EventHub(staticEvent, this); - } - // ! 这是一个完整的流控 - _createLogicLine() { - this.spiderSource$ = this.$EventHub.createSource$('Flow:input').pipe( - pauseToggle( - this.$EventHub.createSource$('Flow:stop'), - - this.$EventHub.createSource$('Flow:start'), - ), - this._pipeline.operator, - ); - - this.spiderSource$.subscribe( - // 所有的事件分配到 staticEvent 中去写 - (task) => this.$EventHub.emit('Task:success', task), - (error) => this.$EventHub.emit('Task:error', error), - () => this.$EventHub.emit('Flow:complete'), - ); - this.$EventHub.emit('Flow:stop'); - } - - pipeline(...plugins) { - const pipeline = new Pipeline(plugins); - if (this.status === 'free') { - this.$EventHub.emit('stateChange', 'preparing'); - this._pipeline = pipeline; - this.#runningQueue.enQueue( - () => this._pipeline.preparePipeline(), - () => { - this.$EventHub.emit('Spider:clearFlow'); // 先注销流 - this._createLogicLine(); // 创建新流 - this.$EventHub.emit('stateChange', 'free'); - }, - ); - } else { - throw new Error('在运行阶段是不能够进行操作的哦'); - } - } - - // |startInfo| - TaskManager.createTask -> |Task| - emit EventHub -> |Flow| - createFlow(infos, { fromBackup = false } = {}) { - return this.#runningQueue.enQueue(() => { - infos.forEach((info) => { - if (!this._pipeline) throw new Error('没有创建pipeline'); - const task = this.TaskManager.createTask(info, this._pipeline.UUID); - if (fromBackup) task.$store.$import(info); - this.$EventHub.emit('Flow:input', task); - }); - }); - } - - startFlow() { - // 开始流必须要等待其他事件完成 - this.#runningQueue.enQueue(() => { - this.$EventHub.emit('Flow:start'); - }); - } - - stopFlow() { - // 关闭流不需要等待其他事件完成 - this.$EventHub.emit('Flow:stop'); - } -} - +function uc(e){return yo(e,yo.URL)} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -var ControlPanel = new ControlPanel$1(); - -// 注意,这里只要 View 被实例化了,它就会订阅数据 -class View { - constructor({ tasks = false, controlPanel = false } = {}) { - this.config = { - tasks, - controlPanel, - }; - - if (tasks) { - this.#subscriber.push(TaskUpdate.subscribe((data) => this._update(data))); - } - if (controlPanel) { - this.#subscriber.push(ControlUpdate.subscribe((data) => this._change(data))); - } - } - config = {}; - #subscriber = []; - $destroy() { - this.#subscriber.forEach((sub) => { - sub.unsubscribe(); - }); - } -} - -class ConsoleView extends View { - constructor(config) { - super(Object.assign(config, { tasks: true, controlPanel: true })); - } - tasks = []; - #uuidArray = []; - _update(data) { - const index = this.#uuidArray.indexOf(data.uuid); - if (index === -1) { - this.#uuidArray.push(data.uuid); - this.tasks.push(data); - } else { - // 并不是直接赋值,而是通过数组的 splice 方式进行数组的更新,这样可以方便 Vue 渲染 - this.tasks.splice(index, 1, data); - } - } - _change({ name, value = '' }) {} -} - + */class cc{constructor(e){this.Plugins=e}UUID=null;operator=null;pluginUUIDMap=new Map;#PluginQueue=new sc;preparePipeline(){let e="";const t=this.Plugins.map(((t,r)=>(e+=(t?.main||t.operator).toString(),t.init instanceof Function&&this.#PluginQueue.enQueue(t.init),t.initUUID(r),this.pluginUUIDMap.set(t.uuid,t?.name||t.uuid),t.operator(this))));return this.operator=zo(...t),this.UUID=uc(e),this.#PluginQueue.QueuePromise}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -// Spider 是一个 View -class Spider { - constructor({ logEvery = false } = {}) { - this.config = { - logEvery, - }; - this.views = new ConsoleView(this.config); - } - crawl(...args) { - ControlPanel.createFlow(args.flat()); - return this; - } - pipeline(...plugins) { - ControlPanel.pipeline(...plugins); - return this; - } - start() { - ControlPanel.startFlow(); - return this; - } - stop() { - ControlPanel.stopFlow(); - return this; - } -} - /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -// Plugin main 函数发生了错误 -class PluginError extends Error { - constructor(message) { - super(message); - this.name = 'PluginError'; - } -} - -// 重试的时候发生了错误 -class RetryError extends Error { - constructor(message) { - super(message); - this.name = 'FlowError'; - } -} - +var lc=new class{status="free";#runningQueue=new sc;_stop=!1;spiderSource$=null;_pipeline=null;TaskManager=new ac;constructor(){this.$EventHub=new Zu(ic,this)}_createLogicLine(){var e,t;this.spiderSource$=this.$EventHub.createSource$("Flow:input").pipe((e=this.$EventHub.createSource$("Flow:stop"),t=this.$EventHub.createSource$("Flow:start"),r=>new Lo((n=>{const i=new Set;let o=!1;const a=r.subscribe((e=>{o?i.add(e):n.next(e)}),la,(()=>{i.forEach((e=>n.next(e))),i.clear(),n.complete()})),s=e.subscribe((()=>{o=t.subscribe((()=>{i.forEach((e=>n.next(e))),i.clear(),o.unsubscribe(),o=!1}))}));return()=>{i.clear(),a.unsubscribe(),s.unsubscribe(),o&&o.unsubscribe()}}))),this._pipeline.operator),this.spiderSource$.subscribe((e=>this.$EventHub.emit("Task:success",e)),(e=>this.$EventHub.emit("Task:error",e)),(()=>this.$EventHub.emit("Flow:complete"))),this.$EventHub.emit("Flow:stop")}pipeline(...e){const t=new cc(e);if("free"!==this.status)throw new Error("在运行阶段是不能够进行操作的哦");this.$EventHub.emit("stateChange","preparing"),this._pipeline=t,this.#runningQueue.enQueue((()=>this._pipeline.preparePipeline()),(()=>{this.$EventHub.emit("Spider:clearFlow"),this._createLogicLine(),this.$EventHub.emit("stateChange","free")}))}createFlow(e,{fromBackup:t=!1}={}){return this.#runningQueue.enQueue((()=>{e.forEach((e=>{if(!this._pipeline)throw new Error("没有创建pipeline");const r=this.TaskManager.createTask(e,this._pipeline.UUID);t&&r.$store.$import(e),this.$EventHub.emit("Flow:input",r)}))}))}startFlow(){this.#runningQueue.enQueue((()=>{this.$EventHub.emit("Flow:start")}))}stopFlow(){this.$EventHub.emit("Flow:stop")}};class fc extends class{constructor({tasks:e=!1,controlPanel:t=!1}={}){this.config={tasks:e,controlPanel:t},e&&this.#subscriber.push(rc.subscribe((e=>this._update(e)))),t&&this.#subscriber.push(nc.subscribe((e=>this._change(e))))}config={};#subscriber=[];$destroy(){this.#subscriber.forEach((e=>{e.unsubscribe()}))}}{constructor(e){super(Object.assign(e,{tasks:!0,controlPanel:!0}))}tasks=[];#uuidArray=[];_update(e){const t=this.#uuidArray.indexOf(e.uuid);-1===t?(this.#uuidArray.push(e.uuid),this.tasks.push(e)):this.tasks.splice(t,1,e)}_change({name:e,value:t=""}){}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -class PLUGIN$1 { - constructor({ - forceRetry = true, - saveResult = false, - name = null, - main, - init = null, - error = null, - complete = null, - options = {}, - operator, - }) { - if (operator) this.operator = operator; - // 写入自身中 - Object.assign(this, { - name, // 名称,一般用作提示标记 - main, // Plugin 中的功能性函数 - init, // 初始化整个 Plugin 的函数 - error, // operator 错误时的事件,若返回 false 类的数据,将会中断流,返回正常数据会继续流 - complete, // 函数完成时的提示事件 - options, // main 函数接收的 options - saveResult, // 是否保存结果到每一个 Task 中 - forceRetry, // 是否强制重新使用 Plugin - }); - } - initUUID(index) { - this.uuid = createUUID((this?.main || this.operator).toString() + index); - } - // 对 main 函数外包一层,直接启动 main 函数的执行,返回一条流 - TaskStarter(task) { - return of(task).pipe( - // 设置跳过 Plugin 的逻辑 - switchMap((task) => { - return of(task).pipe( - map((task) => [task.$commit('start', this.uuid), task._originData]), - - switchMap(([data, originData]) => { - const result = this.main(data, originData); - return result instanceof Promise || result instanceof Observable ? from$1(result) : of(result); - }), - map((result) => { - task.$commit('success', result, this.uuid, this.saveResult); - return task; - }), - ); - }), - // 捕获到异常 - catchError((...args) => { - if (this.error instanceof Function) { - const afterError = this.error(task, ...args); - if (afterError) throw new PluginError(afterError); - - return EMPTY; - } - throw new PluginError(args[0]); - }), - // 完成 Plugin 时的事件 - tap((task) => this.complete && this.complete(task)), - ); - } - - operator(context) { - // ! 这个是默认的 operator 函数 - // context 为上层的 JSpider 实例 - return pipe(switchMap((task) => this.TaskStarter(task))); - } -} - -function Plugin$1(Process, otherOptions = {}) { - if (Process instanceof Function) { - return new PLUGIN$1( - Object.assign(otherOptions, { - main: Process, - }), - ); - } - if (Process instanceof Object) { - return new PLUGIN$1(Process); - } - throw new PluginError('Plugin 必须是一个函数或者是 Plugin 描述对象'); -} - /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -// delay 可以是一个函数用于产生数字 -const retryAndDelay = (count, delay) => - pipe( - retryWhen((err$) => - err$.pipe( - scan((errCount, err) => { - console.log('尝试次数', errCount, err); - if (errCount >= count) throw new RetryError('超出尝试次数', err); - return errCount + 1; - }, 0), - delayWhen((...args) => { - switch (typeof delay) { - case 'string': - case 'number': - return timer(parseInt(delay, 10)); - case 'function': - return timer(delay(...args)); - default: - throw new RetryError('您输入的 delay 错误'); - } - }), - ), - ), - ); - +class pc extends Error{constructor(e){super(e),this.name="PluginError"}}class hc extends Error{constructor(e){super(e),this.name="FlowError"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -function concurrent( - promiseFunc, // 并发的异步函数用于接收上流来的数据 - { - retry = 3, // 若发生失败时最大重试次数 - buffer = 3, // 每次并发处理的次数 - delay = 1000, // 每个分组之间的间隔 - retryDelay = 300, // 每次延迟的次数;与 retryAndDelay 相同的一个函数 - handleError = function handleError(err, err$) { - // 重试错误时的操作 - throw new Error(err, err$); - }, - } = {}, -) { - // 异步函数的处理工作 - const asyncSingle = (data) => - of(data).pipe( - mergeMap((res) => { - // mergeMap 可以直接将 Observable 或者是 Promise 转化为正常流 - return promiseFunc(res); - }), - retryAndDelay(retry, retryDelay), - catchError((...args) => { - // 自定义错误处理 - const clear = handleError instanceof Function ? handleError(...args) : handleError; - - return clear || EMPTY; // 通过 EMPTY 取消掉这个订阅 - }), - ); - - // 这是 concurrent 的核心逻辑 - return pipe( - // ! 这里的 bufferTime 的第二个参数保持 undefined 即可 - bufferTime(1000, undefined, buffer), - filter((i) => i.length), - // 无论如何每一组都会被推迟的时间量 - delayWhen((_, index) => timer(index * delay)), - mergeMap((array) => from$1(array)), - concatMap(asyncSingle), - ); -} - + */class bc{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=uc((this?.main||this.operator).toString()+e)}TaskStarter(e){return ua(e).pipe(Ku((e=>ua(e).pipe(fa((e=>[e.$commit("start",this.uuid),e._originData])),Ku((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Lo?Oa(r):ua(r)})),fa((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),Iu(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new pc(r);return na}throw new pc(t[0])})),Yu((e=>this.complete&&this.complete(e))))}operator(e){return zo(Ku((e=>this.TaskStarter(e))))}}function dc(e,t={}){if(e instanceof Function)return new bc(Object.assign(t,{main:e}));if(e instanceof Object)return new bc(e);throw new pc("Plugin 必须是一个函数或者是 Plugin 描述对象")} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -// ! 这个 Request 文件是标准的 Plugin 的高级注册示例 - -// Format 是边缘的处理逻辑,用于自动化相应返回数据的格式处理,与 Plugin 关系较小 -function Format(res, returnType) { - const type = res.headers.get('content-type') || ''; - // 根据 returnType 强制返回 - if (!returnType || returnType === 'auto') { - // 自动判断类型并解析 - if (/text|html|rtf|xml/.test(type)) { - return res.text(); - } - if (/json/.test(type)) { - return res.json(); - } - if (/arrayBuffer/.test(type)) { - return res.arrayBuffer(); - } - // 默认返回 Blob 数据 配合 node端 的buffer - return res.buffer ? res.buffer() : res.blob(); - } - if (returnType) { - return res[returnType](); - } - return res.json(); -} - -// Plugin 的核心函数 (this.main),用于请求 -// 第一参数为 Task 内部使用 start 事件返回的参数,你可以看成是上一个 Plugin 返回给你的数据 -// 第二个为 Plugin 内部的 options, 可以调用这些数据进行操作 - -function request({ url, options = {} }) { - const { returnType = 'json' } = this.options; - - // 获取数据为 request - console.log('- 爬取 ', url); - return fetch(url, options) - .then((res) => { - if (!res.ok) { - throw Error(res.statusText); - } - return Format(res, returnType); - }) - .then((res) => { - console.log(`${url} 爬取成功`); - return res; - }) - .catch((err) => { - throw err; - }); -} - -// 在超过重试次数时,进行的操作 -function HandleError(err) { - throw err; -} -function Request(options = {}) { - return Plugin$1({ - init() {}, // 在所有工作开始前会启动的函数,可以用于 Promise 加载一些 js 插件 - name: 'Request', // 这个 name 是负责进行监控的标志符号 - main: request, // 功能性的核心函数 - options, // 接收所有的参数,提供给所有函数使用 - - operator() { - // 复写 operator 函数,属于高级操作,可以操作到最顶层的数据流环节 - - // 通过 this.options 来获取传入的参数,这个参数解析都是由 Plugin 开发者来设置逻辑的 - // 所以灵活性很高 - const { delay = 200, buffer = 3, retry = 3, handleError = null } = this.options; - - return ($source) => - $source.pipe( - concurrent( - (task) => - // 注意此处的 TaskStarter 是 Plugin 内置的函数, - // 通过这个函数可以直接回应 Task - // 使得 Plugin 开发者 不用学 Task 相关知识, - // 而只是调用一下这个形式就可以了 - // TaskStarter 是用于间接调用 main 函数的 Wrapper 函数, - // 主要是对 Task 进行一些操作 - this.TaskStarter(task), - { - delay, - buffer, - retry, - handleError: handleError || HandleError, - }, - ), - ); - }, - }); -} - + */const vc=(e,t)=>{return zo((r=r=>r.pipe(function(e,t){var r=!1;return arguments.length>=2&&(r=!0),function(n){return n.lift(new zu(e,t,r))}}(((t,r)=>{if(console.log("尝试次数",t,r),t>=e)throw new hc("超出尝试次数",r);return t+1}),0),Nu(((...e)=>{switch(typeof t){case"string":case"number":return Na(parseInt(t,10));case"function":return Na(t(...e));default:throw new hc("您输入的 delay 错误")}}))),function(e){return e.lift(new $u(r,e))})); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -function toFile(data, name) { - if (data instanceof File) return data; - if (data instanceof Blob) { - data.name = name; - return data; - } - - return new File([JSON.stringify(data)], name); -} - + */var r};function yc(e,{retry:t=3,buffer:r=3,delay:n=1e3,retryDelay:i=300,handleError:o=function(e,t){throw new Error(e,t)}}={}){return zo(function(e){var t=arguments.length,r=ca;ia(arguments[arguments.length-1])&&(r=arguments[arguments.length-1],t--);var n=null;t>=2&&(n=arguments[1]);var i=Number.POSITIVE_INFINITY;return t>=3&&(i=arguments[2]),function(t){return t.lift(new Pu(e,n,i,r))}}(1e3,void 0,r),Ca((e=>e.length)),Nu(((e,t)=>Na(t*n))),Aa((e=>Oa(e))),Du((r=>ua(r).pipe(Aa((t=>e(t))),vc(t,i),Iu(((...e)=>(o instanceof Function?o(...e):o)||na))))))} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -// 在 浏览器中下载是不能够同时进行的,也就是说,如果前面的没有下载完,后面的又提交 -// 会导致后面的全部失效,所以设置 Promise 下载队列 -const DownloadQueue = { - main: Promise.resolve(true), - add(file) { - this.main.then(() => aDownload(file)); - }, -}; -// a 标签下载的方式貌似为同步模式(未验证) -const aDownload = function (file) { - const a = document.createElement('a'); - a.href = URL.createObjectURL(file); - a.download = file.name; - a.click(); - URL.revokeObjectURL(a.href); - a.remove(); - console.log('%c 下载完成', 'color:green'); -}; - -const download = (data, { DownloadFileName: name } = {}, originData) => { - const file = toFile(data, name || (typeof url === 'string' ? originData.url.replace(/[^\/]*?\//g, '') : '')); - DownloadQueue.add(file); - return null; -}; -const Download = function (options = {}) { - return Plugin$1({ - name: 'Download', - main: download, - options, - }); -}; - + */function gc({url:e,options:t={}}){const{returnType:r="json"}=this.options;return console.log("- 爬取 ",e),fetch(e,Object.assign({cache:"force-cache"},t)).then((e=>{if(!e.ok)throw Error(e.statusText);return function(e,t){const r=e.headers.get("content-type")||"";return t&&"auto"!==t?t?e[t]():e.json():/text|html|rtf|xml/.test(r)?e.text():/json/.test(r)?e.json():/arrayBuffer/.test(r)?e.arrayBuffer():e.buffer?e.buffer():e.blob()}(e,r)})).then((t=>(console.log(`${e} 爬取成功`),t))).catch((e=>{throw e}))}function mc(e){throw e} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -const loaderFunction = { - // 加载 js 文件到 html 文档中 - script(url) { - return new Promise((resolve, reject) => { - const script = document.createElement('script'); - script.src = url; - - script.onload = () => { - console.log(`${url} 加载完成`); - script.remove(); - resolve(); - }; - script.onerror = (err) => reject(err); - document.body.append(script); - }); - }, - // 加载 css 文件到 html 文档中 - css(url) { - return new Promise((resolve, reject) => { - const style = document.createElement('style'); - style.rel = 'stylesheet'; - style.src = url; - style.onload = () => { - console.log(`${url} 加载完成`); - resolve(); - }; - style.onerror = (err) => reject(err); - document.body.append(style); - }); - }, - // TODO UMD AMD 等类型的 JS 代码的载入 -}; - +function _c(e,t){return e instanceof File?e:e instanceof Blob?(e.name=t,e):new File([JSON.stringify(e)],t)} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -var scriptMap = { - zangodb: 'https://cdn.jsdelivr.net/gh/erikolson186/zangodb/dist/zangodb.min.js', - dexie: 'https://cdn.jsdelivr.net/npm/dexie@3.0.3/dist/dexie.min.js', - mockjs: 'https://cdn.jsdelivr.net/npm/mockjs-esm/dist/mock.min.js', - xlsx: 'https://cdn.jsdelivr.net/npm/xlsx@0.17.0/dist/xlsx.full.min.js', - lodash: 'https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js', - gsap: [ - 'https://cdn.jsdelivr.net/npm/gsap@3.6.1/dist/gsap.min.js', - 'https://cdn.jsdelivr.net/npm/gsap@3.6.1/dist/ScrollTrigger.min.js', - ], - animejs: 'https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js', - rxjs: 'https://cdn.jsdelivr.net/npm/rxjs@7.1.0/dist/bundles/rxjs.umd.min.js', - jszip: 'https://cdn.jsdelivr.net/npm/jszip@3.6.0/dist/jszip.min.js', - 'ajax-hook': 'https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js', - axios: 'https://cdn.jsdelivr.net/npm/axios@0.21.1/dist/axios.min.js', - react: [ - 'https://unpkg.com/react@16/umd/react.production.min.js', - 'https://unpkg.com/react-dom@16/umd/react-dom.production.min.js', - ], - vue: [ - 'https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js', - 'https://cdn.jsdelivr.net/npm/vuex@3.6.2/dist/vuex.min.js', - ], -}; - + */const wc={main:Promise.resolve(!0),add(e){this.main.then((()=>Oc(e)))}},Oc=function(e){const t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=e.name,t.click(),URL.revokeObjectURL(t.href),t.remove(),console.log("%c 下载完成","color:green")},jc=(e,{DownloadFileName:t}={},r)=>{const n=_c(e,t||("string"==typeof url?r.url.replace(/[^\/]*?\//g,""):""));return wc.add(n),null},Pc={script:e=>new Promise(((t,r)=>{const n=document.createElement("script");n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),n.remove(),t()},n.onerror=e=>r(e),document.body.append(n)})),css:e=>new Promise(((t,r)=>{const n=document.createElement("style");n.rel="stylesheet",n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),t()},n.onerror=e=>r(e),document.body.append(n)}))}; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -// 借助 jsdelivr 网站的免费 cdn 实现直接查询导入插件的功能。 -const URI = 'https://cdn.jsdelivr.net'; -const wayMap = Object.entries({ - npm: /^npm?/i, - gh: /gh?|github/i, - wp: /wordpress|wp/i, -}); - -/** - * 描述 - * @date 2021-06-28 - * @param {any} moduleName - * @param {any} options - * @return {any} - */ -function jsdelivr(moduleName, { version = '', store = 'npm', path = '' } = {}) { - const way = wayMap.reduce((final, [key, value]) => (value.test(store) ? key : final), 'npm'); - return `${URI}/${way}/${moduleName}${version ? `@${version}` : ''}${path ? `/${path}` : ''}`; -} - +var Sc={zangodb:"https://cdn.jsdelivr.net/gh/erikolson186/zangodb/dist/zangodb.min.js",dexie:"https://cdn.jsdelivr.net/npm/dexie@3.0.3/dist/dexie.min.js",mockjs:"https://cdn.jsdelivr.net/npm/mockjs-esm/dist/mock.min.js",xlsx:"https://cdn.jsdelivr.net/npm/xlsx@0.17.0/dist/xlsx.full.min.js",lodash:"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js",gsap:["https://cdn.jsdelivr.net/npm/gsap@3.6.1/dist/gsap.min.js","https://cdn.jsdelivr.net/npm/gsap@3.6.1/dist/ScrollTrigger.min.js"],animejs:"https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js",rxjs:"https://cdn.jsdelivr.net/npm/rxjs@7.1.0/dist/bundles/rxjs.umd.min.js",jszip:"https://cdn.jsdelivr.net/npm/jszip@3.6.0/dist/jszip.min.js","ajax-hook":"https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js",axios:"https://cdn.jsdelivr.net/npm/axios@0.21.1/dist/axios.min.js",react:["https://unpkg.com/react@16/umd/react.production.min.js","https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"],vue:["https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js","https://cdn.jsdelivr.net/npm/vuex@3.6.2/dist/vuex.min.js"]}; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -function type$1(any) { - return Object.prototype.toString.call(any).match(/(?<=\[object\s+)\S+?(?=\])/)[0]; -} - + */const Ac=Object.entries({npm:/^npm?/i,gh:/gh?|github/i,wp:/wordpress|wp/i});function xc(e,{version:t="",store:r="npm",path:n=""}={}){return`https://cdn.jsdelivr.net/${Ac.reduce(((e,[t,n])=>n.test(r)?t:e),"npm")}/${e}${t?`@${t}`:""}${n?`/${n}`:""}`} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -const URLTest$1 = /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/; - -/** - * 根据 name object 获取 url - * @date 2021-06-28 - * @param {any} {name - * @param {any} way - * @param {any} path - * @param {any} version} - * @return {any} - */ -function fromName$1({ name, way, path, version }) { - if (scriptMap.hasOwnProperty(name)) { - // 优先使用自带的位置 - return scriptMap[name]; - } - return jsdelivr(name, { version, store: way, path }); -} - -const handle$1 = { - Object({ url = '', name, way = 'npm', path = '', version = '', type = 'script' }) { - if (!url) { - // 没有 url 属性 - const result = fromName$1({ name, way, path, version }); - if (typeof result === 'string') { - url = result; - } else { - // 发现 scriptMap 内部的描述是完整的 $load 可以接收的 array 和 object 类型 - return $load$1(result); - } - } - return loaderFunction[type](url); - }, - String(Module) { - return this.Object({ [URLTest$1.test(Module) ? 'url' : 'name']: Module }); - }, - Array(arr) { - return Promise.all(arr.map((i) => $load$1(i))); - }, -}; -async function $load$1(Module) { - return handle$1[type$1(Module)](Module); -} - + */function Ec(e){return Object.prototype.toString.call(e).match(/(?<=\[object\s+)\S+?(?=\])/)[0]} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -let XLSX; -function init$1() { - return $load$1('xlsx').then(() => { - XLSX = window.XLSX; - }); -} - + */const Tc=/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;const Ic={Object({url:e="",name:t,way:r="npm",path:n="",version:i="",type:o="script"}){if(!e){const o=function({name:e,way:t,path:r,version:n}){return Sc.hasOwnProperty(e)?Sc[e]:xc(e,{version:n,store:t,path:r})}({name:t,way:r,path:n,version:i});if("string"!=typeof o)return Cc(o);e=o}return Pc[o](e)},String(e){return this.Object({[Tc.test(e)?"url":"name"]:e})},Array:e=>Promise.all(e.map((e=>Cc(e))))};async function Cc(e){return Ic[Ec(e)](e)} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -// XLSX 通过 script 导入 -function ArrayToSheet(sheetArray) { - sheetArray.forEach((i) => { - Object.entries(i).forEach(([key, value]) => { - if (value instanceof Object) { - i[key] = JSON.stringify(value); - } - }); - // 处理二层数据不能够写入的问题 - }); - return XLSX.utils.json_to_sheet(sheetArray); -} - -function bookToFile(book, name, options) { - const ArrayBuffer = XLSX.write(book, options); - return new File([ArrayBuffer], `${name}.${options.bookType}`); -} -function ObjectToBook(input) { - const book = XLSX.utils.book_new(); - Object.entries(input).forEach(([sheetName, sheetArray]) => { - const sheet = ArrayToSheet(sheetArray); - XLSX.utils.book_append_sheet(book, sheet, sheetName); - }); - return book; -} - -// input: {sheetName1:[],sheetName2:[]} -function createExcelFile(input, fileName, XLSXOptions) { - const { bookType = 'xlsx', bookSST = true, type = 'array' } = XLSXOptions || {}; - return bookToFile(ObjectToBook(input), fileName, { - bookType, - bookSST, - type, - }); -} - + */let kc;function Dc(){return Cc("xlsx").then((()=>{kc=window.XLSX}))} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -// 未完成 导入 XLSX 的 Promise 到流的转变 - -// ExcelHelper 是将 Object => Book => File 用于下载的一个库 -const ExcelHelper = function (formatter, options = {}) { - return Plugin$1({ - name: 'ExcelHelper', - init: init$1, - options, - main(data) { - const { fileName = 'result', XLSXOptions = {} } = this.options; - if (formatter instanceof Function) data = formatter(data); - return createExcelFile(data, `${fileName}-${new Date().getTime()}`, XLSXOptions); - }, - }); -}; - + */function Nc(e){const t=kc.utils.book_new();return Object.entries(e).forEach((([e,r])=>{const n=function(e){return e.forEach((e=>{Object.entries(e).forEach((([t,r])=>{r instanceof Object&&(e[t]=JSON.stringify(r))}))})),kc.utils.json_to_sheet(e)}(r);kc.utils.book_append_sheet(t,n,e)})),t}function Vc(e,t,r){const{bookType:n="xlsx",bookSST:i=!0,type:o="array"}=r||{};return function(e,t,r){const n=kc.write(e,r);return new File([n],`${t}.${r.bookType}`)}(Nc(e),t,{bookType:n,bookSST:i,type:o})} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -let JSZip; -function init() { - return $load$1('jszip').then(() => { - JSZip = window.JSZip; - }); -} - /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -let index$1 = 0; -async function zipper(fileArray, zipName) { - // 启动压缩 - const zip = new JSZip(); - // 压入所有文件 - fileArray.forEach((file) => zip.file(file.name, file)); - // 设置压缩格式,开始打包 - const content = await zip.generateAsync({ - type: 'blob', // nodejs用 nodebuffer ,浏览器用 blob - }); - // 给压缩文件一个名称 - content.name = `${zipName}-${index$1++}.zip`; - return content; -} - +let Rc;function Uc(){return Cc("jszip").then((()=>{Rc=window.JSZip}))} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -const ZipFile = function (options = {}) { - if (!options.zipFileName) options.zipFileName = new Date().getTime(); - return Plugin$1({ - init, - name: 'zipFile', - main(blob) { - const { zipFileName } = this.options; - const files = toFile(blob, zipFileName); - return zipper(files, zipFileName); - }, - options, - }); -}; - + */let Mc=0; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -function Combine(number, waitTime = 5000, options = {}) { - return Plugin$1({ - name: 'Combine', // 这个 name 是负责进行监控的标志符号 - options, // 接收所有的参数,提供给所有函数使用 - operator() { - // 复写 operator - return (source) => - source.pipe( - bufferTime(waitTime, undefined, number), - filter((i) => i.length), // 必须要进行检测是否为空 - concatMap((tasks) => of(new TaskGroup(tasks))), - ); - }, - }); -} -function Break() { - return Plugin$1({ - name: 'Break', // 这个 name 是负责进行监控的标志符号 - options, - operator() { - return (source) => - source.pipe( - concatMap((taskGroup) => { - if (taskGroup instanceof TaskGroup) { - return from(taskGroup.$destroy()); - } else { - return of(taskGroup); - } - }), - ); - }, - }); -} - +function zc(e=3,t=1e3){return r=>new Lo((n=>{const i=new Set;let o=0;const a=()=>{i.size&&(n.next([...i]),i.clear())},s=r.subscribe((r=>{switch(console.log(o),o&&(clearTimeout(o),o=0),i.size){case 0:return i.add(r);case e-1:return i.add(r),a();default:return o=setTimeout(a,t),i.add(r)}}),la,(()=>{a(),n.complete()}));return()=>{i.clear(),s.unsubscribe()}}))} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -var plugins = /*#__PURE__*/Object.freeze({ - __proto__: null, - Request: Request, - Download: Download, - ExcelHelper: ExcelHelper, - ZipFile: ZipFile, - Combine: Combine, - Break: Break -}); - /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -/* - * @Author: KonghaYao - * @Date: 2021-06-29 16:16:29 - * @Last Modified by: KonghaYao - * @Last Modified time: 2021-06-29 16:16:29 - */ -/* eslint-disable no-extend-native */ - -// 解决无限debugger的一种方式 -// 对于无限 debugger 不一定有效 -// TODO 验证有效性 -function $antiDebugger() { - if (!Function.prototype.$constructor) { - // 对 Function 构造函数外包一层 - Function.prototype.$constructor = Function.prototype.constructor; - Function.prototype.constructor = function (...args) { - if (args && typeof args[0] === 'string') { - if (args[0] === 'debugger') { - return; - } - } - return Function.prototype.$constructor.apply(this, args); - }; - } -} - +var Fc=Object.freeze({__proto__:null,Request:function(e={}){return dc({init(){},name:"Request",main:gc,options:e,operator(){const{delay:e=200,buffer:t=1,retry:r=3,handleError:n=null}=this.options;return i=>i.pipe(yc((e=>this.TaskStarter(e)),{delay:e,buffer:t,retry:r,handleError:n||mc}))}})},Download:function(e={}){return dc({name:"Download",main:jc,options:e})},ExcelHelper:function(e,t={}){return dc({name:"ExcelHelper",init:Dc,options:t,main(t){const{fileName:r="result",XLSXOptions:n={}}=this.options;return e instanceof Function&&(t=e(t)),Vc(t,`${r}-${(new Date).getTime()}`,n)}})},ZipFile:function(e={}){return e.zipFileName||(e.zipFileName=(new Date).getTime()),dc({init:Uc,name:"zipFile",main(e){const{zipFileName:t}=this.options;return async function(e,t){const r=new Rc;e.forEach((e=>r.file(e.name,e)));const n=await r.generateAsync({type:"blob"});return n.name=`${t}-${Mc++}.zip`,n} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -/** - * 这是清理copy的函数,目的是为了能够让用户进行复制 - * @date 2021-03-02 - */ -function clearCopyBarriers() { - [document, ...document.querySelectorAll('*')].forEach((ele) => { - // 删除对象属性上的函数 - ele.oncontextmenu = ''; - ele.oncopy = ''; - ele.oncut = ''; - ele.onselectstart = true; - - // 清除事件绑定的控制 - const event = window.getEventListeners(ele); - // 清除 快捷键 copy cut 事件的占用 - ['keydown', 'copy', 'cut'].forEach((eventName) => { - if (event.hasOwnProperty(eventName)) { - event[eventName].forEach((target) => ele.removeEventListener(eventName, target.listener)); - } - }); - }); - console.log('copy 方式清理完成'); -} -/** - * 复制函数 - * @description 这个函数只能用在浏览器环境中 - * @date 2021-03-02 - * @param {any} content 要复制的东西,可以是 DOM - * @param {Boolean} clearBarriers=false 顺便帮你解决不能复制的问题,可能会失败 - */ -function $copy(content, clearBarriers = false) { - if (clearBarriers) clearCopyBarriers(); - - // 询问 window.copy 是否被覆盖了 - if (!(window.copy && window.copy.toString() === 'function copy(value) { [Command Line API] }')) { - // 尝试重置 copy 函数 - delete window.copy; - } - // 直接使用控制台的复制功能 - // ! 在开发者工具中可以调用这个函数 - window.copy(content); - console.log('copy 完成,请您查看您的剪贴版'); -} - -var iframe = [ - "webkitStorageInfo", - "0", - "1", - "cookieStore", - "crossOriginIsolated", - "onbeforexrselect", - "ontransitioncancel", - "ontransitionrun", - "ontransitionstart", - "originAgentCluster", - "showDirectoryPicker", - "showOpenFilePicker", - "showSaveFilePicker", - "trustedTypes", - "parent", - "opener", - "top", - "length", - "frames", - "closed", - "location", - "self", - "window", - "document", - "name", - "customElements", - "history", - "locationbar", - "menubar", - "personalbar", - "scrollbars", - "statusbar", - "toolbar", - "status", - "frameElement", - "navigator", - "origin", - "external", - "screen", - "innerWidth", - "innerHeight", - "scrollX", - "pageXOffset", - "scrollY", - "pageYOffset", - "visualViewport", - "screenX", - "screenY", - "outerWidth", - "outerHeight", - "devicePixelRatio", - "clientInformation", - "screenLeft", - "screenTop", - "defaultStatus", - "defaultstatus", - "styleMedia", - "onsearch", - "isSecureContext", - "onabort", - "onblur", - "oncancel", - "oncanplay", - "oncanplaythrough", - "onchange", - "onclick", - "onclose", - "oncontextmenu", - "oncuechange", - "ondblclick", - "ondrag", - "ondragend", - "ondragenter", - "ondragleave", - "ondragover", - "ondragstart", - "ondrop", - "ondurationchange", - "onemptied", - "onended", - "onerror", - "onfocus", - "onformdata", - "oninput", - "oninvalid", - "onkeydown", - "onkeypress", - "onkeyup", - "onload", - "onloadeddata", - "onloadedmetadata", - "onloadstart", - "onmousedown", - "onmouseenter", - "onmouseleave", - "onmousemove", - "onmouseout", - "onmouseover", - "onmouseup", - "onmousewheel", - "onpause", - "onplay", - "onplaying", - "onprogress", - "onratechange", - "onreset", - "onresize", - "onscroll", - "onseeked", - "onseeking", - "onselect", - "onstalled", - "onsubmit", - "onsuspend", - "ontimeupdate", - "ontoggle", - "onvolumechange", - "onwaiting", - "onwebkitanimationend", - "onwebkitanimationiteration", - "onwebkitanimationstart", - "onwebkittransitionend", - "onwheel", - "onauxclick", - "ongotpointercapture", - "onlostpointercapture", - "onpointerdown", - "onpointermove", - "onpointerup", - "onpointercancel", - "onpointerover", - "onpointerout", - "onpointerenter", - "onpointerleave", - "onselectstart", - "onselectionchange", - "onanimationend", - "onanimationiteration", - "onanimationstart", - "ontransitionend", - "onafterprint", - "onbeforeprint", - "onbeforeunload", - "onhashchange", - "onlanguagechange", - "onmessage", - "onmessageerror", - "onoffline", - "ononline", - "onpagehide", - "onpageshow", - "onpopstate", - "onrejectionhandled", - "onstorage", - "onunhandledrejection", - "onunload", - "performance", - "stop", - "open", - "alert", - "confirm", - "prompt", - "print", - "queueMicrotask", - "requestAnimationFrame", - "cancelAnimationFrame", - "captureEvents", - "releaseEvents", - "requestIdleCallback", - "cancelIdleCallback", - "getComputedStyle", - "matchMedia", - "moveTo", - "moveBy", - "resizeTo", - "resizeBy", - "scroll", - "scrollTo", - "scrollBy", - "getSelection", - "find", - "webkitRequestAnimationFrame", - "webkitCancelAnimationFrame", - "fetch", - "btoa", - "atob", - "setTimeout", - "clearTimeout", - "setInterval", - "clearInterval", - "createImageBitmap", - "close", - "focus", - "blur", - "postMessage", - "onappinstalled", - "onbeforeinstallprompt", - "crypto", - "indexedDB", - "sessionStorage", - "localStorage", - "chrome", - "onpointerrawupdate", - "speechSynthesis", - "webkitRequestFileSystem", - "webkitResolveLocalFileSystemURL", - "openDatabase", - "applicationCache", - "caches", - "ondevicemotion", - "ondeviceorientation", - "ondeviceorientationabsolute" -]; - + */(_c(e,t),t)},options:e})},Combine:function(e,t=1e3,r){return dc({name:"Combine",main:r,operator(){return n=>n.pipe(zc(e,t),Ca((e=>e.length)),Du((e=>{const t=ua(new ec(e));return r instanceof Function?t.pipe(Du((e=>this.TaskStarter(e)))):t})))}})},Break:function(){return dc({name:"Break",options:options,operator:()=>e=>e.pipe(Du((e=>e instanceof ec?from(e.$destroy()):ua(e))))})}}); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -// iframe 是所有的 window 对象下稳定的属性名 -// !若是使用 iframe 标签的属性来得到 window 的自带属性,遇到不能使用 iframe 的网站就会失效 -// ! 所以使用了这种方式。 - -/** - * 全局变量展示 - * @date 2020-09-17 - * @description 将 window 和 上面引入的 iframe 对象做了比较 - * @return {Object} 返回 window 的属性和对象 - */ -function $GlobalVars() { - // 通过比较得出window上的变量 - const diff = difference(Object.keys(window), iframe); - return pick(window, diff); -} - + */var Lc=["webkitStorageInfo","0","1","cookieStore","crossOriginIsolated","onbeforexrselect","ontransitioncancel","ontransitionrun","ontransitionstart","originAgentCluster","showDirectoryPicker","showOpenFilePicker","showSaveFilePicker","trustedTypes","parent","opener","top","length","frames","closed","location","self","window","document","name","customElements","history","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","status","frameElement","navigator","origin","external","screen","innerWidth","innerHeight","scrollX","pageXOffset","scrollY","pageYOffset","visualViewport","screenX","screenY","outerWidth","outerHeight","devicePixelRatio","clientInformation","screenLeft","screenTop","defaultStatus","defaultstatus","styleMedia","onsearch","isSecureContext","onabort","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onmousewheel","onpause","onplay","onplaying","onprogress","onratechange","onreset","onresize","onscroll","onseeked","onseeking","onselect","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel","onauxclick","ongotpointercapture","onlostpointercapture","onpointerdown","onpointermove","onpointerup","onpointercancel","onpointerover","onpointerout","onpointerenter","onpointerleave","onselectstart","onselectionchange","onanimationend","onanimationiteration","onanimationstart","ontransitionend","onafterprint","onbeforeprint","onbeforeunload","onhashchange","onlanguagechange","onmessage","onmessageerror","onoffline","ononline","onpagehide","onpageshow","onpopstate","onrejectionhandled","onstorage","onunhandledrejection","onunload","performance","stop","open","alert","confirm","prompt","print","queueMicrotask","requestAnimationFrame","cancelAnimationFrame","captureEvents","releaseEvents","requestIdleCallback","cancelIdleCallback","getComputedStyle","matchMedia","moveTo","moveBy","resizeTo","resizeBy","scroll","scrollTo","scrollBy","getSelection","find","webkitRequestAnimationFrame","webkitCancelAnimationFrame","fetch","btoa","atob","setTimeout","clearTimeout","setInterval","clearInterval","createImageBitmap","close","focus","blur","postMessage","onappinstalled","onbeforeinstallprompt","crypto","indexedDB","sessionStorage","localStorage","chrome","onpointerrawupdate","speechSynthesis","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","openDatabase","applicationCache","caches","ondevicemotion","ondeviceorientation","ondeviceorientationabsolute"]; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -function type(any) { - return Object.prototype.toString.call(any).match(/(?<=\[object\s+)\S+?(?=\])/)[0]; -} - /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - -const TypeMap = { - RE: '', - StringFunction(all, key, value, keyValue) { - if (this.RE.test(`${value}`)) all.push(keyValue); - return all; - }, - - Array(all, key, value) { - const arr = searchObj(Object.entries(value), this.RE); - - const Value = arr.reduce((final, [k, v]) => { - final[parseInt(k)] = v; - return final; - }, []); - if (arr.length) all.push([key, Value]); - - return all; - }, - Function(all, key, value) { - const entries = searchObj(Object.entries(value), this.RE); - if (entries.length) { - all.push([key, Object.assign(value, Object.fromEntries(entries))]); - } - return all; - }, - Object(all, key, value) { - const entries = searchObj(Object.entries(value), this.RE); - if (entries.length) all.push([key, Object.fromEntries(entries)]); - - return all; - }, -}; -TypeMap.Number = TypeMap.StringFunction; -TypeMap.String = TypeMap.StringFunction; - -/** - * 描述 - * @date 2021-06-28 - * @param {any} arr - * @param {any} RE - * @param {any} keepUnknown=false - * @return {any} - */ -function searchObj(arr, RE, keepUnknown = false) { - return arr.reduce((all, keyValue) => { - const [key, value] = keyValue; - // 判断 key 中是否有符合项 - if (RE.test(key)) { - return [...all, keyValue]; - } - // 判断数据类型 分类操作 - TypeMap.RE = RE; - const type$1 = type(value); - if (TypeMap.hasOwnProperty(type$1)) { - return TypeMap[type$1](all, key, value, keyValue); - } - return keepUnknown ? [all, keyValue] : all; - }, []); -} - +const $c={RE:"",StringFunction(e,t,r,n){return this.RE.test(`${r}`)&&e.push(n),e},Array(e,t,r){const n=Hc(Object.entries(r),this.RE),i=n.reduce(((e,[t,r])=>(e[parseInt(t)]=r,e)),[]);return n.length&&e.push([t,i]),e},Function(e,t,r){const n=Hc(Object.entries(r),this.RE);return n.length&&e.push([t,Object.assign(r,Object.fromEntries(n))]),e},Object(e,t,r){const n=Hc(Object.entries(r),this.RE);return n.length&&e.push([t,Object.fromEntries(n)]),e}};function Hc(e,t,r=!1){return e.reduce(((e,n)=>{const[i,o]=n;if(t.test(i))return[...e,n];$c.RE=t;const a=(s=o,Object.prototype.toString.call(s).match(/(?<=\[object\s+)\S+?(?=\])/)[0]); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -/** - * 描述 - * @date 2021-06-28 - * @param {any} obj - * @param {any} reg - * @returns {any} - */ - -function $search(obj, reg) { - if (!isRegExp(reg) && isString(reg)) { - reg = new RegExp(reg); - } - if (obj instanceof Array) { - return searchObj(Object.entries({ i: obj }), reg)[0][1]; - } - if (obj instanceof Object) { - return Object.fromEntries(searchObj(Object.entries(obj), reg)); - } - throw new Error('不是对象,不能搜索'); -} - +var s;return $c.hasOwnProperty(a)?$c[a](e,i,o,n):r?[e,n]:e}),[])} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -const URLTest = /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/; - + */$c.Number=$c.StringFunction,$c.String=$c.StringFunction; /** - * 根据 name object 获取 url - * @date 2021-06-28 - * @param {any} {name - * @param {any} way - * @param {any} path - * @param {any} version} - * @return {any} + * @license + * Copyright 2021 KonghaYao 江夏尧 + * SPDX-License-Identifier: Apache-2.0 */ -function fromName({ name, way, path, version }) { - if (scriptMap.hasOwnProperty(name)) { - // 优先使用自带的位置 - return scriptMap[name]; - } - return jsdelivr(name, { version, store: way, path }); -} - -const handle = { - Object({ url = '', name, way = 'npm', path = '', version = '', type = 'script' }) { - if (!url) { - // 没有 url 属性 - const result = fromName({ name, way, path, version }); - if (typeof result === 'string') { - url = result; - } else { - // 发现 scriptMap 内部的描述是完整的 $load 可以接收的 array 和 object 类型 - return $load(result); - } - } - return loaderFunction[type](url); - }, - String(Module) { - return this.Object({ [URLTest.test(Module) ? 'url' : 'name']: Module }); - }, - Array(arr) { - return Promise.all(arr.map((i) => $load(i))); - }, -}; -async function $load(Module) { - return handle[type$1(Module)](Module); -} - +const Bc=/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;const Gc={Object({url:e="",name:t,way:r="npm",path:n="",version:i="",type:o="script"}){if(!e){const o=function({name:e,way:t,path:r,version:n}){return Sc.hasOwnProperty(e)?Sc[e]:xc(e,{version:n,store:t,path:r})}({name:t,way:r,path:n,version:i});if("string"!=typeof o)return Kc(o);e=o}return Pc[o](e)},String(e){return this.Object({[Bc.test(e)?"url":"name"]:e})},Array:e=>Promise.all(e.map((e=>Kc(e))))};async function Kc(e){return Gc[Ec(e)](e)} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var excelTemplate = { - 'data|100': [ - { - ID: '@increment()', - name: '@cname()', - description: '@csentence()', - avatar: '@dataImage("64x64")', - address: '@region()', - province: '@province()', - }, - ], -}; - /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -// 在这里配置 url 和 type 信息 -const Server = { - excel: { - url: '/fake/excel', - type: 'get', - template: excelTemplate, - }, -}; - +const qc={excel:{url:"/fake/excel",type:"get",template:{"data|100":[{ID:"@increment()",name:"@cname()",description:"@csentence()",avatar:'@dataImage("64x64")',address:"@region()",province:"@province()"}]}}}; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -async function Mock(MockSiteName) { - // 导入 Mockjs - if (!window.Mock) { - await $load('mockjs'); - console.warn('Mockjs 载入并代理 Ajax 中'); - } - console.warn('mock 启动后台 ', MockSiteName); - const { url, type, template } = Server[MockSiteName]; - window.Mock.mock(url, type, template); - return true; -} -const $Mock = memoize(Mock); - + */const Wc=eu((async function(e){window.Mock||(await Kc("mockjs"),console.warn("Mockjs 载入并代理 Ajax 中")),console.warn("mock 启动后台 ",e);const{url:t,type:r,template:n}=qc[e];return window.Mock.mock(t,r,n),!0})),Yc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","hash"],Qc={strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - + */function Xc(e,t=!1){const r=Qc[t?"strict":"loose"].exec(decodeURI(e)),n=Yc.reduce(((e,t,n)=>(e[t]=r[n]||"",e)),{});var i;return n.queryParams=(i=n.query,String(i).split(/&|;/).reduce((function(e,t){try{t=decodeURIComponent(t.replace(/\+/g," "))}catch(e){}const[r,n]=t.split(/=/g);return e[r]=n,e}),{})),n.base=n.host?(n.protocol?n.protocol+"://"+n.host:n.host)+(n.port?":"+n.port:""):"",n} /** - * The Regexps were copied from Purl (A JavaScript URL parser) v2.3.1 - * which developed and maintained by Mark Perkins, mark@allmarkedup.com - * Source repository: https://github.com/allmarkedup/jQuery-URL-Parser - * Licensed under an MIT-style license. + * @license + * Copyright 2021 KonghaYao 江夏尧 + * SPDX-License-Identifier: Apache-2.0 */ -const key = [ - 'source', - 'protocol', - 'authority', - 'userInfo', - 'user', - 'password', - 'host', - 'port', - 'relative', - 'path', - 'directory', - 'file', - 'query', - 'hash', -]; // keys available to query -const parser = { - // less intuitive, more accurate to the specs - strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, - // more intuitive, fails on relative paths and deviates from specs - loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/, -}; - -function parseUri(url, strictMode = false) { - const res = parser[strictMode ? 'strict' : 'loose'].exec(decodeURI(url)); - - const uri = key.reduce((col, keyName, index) => { - col[keyName] = res[index] || ''; - return col; - }, {}); - - // build query and hash parameters - uri.queryParams = parseString(uri.query); - - // compile a 'base' domain attribute - uri['base'] = uri.host - ? (uri.protocol ? uri.protocol + '://' + uri.host : uri.host) + (uri.port ? ':' + uri.port : '') - : ''; - - return uri; -} - -function parseString(queryString) { - return String(queryString) - .split(/&|;/) - .reduce(function (collection, pair) { - try { - pair = decodeURIComponent(pair.replace(/\+/g, ' ')); - } catch (e) { - // ignore - } - const [key, value] = pair.split(/=/g); - collection[key] = value; - return collection; - }, {}); -} - -function parseURL(url, strictMode = false) { - return parseUri(url, strictMode); -} - +var Zc=Object.freeze({__proto__:null,$antiDebugger:function(){Function.prototype.$constructor||(Function.prototype.$constructor=Function.prototype.constructor,Function.prototype.constructor=function(...e){if(!e||"string"!=typeof e[0]||"debugger"!==e[0])return Function.prototype.$constructor.apply(this,e)})} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -var tools = /*#__PURE__*/Object.freeze({ - __proto__: null, - $antiDebugger: $antiDebugger, - $copy: $copy, - $GlobalVars: $GlobalVars, - $search: $search, - $load: $load, - $Mock: $Mock, - parseURL: parseURL -}); - + */,$copy:function(e,t=!1){t&&([document,...document.querySelectorAll("*")].forEach((e=>{e.oncontextmenu="",e.oncopy="",e.oncut="",e.onselectstart=!0;const t=window.getEventListeners(e);["keydown","copy","cut"].forEach((r=>{t.hasOwnProperty(r)&&t[r].forEach((t=>e.removeEventListener(r,t.listener)))}))})),console.log("copy 方式清理完成")),window.copy&&"function copy(value) { [Command Line API] }"===window.copy.toString()||delete window.copy,window.copy(e),console.log("copy 完成,请您查看您的剪贴版")},$GlobalVars:function(){const e=gu(Object.keys(window),Lc);return ju(window,e)},$search:function(e,t){var r;if(!_u(t)&&("string"==typeof(r=t)||!Qa(r)&&qa(r)&&"[object String]"==Ka(r))&&(t=new RegExp(t)),e instanceof Array)return Hc(Object.entries({i:e}),t)[0][1];if(e instanceof Object)return Object.fromEntries(Hc(Object.entries(e),t));throw new Error("不是对象,不能搜索")},$load:Kc,$Mock:Wc,parseURL:function(e,t=!1){return Xc(e,t)}}); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - -class PLUGIN { - constructor({ - forceRetry = true, - saveResult = false, - name = null, - main, - init = null, - error = null, - complete = null, - options = {}, - operator, - }) { - if (operator) this.operator = operator; - // 写入自身中 - Object.assign(this, { - name, // 名称,一般用作提示标记 - main, // Plugin 中的功能性函数 - init, // 初始化整个 Plugin 的函数 - error, // operator 错误时的事件,若返回 false 类的数据,将会中断流,返回正常数据会继续流 - complete, // 函数完成时的提示事件 - options, // main 函数接收的 options - saveResult, // 是否保存结果到每一个 Task 中 - forceRetry, // 是否强制重新使用 Plugin - }); - } - initUUID(index) { - this.uuid = createUUID((this?.main || this.operator).toString() + index); - } - // 对 main 函数外包一层,直接启动 main 函数的执行,返回一条流 - TaskStarter(task) { - return of(task).pipe( - // 设置跳过 Plugin 的逻辑 - switchMap((task) => { - return of(task).pipe( - map((task) => [task.$commit('start', this.uuid), task._originData]), - - switchMap(([data, originData]) => { - const result = this.main(data, originData); - return result instanceof Promise || result instanceof Observable ? from$1(result) : of(result); - }), - map((result) => { - task.$commit('success', result, this.uuid, this.saveResult); - return task; - }), - ); - }), - // 捕获到异常 - catchError((...args) => { - if (this.error instanceof Function) { - const afterError = this.error(task, ...args); - if (afterError) throw new PluginError(afterError); - - return EMPTY; - } - throw new PluginError(args[0]); - }), - // 完成 Plugin 时的事件 - tap((task) => this.complete && this.complete(task)), - ); - } - - operator(context) { - // ! 这个是默认的 operator 函数 - // context 为上层的 JSpider 实例 - return pipe(switchMap((task) => this.TaskStarter(task))); - } -} - -function Plugin(Process, otherOptions = {}) { - if (Process instanceof Function) { - return new PLUGIN( - Object.assign(otherOptions, { - main: Process, - }), - ); - } - if (Process instanceof Object) { - return new PLUGIN(Process); - } - throw new PluginError('Plugin 必须是一个函数或者是 Plugin 描述对象'); -} - + */class Jc{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=uc((this?.main||this.operator).toString()+e)}TaskStarter(e){return ua(e).pipe(Ku((e=>ua(e).pipe(fa((e=>[e.$commit("start",this.uuid),e._originData])),Ku((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Lo?Oa(r):ua(r)})),fa((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),Iu(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new pc(r);return na}throw new pc(t[0])})),Yu((e=>this.complete&&this.complete(e))))}operator(e){return zo(Ku((e=>this.TaskStarter(e))))}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var index = Object.assign(Spider, tools, { - plugins, - Plugin, - Task, - TaskGroup, - version: "3.2.1", - buildDate: new Date(1628326859357), -}); - -export default index; +var el=Object.assign(class{constructor({logEvery:e=!1}={}){this.config={logEvery:e},this.views=new fc(this.config)}crawl(...e){return lc.createFlow(e.flat()),this}pipeline(...e){return lc.pipeline(...e),this}start(){return lc.startFlow(),this}stop(){return lc.stopFlow(),this}},Zc,{plugins:Fc,Plugin:function(e,t={}){if(e instanceof Function)return new Jc(Object.assign(t,{main:e}));if(e instanceof Object)return new Jc(e);throw new pc("Plugin 必须是一个函数或者是 Plugin 描述对象")},Task:Ju,TaskGroup:ec,version:"3.2.2",buildDate:new Date(1628382223946)});export default el; diff --git a/dist/JSpider.min.js b/dist/JSpider.min.js index b07bff8..171bde9 100644 --- a/dist/JSpider.min.js +++ b/dist/JSpider.min.js @@ -1,18221 +1,490 @@ +/** + * Apache License + * Version 2.0, January 2004 + * http://www.apache.org/licenses/ + * + * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + * + * 1. Definitions. + * + * "License" shall mean the terms and conditions for use, reproduction, + * and distribution as defined by Sections 1 through 9 of this document. + * + * "Licensor" shall mean the copyright owner or entity authorized by + * the copyright owner that is granting the License. + * + * "Legal Entity" shall mean the union of the acting entity and all + * other entities that control, are controlled by, or are under common + * control with that entity. For the purposes of this definition, + * "control" means (i) the power, direct or indirect, to cause the + * direction or management of such entity, whether by contract or + * otherwise, or (ii) ownership of fifty percent (50%) or more of the + * outstanding shares, or (iii) beneficial ownership of such entity. + * + * "You" (or "Your") shall mean an individual or Legal Entity + * exercising permissions granted by this License. + * + * "Source" form shall mean the preferred form for making modifications, + * including but not limited to software source code, documentation + * source, and configuration files. + * + * "Object" form shall mean any form resulting from mechanical + * transformation or translation of a Source form, including but + * not limited to compiled object code, generated documentation, + * and conversions to other media types. + * + * "Work" shall mean the work of authorship, whether in Source or + * Object form, made available under the License, as indicated by a + * copyright notice that is included in or attached to the work + * (an example is provided in the Appendix below). + * + * "Derivative Works" shall mean any work, whether in Source or Object + * form, that is based on (or derived from) the Work and for which the + * editorial revisions, annotations, elaborations, or other modifications + * represent, as a whole, an original work of authorship. For the purposes + * of this License, Derivative Works shall not include works that remain + * separable from, or merely link (or bind by name) to the interfaces of, + * the Work and Derivative Works thereof. + * + * "Contribution" shall mean any work of authorship, including + * the original version of the Work and any modifications or additions + * to that Work or Derivative Works thereof, that is intentionally + * submitted to Licensor for inclusion in the Work by the copyright owner + * or by an individual or Legal Entity authorized to submit on behalf of + * the copyright owner. For the purposes of this definition, "submitted" + * means any form of electronic, verbal, or written communication sent + * to the Licensor or its representatives, including but not limited to + * communication on electronic mailing lists, source code control systems, + * and issue tracking systems that are managed by, or on behalf of, the + * Licensor for the purpose of discussing and improving the Work, but + * excluding communication that is conspicuously marked or otherwise + * designated in writing by the copyright owner as "Not a Contribution." + * + * "Contributor" shall mean Licensor and any individual or Legal Entity + * on behalf of whom a Contribution has been received by Licensor and + * subsequently incorporated within the Work. + * + * 2. Grant of Copyright License. Subject to the terms and conditions of + * this License, each Contributor hereby grants to You a perpetual, + * worldwide, non-exclusive, no-charge, royalty-free, irrevocable + * copyright license to reproduce, prepare Derivative Works of, + * publicly display, publicly perform, sublicense, and distribute the + * Work and such Derivative Works in Source or Object form. + * + * 3. Grant of Patent License. Subject to the terms and conditions of + * this License, each Contributor hereby grants to You a perpetual, + * worldwide, non-exclusive, no-charge, royalty-free, irrevocable + * (except as stated in this section) patent license to make, have made, + * use, offer to sell, sell, import, and otherwise transfer the Work, + * where such license applies only to those patent claims licensable + * by such Contributor that are necessarily infringed by their + * Contribution(s) alone or by combination of their Contribution(s) + * with the Work to which such Contribution(s) was submitted. If You + * institute patent litigation against any entity (including a + * cross-claim or counterclaim in a lawsuit) alleging that the Work + * or a Contribution incorporated within the Work constitutes direct + * or contributory patent infringement, then any patent licenses + * granted to You under this License for that Work shall terminate + * as of the date such litigation is filed. + * + * 4. Redistribution. You may reproduce and distribute copies of the + * Work or Derivative Works thereof in any medium, with or without + * modifications, and in Source or Object form, provided that You + * meet the following conditions: + * + * (a) You must give any other recipients of the Work or + * Derivative Works a copy of this License; and + * + * (b) You must cause any modified files to carry prominent notices + * stating that You changed the files; and + * + * (c) You must retain, in the Source form of any Derivative Works + * that You distribute, all copyright, patent, trademark, and + * attribution notices from the Source form of the Work, + * excluding those notices that do not pertain to any part of + * the Derivative Works; and + * + * (d) If the Work includes a "NOTICE" text file as part of its + * distribution, then any Derivative Works that You distribute must + * include a readable copy of the attribution notices contained + * within such NOTICE file, excluding those notices that do not + * pertain to any part of the Derivative Works, in at least one + * of the following places: within a NOTICE text file distributed + * as part of the Derivative Works; within the Source form or + * documentation, if provided along with the Derivative Works; or, + * within a display generated by the Derivative Works, if and + * wherever such third-party notices normally appear. The contents + * of the NOTICE file are for informational purposes only and + * do not modify the License. You may add Your own attribution + * notices within Derivative Works that You distribute, alongside + * or as an addendum to the NOTICE text from the Work, provided + * that such additional attribution notices cannot be construed + * as modifying the License. + * + * You may add Your own copyright statement to Your modifications and + * may provide additional or different license terms and conditions + * for use, reproduction, or distribution of Your modifications, or + * for any such Derivative Works as a whole, provided Your use, + * reproduction, and distribution of the Work otherwise complies with + * the conditions stated in this License. + * + * 5. Submission of Contributions. Unless You explicitly state otherwise, + * any Contribution intentionally submitted for inclusion in the Work + * by You to the Licensor shall be under the terms and conditions of + * this License, without any additional terms or conditions. + * Notwithstanding the above, nothing herein shall supersede or modify + * the terms of any separate license agreement you may have executed + * with Licensor regarding such Contributions. + * + * 6. Trademarks. This License does not grant permission to use the trade + * names, trademarks, service marks, or product names of the Licensor, + * except as required for reasonable and customary use in describing the + * origin of the Work and reproducing the content of the NOTICE file. + * + * 7. Disclaimer of Warranty. Unless required by applicable law or + * agreed to in writing, Licensor provides the Work (and each + * Contributor provides its Contributions) on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied, including, without limitation, any warranties or conditions + * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + * PARTICULAR PURPOSE. You are solely responsible for determining the + * appropriateness of using or redistributing the Work and assume any + * risks associated with Your exercise of permissions under this License. + * + * 8. Limitation of Liability. In no event and under no legal theory, + * whether in tort (including negligence), contract, or otherwise, + * unless required by applicable law (such as deliberate and grossly + * negligent acts) or agreed to in writing, shall any Contributor be + * liable to You for damages, including any direct, indirect, special, + * incidental, or consequential damages of any character arising as a + * result of this License or out of the use or inability to use the + * Work (including but not limited to damages for loss of goodwill, + * work stoppage, computer failure or malfunction, or any and all + * other commercial damages or losses), even if such Contributor + * has been advised of the possibility of such damages. + * + * 9. Accepting Warranty or Additional Liability. While redistributing + * the Work or Derivative Works thereof, You may choose to offer, + * and charge a fee for, acceptance of support, warranty, indemnity, + * or other liability obligations and/or rights consistent with this + * License. However, in accepting such obligations, You may act only + * on Your own behalf and on Your sole responsibility, not on behalf + * of any other Contributor, and only if You agree to indemnify, + * defend, and hold each Contributor harmless for any liability + * incurred by, or claims asserted against, such Contributor by reason + * of your accepting any such warranty or additional liability. + * + * END OF TERMS AND CONDITIONS + * + * APPENDIX: How to apply the Apache License to your work. + * + * To apply the Apache License to your work, attach the following + * boilerplate notice, with the fields enclosed by brackets "[]" + * replaced with your own identifying information. (Don't include + * the brackets!) The text should be enclosed in the appropriate + * comment syntax for the file format. We also recommend that a + * file or class name and description of purpose be included on the + * same "printed page" as the copyright notice for easier + * identification within third-party archives. + * + * Copyright 2021 KonghaYao 江夏尧 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var JSpider=function(){"use strict";function e(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;ne.length)&&(t=e.length);for(var r=0,n=new Array(t);r=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=e[Symbol.iterator]()).next.bind(r)}var R=Symbol("mobx-stored-annotations");function U(e){return Object.assign((function(t,r){M(t,r,e)}),e)}function M(e,t,r){x(e,R)||m(e,R,C({},e[R])),function(e){return e.annotationType_===K}(r)||(e[R][t]=r)}var z=Symbol("mobx administration"),F=function(){function e(e){void 0===e&&(e="Atom"),this.name_=void 0,this.isPendingUnobservation_=!1,this.isBeingObserved_=!1,this.observers_=new Set,this.diffValue_=0,this.lastAccessedBy_=0,this.lowestObserverState_=ze.NOT_TRACKING_,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return ut(this)},t.reportChanged=function(){at(),ct(this),st()},t.toString=function(){return this.name_},e}(),L=w("Atom",F);function $(e,t,r){void 0===t&&(t=h),void 0===r&&(r=h);var n,i=new F(e);return t!==h&&Ct(Tt,i,t,n),r!==h&&It(i,r),i}var H={identity:function(e,t){return e===t},structural:function(e,t){return Wr(e,t)},default:function(e,t){return Object.is(e,t)},shallow:function(e,t){return Wr(e,t,1)}};function B(e,t,r){return Lt(e)?e:Array.isArray(e)?Oe.array(e,{name:r}):y(e)?Oe.object(e,void 0,{name:r}):O(e)?Oe.map(e,{name:r}):j(e)?Oe.set(e,{name:r}):"function"!=typeof e||St(e)||Mt(e)?e:g(e)?Rt(e):jt(r,e)}function G(e){return e}var K="override";function q(e,t){return{annotationType_:e,options_:t,make_:W,extend_:Y}}function W(e,t,r,n){var i;if(null==(i=this.options_)?void 0:i.bound)return null===this.extend_(e,t,r,!1)?0:1;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if(St(r.value))return 1;var a=Q(e,this,t,r,!1);return o(n,t,a),2}function Y(e,t,r,n){var i=Q(e,this,t,r);return e.defineProperty_(t,i,n)}function Q(e,t,r,n,i){var o,a,s,u,c,l;void 0===i&&(i=rt.safeDescriptors),l=n,t.annotationType_,l.value;var f,p=n.value;(null==(o=t.options_)?void 0:o.bound)&&(p=p.bind(null!=(f=e.proxy_)?f:e.target_));return{value:ke(null!=(a=null==(s=t.options_)?void 0:s.name)?a:r.toString(),p,null!=(u=null==(c=t.options_)?void 0:c.autoAction)&&u),configurable:!i||e.isPlainObject_,enumerable:!1,writable:!i}}function X(e,t){return{annotationType_:e,options_:t,make_:Z,extend_:J}}function Z(e,t,r,n){var i;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if((null==(i=this.options_)?void 0:i.bound)&&!Mt(e.target_[t])&&null===this.extend_(e,t,r,!1))return 0;if(Mt(r.value))return 1;var a=ee(e,this,t,r,!1,!1);return o(n,t,a),2}function J(e,t,r,n){var i,o=ee(e,this,t,r,null==(i=this.options_)?void 0:i.bound);return e.defineProperty_(t,o,n)}function ee(e,t,r,n,i,o){var a;void 0===o&&(o=rt.safeDescriptors),a=n,t.annotationType_,a.value;var s,u=n.value;i&&(u=u.bind(null!=(s=e.proxy_)?s:e.target_));return{value:Rt(u),configurable:!o||e.isPlainObject_,enumerable:!1,writable:!o}}function te(e,t){return{annotationType_:e,options_:t,make_:re,extend_:ne}}function re(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function ne(e,t,r,n){var i;return i=r,this.annotationType_,i.get,e.defineComputedProperty_(t,C({},this.options_,{get:r.get,set:r.set}),n)}function ie(e,t){return{annotationType_:e,options_:t,make_:oe,extend_:ae}}function oe(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function ae(e,t,r,n){var i,o;return this.annotationType_,e.defineObservableProperty_(t,r.value,null!=(i=null==(o=this.options_)?void 0:o.enhancer)?i:B,n)}var se=ue();function ue(e){return{annotationType_:"true",options_:e,make_:ce,extend_:le}}function ce(e,t,r,n){var i,a,s,u;if(r.get)return Ae.make_(e,t,r,n);if(r.set){var c=ke(t.toString(),r.set);return n===e.target_?null===e.defineProperty_(t,{configurable:!rt.safeDescriptors||e.isPlainObject_,set:c})?0:2:(o(n,t,{configurable:!0,set:c}),2)}if(n!==e.target_&&"function"==typeof r.value)return g(r.value)?((null==(u=this.options_)?void 0:u.autoBind)?Rt.bound:Rt).make_(e,t,r,n):((null==(s=this.options_)?void 0:s.autoBind)?jt.bound:jt).make_(e,t,r,n);var l,f=!1===(null==(i=this.options_)?void 0:i.deep)?Oe.ref:Oe;"function"==typeof r.value&&(null==(a=this.options_)?void 0:a.autoBind)&&(r.value=r.value.bind(null!=(l=e.proxy_)?l:e.target_));return f.make_(e,t,r,n)}function le(e,t,r,n){var i,o,a;if(r.get)return Ae.extend_(e,t,r,n);if(r.set)return e.defineProperty_(t,{configurable:!rt.safeDescriptors||e.isPlainObject_,set:ke(t.toString(),r.set)},n);"function"==typeof r.value&&(null==(i=this.options_)?void 0:i.autoBind)&&(r.value=r.value.bind(null!=(a=e.proxy_)?a:e.target_));return(!1===(null==(o=this.options_)?void 0:o.deep)?Oe.ref:Oe).extend_(e,t,r,n)}var fe={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function pe(e){return e||fe}Object.freeze(fe);var he=ie("observable"),be=ie("observable.ref",{enhancer:G}),de=ie("observable.shallow",{enhancer:function(e,t,r){return null==e||Nr(e)||yr(e)||Pr(e)||xr(e)?e:Array.isArray(e)?Oe.array(e,{name:r,deep:!1}):y(e)?Oe.object(e,void 0,{name:r,deep:!1}):O(e)?Oe.map(e,{name:r,deep:!1}):j(e)?Oe.set(e,{name:r,deep:!1}):void 0}}),ve=ie("observable.struct",{enhancer:function(e,t){return Wr(e,t)?t:e}}),ye=U(he);function ge(e){return!0===e.deep?B:!1===e.deep?G:(t=e.defaultDecorator)&&null!=(r=null==(n=t.options_)?void 0:n.enhancer)?r:B;var t,r,n}function me(e,t,r){if(!d(t))return Lt(e)?e:y(e)?Oe.object(e,t,r):Array.isArray(e)?Oe.array(e,t):O(e)?Oe.map(e,t):j(e)?Oe.set(e,t):"object"==typeof e&&null!==e?e:Oe.box(e,t);M(e,t,he)}Object.assign(me,ye);var _e,we,Oe=n(me,{box:function(e,t){var r=pe(t);return new Ue(e,ge(r),r.name,!0,r.equals)},array:function(e,t){var r=pe(t);return(!1===rt.useProxies||!1===r.proxy?Hr:ur)(e,ge(r),r.name)},map:function(e,t){var r=pe(t);return new jr(e,ge(r),r.name)},set:function(e,t){var r=pe(t);return new Ar(e,ge(r),r.name)},object:function(e,t,r){return function(e,t,r,n){var i=E(t),o=Cr(e,n)[z];at();try{S(i).forEach((function(e){o.extend_(e,i[e],!r||(!(e in r)||r[e]))}))}finally{st()}return e}(!1===rt.useProxies||!1===(null==r?void 0:r.proxy)?Cr({},r):function(e,t){var r,n;return f(),e=Cr(e,t),null!=(n=(r=e[z]).proxy_)?n:r.proxy_=new Proxy(e,Qt)}({},r),e,t)},ref:U(be),shallow:U(de),deep:ye,struct:U(ve)}),je="computed",Pe=te(je),Se=te("computed.struct",{equals:H.structural}),Ae=function(e,t){if(d(t))return M(e,t,Pe);if(y(e))return U(te(je,e));var r=y(t)?t:{};return r.get=e,r.name||(r.name=e.name||""),new Le(r)};Object.assign(Ae,Pe),Ae.struct=U(Se);var xe,Ee=0,Te=1,Ie=null!=(_e=null==(we=i((function(){}),"name"))?void 0:we.configurable)&&_e,Ce={value:"action",configurable:!0,writable:!1,enumerable:!1};function ke(e,t,r,n){function i(){return De(e,r,t,n||this,arguments)}return void 0===r&&(r=!1),i.isMobxAction=!0,Ie&&(Ce.value=e,Object.defineProperty(i,"name",Ce)),i}function De(t,r,n,i,o){var a=function(e,t,r,n){var i=!1,o=0,a=rt.trackingDerivation,s=!t||!a;at();var u=rt.allowStateChanges;s&&(Ye(),u=Ne(!0));var c=Xe(!0),l={runAsAction_:s,prevDerivation_:a,prevAllowStateChanges_:u,prevAllowStateReads_:c,notifySpy_:i,startTime_:o,actionId_:Te++,parentActionId_:Ee};return Ee=l.actionId_,l}(0,r);try{return n.apply(i,o)}catch(e){throw a.error_=e,e}finally{!function(t){Ee!==t.actionId_&&e(30);Ee=t.parentActionId_,void 0!==t.error_&&(rt.suppressReactionErrors=!0);Ve(t.prevAllowStateChanges_),Ze(t.prevAllowStateReads_),st(),t.runAsAction_&&Qe(t.prevDerivation_);rt.suppressReactionErrors=!1}(a)}}function Ne(e){var t=rt.allowStateChanges;return rt.allowStateChanges=e,t}function Ve(e){rt.allowStateChanges=e}xe=Symbol.toPrimitive;var Re,Ue=function(e){function t(t,r,n,i,o){var a;return void 0===n&&(n="ObservableValue"),void 0===o&&(o=H.default),(a=e.call(this,n)||this).enhancer=void 0,a.name_=void 0,a.equals=void 0,a.hasUnreportedChange_=!1,a.interceptors_=void 0,a.changeListeners_=void 0,a.value_=void 0,a.dehancer=void 0,a.enhancer=r,a.name_=n,a.equals=o,a.value_=r(t,void 0,n),a}k(t,e);var r=t.prototype;return r.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.set=function(e){this.value_,(e=this.prepareNewValue_(e))!==rt.UNCHANGED&&this.setNewValue_(e)},r.prepareNewValue_=function(e){if(Xt(this)){var t=Jt(this,{object:this,type:or,newValue:e});if(!t)return rt.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value_,this.name_),this.equals(this.value_,e)?rt.UNCHANGED:e},r.setNewValue_=function(e){var t=this.value_;this.value_=e,this.reportChanged(),er(this)&&rr(this,{type:or,object:this,newValue:e,oldValue:t})},r.get=function(){return this.reportObserved(),this.dehanceValue(this.value_)},r.intercept_=function(e){return Zt(this,e)},r.observe_=function(e,t){return t&&e({observableKind:"value",debugObjectName:this.name_,object:this,type:or,newValue:this.value_,oldValue:void 0}),tr(this,e)},r.raw=function(){return this.value_},r.toJSON=function(){return this.get()},r.toString=function(){return this.name_+"["+this.value_+"]"},r.valueOf=function(){return A(this.get())},r[xe]=function(){return this.valueOf()},t}(F),Me=w("ObservableValue",Ue);Re=Symbol.toPrimitive;var ze,Fe,Le=function(){function t(t){this.dependenciesState_=ze.NOT_TRACKING_,this.observing_=[],this.newObserving_=null,this.isBeingObserved_=!1,this.isPendingUnobservation_=!1,this.observers_=new Set,this.diffValue_=0,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=ze.UP_TO_DATE_,this.unboundDepsCount_=0,this.value_=new He(null),this.name_=void 0,this.triggeredBy_=void 0,this.isComputing_=!1,this.isRunningSetter_=!1,this.derivation=void 0,this.setter_=void 0,this.isTracing_=Fe.NONE,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,t.get||e(31),this.derivation=t.get,this.name_=t.name||"ComputedValue",t.set&&(this.setter_=ke("ComputedValue-setter",t.set)),this.equals_=t.equals||(t.compareStructural||t.struct?H.structural:H.default),this.scope_=t.context,this.requiresReaction_=!!t.requiresReaction,this.keepAlive_=!!t.keepAlive}var r=t.prototype;return r.onBecomeStale_=function(){!function(e){if(e.lowestObserverState_!==ze.UP_TO_DATE_)return;e.lowestObserverState_=ze.POSSIBLY_STALE_,e.observers_.forEach((function(e){e.dependenciesState_===ze.UP_TO_DATE_&&(e.dependenciesState_=ze.POSSIBLY_STALE_,e.onBecomeStale_())}))}(this)},r.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},r.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},r.get=function(){if(this.isComputing_&&e(32,this.name_,this.derivation),0!==rt.inBatch||0!==this.observers_.size||this.keepAlive_){if(ut(this),Ge(this)){var t=rt.trackingContext;this.keepAlive_&&!t&&(rt.trackingContext=this),this.trackAndCompute()&&function(e){if(e.lowestObserverState_===ze.STALE_)return;e.lowestObserverState_=ze.STALE_,e.observers_.forEach((function(t){t.dependenciesState_===ze.POSSIBLY_STALE_?t.dependenciesState_=ze.STALE_:t.dependenciesState_===ze.UP_TO_DATE_&&(e.lowestObserverState_=ze.UP_TO_DATE_)}))}(this),rt.trackingContext=t}}else Ge(this)&&(this.warnAboutUntrackedRead_(),at(),this.value_=this.computeValue_(!1),st());var r=this.value_;if(Be(r))throw r.cause;return r},r.set=function(t){if(this.setter_){this.isRunningSetter_&&e(33,this.name_),this.isRunningSetter_=!0;try{this.setter_.call(this.scope_,t)}finally{this.isRunningSetter_=!1}}else e(34,this.name_)},r.trackAndCompute=function(){var e=this.value_,t=this.dependenciesState_===ze.NOT_TRACKING_,r=this.computeValue_(!0),n=t||Be(e)||Be(r)||!this.equals_(e,r);return n&&(this.value_=r),n},r.computeValue_=function(e){this.isComputing_=!0;var t,r=Ne(!1);if(e)t=Ke(this,this.derivation,this.scope_);else if(!0===rt.disableErrorBoundaries)t=this.derivation.call(this.scope_);else try{t=this.derivation.call(this.scope_)}catch(e){t=new He(e)}return Ve(r),this.isComputing_=!1,t},r.suspend_=function(){this.keepAlive_||(qe(this),this.value_=void 0)},r.observe_=function(e,t){var r=this,n=!0,i=void 0;return function(e,t){var r,n;void 0===t&&(t=u);var i,o=null!=(r=null==(n=t)?void 0:n.name)?r:"Autorun";if(t.scheduler||t.delay){var a=xt(t),s=!1;i=new lt(o,(function(){s||(s=!0,a((function(){s=!1,i.isDisposed_||i.track(c)})))}),t.onError,t.requiresObservable)}else i=new lt(o,(function(){this.track(c)}),t.onError,t.requiresObservable);function c(){e(i)}return i.schedule_(),i.getDisposer_()}((function(){var o=r.get();if(!n||t){var a=Ye();e({observableKind:"computed",debugObjectName:r.name_,type:or,object:r,newValue:o,oldValue:i}),Qe(a)}n=!1,i=o}))},r.warnAboutUntrackedRead_=function(){},r.toString=function(){return this.name_+"["+this.derivation.toString()+"]"},r.valueOf=function(){return A(this.get())},r[Re]=function(){return this.valueOf()},t}(),$e=w("ComputedValue",Le);!function(e){e[e.NOT_TRACKING_=-1]="NOT_TRACKING_",e[e.UP_TO_DATE_=0]="UP_TO_DATE_",e[e.POSSIBLY_STALE_=1]="POSSIBLY_STALE_",e[e.STALE_=2]="STALE_"}(ze||(ze={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(Fe||(Fe={}));var He=function(e){this.cause=void 0,this.cause=e};function Be(e){return e instanceof He}function Ge(e){switch(e.dependenciesState_){case ze.UP_TO_DATE_:return!1;case ze.NOT_TRACKING_:case ze.STALE_:return!0;case ze.POSSIBLY_STALE_:for(var t=Xe(!0),r=Ye(),n=e.observing_,i=n.length,o=0;on&&(n=s.dependenciesState_)}r.length=i,e.newObserving_=null,o=t.length;for(;o--;){var u=t[o];0===u.diffValue_&&it(u,e),u.diffValue_=0}for(;i--;){var c=r[i];1===c.diffValue_&&(c.diffValue_=0,nt(c,e))}n!==ze.UP_TO_DATE_&&(e.dependenciesState_=n,e.onBecomeStale_())}(e),Ze(n),i}function qe(e){var t=e.observing_;e.observing_=[];for(var r=t.length;r--;)it(t[r],e);e.dependenciesState_=ze.NOT_TRACKING_}function We(e){var t=Ye();try{return e()}finally{Qe(t)}}function Ye(){var e=rt.trackingDerivation;return rt.trackingDerivation=null,e}function Qe(e){rt.trackingDerivation=e}function Xe(e){var t=rt.allowStateReads;return rt.allowStateReads=e,t}function Ze(e){rt.allowStateReads=e}function Je(e){if(e.dependenciesState_!==ze.UP_TO_DATE_){e.dependenciesState_=ze.UP_TO_DATE_;for(var t=e.observing_,r=t.length;r--;)t[r].lowestObserverState_=ze.UP_TO_DATE_}}var et=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},tt=!0,rt=function(){var t=r();return t.__mobxInstanceCount>0&&!t.__mobxGlobals&&(tt=!1),t.__mobxGlobals&&t.__mobxGlobals.version!==(new et).version&&(tt=!1),tt?t.__mobxGlobals?(t.__mobxInstanceCount+=1,t.__mobxGlobals.UNCHANGED||(t.__mobxGlobals.UNCHANGED={}),t.__mobxGlobals):(t.__mobxInstanceCount=1,t.__mobxGlobals=new et):(setTimeout((function(){e(35)}),1),new et)}();function nt(e,t){e.observers_.add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function it(e,t){e.observers_.delete(t),0===e.observers_.size&&ot(e)}function ot(e){!1===e.isPendingUnobservation_&&(e.isPendingUnobservation_=!0,rt.pendingUnobservations.push(e))}function at(){rt.inBatch++}function st(){if(0==--rt.inBatch){ft();for(var e=rt.pendingUnobservations,t=0;t0&&ot(e),!1)}function ct(e){e.lowestObserverState_!==ze.STALE_&&(e.lowestObserverState_=ze.STALE_,e.observers_.forEach((function(e){e.dependenciesState_===ze.UP_TO_DATE_&&e.onBecomeStale_(),e.dependenciesState_=ze.STALE_})))}var lt=function(){function t(e,t,r,n){void 0===e&&(e="Reaction"),void 0===n&&(n=!1),this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=ze.NOT_TRACKING_,this.diffValue_=0,this.runId_=0,this.unboundDepsCount_=0,this.isDisposed_=!1,this.isScheduled_=!1,this.isTrackPending_=!1,this.isRunning_=!1,this.isTracing_=Fe.NONE,this.name_=e,this.onInvalidate_=t,this.errorHandler_=r,this.requiresObservable_=n}var r=t.prototype;return r.onBecomeStale_=function(){this.schedule_()},r.schedule_=function(){this.isScheduled_||(this.isScheduled_=!0,rt.pendingReactions.push(this),ft())},r.isScheduled=function(){return this.isScheduled_},r.runReaction_=function(){if(!this.isDisposed_){at(),this.isScheduled_=!1;var e=rt.trackingContext;if(rt.trackingContext=this,Ge(this)){this.isTrackPending_=!0;try{this.onInvalidate_()}catch(e){this.reportExceptionInDerivation_(e)}}rt.trackingContext=e,st()}},r.track=function(e){if(!this.isDisposed_){at(),this.isRunning_=!0;var t=rt.trackingContext;rt.trackingContext=this;var r=Ke(this,e,void 0);rt.trackingContext=t,this.isRunning_=!1,this.isTrackPending_=!1,this.isDisposed_&&qe(this),Be(r)&&this.reportExceptionInDerivation_(r.cause),st()}},r.reportExceptionInDerivation_=function(e){var t=this;if(this.errorHandler_)this.errorHandler_(e,this);else{if(rt.disableErrorBoundaries)throw e;var r="[mobx] uncaught error in '"+this+"'";rt.suppressReactionErrors||console.error(r,e),rt.globalReactionErrorHandlers.forEach((function(r){return r(e,t)}))}},r.dispose=function(){this.isDisposed_||(this.isDisposed_=!0,this.isRunning_||(at(),qe(this),st()))},r.getDisposer_=function(){var e=this.dispose.bind(this);return e[z]=this,e},r.toString=function(){return"Reaction["+this.name_+"]"},r.trace=function(t){void 0===t&&(t=!1),function(){e("trace() is not available in production builds");for(var t=!1,r=arguments.length,n=new Array(r),i=0;i0||rt.isRunningReactions||function(e){e()}(pt)}function pt(){rt.isRunningReactions=!0;for(var e=rt.pendingReactions,t=0;e.length>0;){100==++t&&(console.error("[mobx] cycle in reaction: "+e[0]),e.splice(0));for(var r=e.splice(0),n=0,i=r.length;n",i=function(){var e,t=this,i=arguments,o=++kt,a=Ot(n+" - runid: "+o+" - init",r).apply(t,i),s=void 0,u=new Promise((function(t,r){var i=0;function u(e){var t;s=void 0;try{t=Ot(n+" - runid: "+o+" - yield "+i++,a.next).call(a,e)}catch(e){return r(e)}l(t)}function c(e){var t;s=void 0;try{t=Ot(n+" - runid: "+o+" - yield "+i++,a.throw).call(a,e)}catch(e){return r(e)}l(t)}function l(e){if(!b(null==e?void 0:e.then))return e.done?t(e.value):(s=Promise.resolve(e.value)).then(u,c);e.then(l,r)}e=r,u(void 0)}));return u.cancel=Ot(n+" - runid: "+o+" - cancel",(function(){try{s&&Ut(s);var t=a.return(void 0),r=Promise.resolve(t.value);r.then(h,h),Ut(r),e(new Dt)}catch(t){e(t)}})),u};return i.isMobXFlow=!0,i}),Nt);function Ut(e){b(e.cancel)&&e.cancel()}function Mt(e){return!0===(null==e?void 0:e.isMobXFlow)}function zt(e,t,r){var n;return Pr(e)||yr(e)||Me(e)?n=Gr(e):Nr(e)&&(n=Gr(e,t)),n.dehancer="function"==typeof t?t:r,function(){n.dehancer=void 0}}function Ft(e,t,r){return b(r)?function(e,t,r){return Gr(e,t).intercept_(r)}(e,t,r):function(e,t){return Gr(e).intercept_(t)}(e,t)}function Lt(e){return function(e,t){return!!e&&(void 0!==t?!!Nr(e)&&e[z].values_.has(t):Nr(e)||!!e[z]||L(e)||ht(e)||$e(e))}(e)}function $t(t){return Nr(t)?t[z].keys_():Pr(t)||xr(t)?Array.from(t.keys()):yr(t)?t.map((function(e,t){return t})):void e(5)}function Ht(t){return Nr(t)?$t(t).map((function(e){return t[e]})):Pr(t)?$t(t).map((function(e){return t.get(e)})):xr(t)?Array.from(t.values()):yr(t)?t.slice():void e(6)}function Bt(t,r,n){if(2!==arguments.length||xr(t))Nr(t)?t[z].set_(r,n):Pr(t)?t.set(r,n):xr(t)?t.add(r):yr(t)?("number"!=typeof r&&(r=parseInt(r,10)),r<0&&e("Invalid index: '"+r+"'"),at(),r>=t.length&&(t.length=r+1),t[r]=n,st()):e(8);else{at();var i=r;try{for(var o in i)Bt(t,o,i[o])}finally{st()}}}function Gt(t,r,n){if(Nr(t))return t[z].defineProperty_(r,n);e(39)}function Kt(e,t,r,n){return b(r)?function(e,t,r,n){return Gr(e,t).observe_(r,n)}(e,t,r,n):function(e,t,r){return Gr(e).observe_(t,r)}(e,t,r)}function qt(e){switch(e.length){case 0:return rt.trackingDerivation;case 1:return Br(e[0]);case 2:return Br(e[0],e[1])}}function Wt(e,t){void 0===t&&(t=void 0),at();try{return e.apply(t)}finally{st()}}function Yt(e){return e[z]}Rt.bound=U(Vt);var Qt={has:function(e,t){return Yt(e).has_(t)},get:function(e,t){return Yt(e).get_(t)},set:function(e,t,r){var n;return!!d(t)&&(null==(n=Yt(e).set_(t,r,!0))||n)},deleteProperty:function(e,t){var r;return!!d(t)&&(null==(r=Yt(e).delete_(t,!0))||r)},defineProperty:function(e,t,r){var n;return null==(n=Yt(e).defineProperty_(t,r))||n},ownKeys:function(e){return Yt(e).ownKeys_()},preventExtensions:function(t){e(13)}};function Xt(e){return void 0!==e.interceptors_&&e.interceptors_.length>0}function Zt(e,t){var r=e.interceptors_||(e.interceptors_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function Jt(t,r){var n=Ye();try{for(var i=[].concat(t.interceptors_||[]),o=0,a=i.length;o0}function tr(e,t){var r=e.changeListeners_||(e.changeListeners_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function rr(e,t){var r=Ye(),n=e.changeListeners_;if(n){for(var i=0,o=(n=n.slice()).length;i0?e.map(this.dehancer):e},r.intercept_=function(e){return Zt(this,e)},r.observe_=function(e,t){return void 0===t&&(t=!1),t&&e({observableKind:"array",object:this.proxy_,debugObjectName:this.atom_.name_,type:"splice",index:0,added:this.values_.slice(),addedCount:this.values_.length,removed:[],removedCount:0}),tr(this,e)},r.getArrayLength_=function(){return this.atom_.reportObserved(),this.values_.length},r.setArrayLength_=function(t){("number"!=typeof t||t<0)&&e("Out of range: "+t);var r=this.values_.length;if(t!==r)if(t>r){for(var n=new Array(t-r),i=0;i0&&$r(t+r+1)},r.spliceWithArray_=function(e,t,r){var n=this;this.atom_;var i=this.values_.length;if(void 0===e?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=1===arguments.length?i-e:null==t?0:Math.max(0,Math.min(t,i-e)),void 0===r&&(r=s),Xt(this)){var o=Jt(this,{object:this.proxy_,type:ir,index:e,removedCount:t,added:r});if(!o)return s;t=o.removedCount,r=o.added}if(r=0===r.length?r:r.map((function(e){return n.enhancer_(e,void 0)})),this.legacyMode_){var a=r.length-t;this.updateArrayLength_(i,a)}var u=this.spliceItemsIntoValues_(e,t,r);return 0===t&&0===r.length||this.notifyArraySplice_(e,r,u),this.dehanceValues_(u)},r.spliceItemsIntoValues_=function(e,t,r){var n;if(r.length<1e4)return(n=this.values_).splice.apply(n,[e,t].concat(r));var i=this.values_.slice(e,e+t),o=this.values_.slice(e+t);this.values_.length=e+r.length-t;for(var a=0;a2?r-2:0),i=2;i-1&&(this.splice(r,1),!0)}};function lr(e,t){"function"==typeof Array.prototype[e]&&(cr[e]=t(e))}function fr(e){return function(){var t=this[z];t.atom_.reportObserved();var r=t.dehanceValues_(t.values_);return r[e].apply(r,arguments)}}function pr(e){return function(t,r){var n=this,i=this[z];return i.atom_.reportObserved(),i.dehanceValues_(i.values_)[e]((function(e,i){return t.call(r,e,i,n)}))}}function hr(e){return function(){var t=this,r=this[z];r.atom_.reportObserved();var n=r.dehanceValues_(r.values_),i=arguments[0];return arguments[0]=function(e,r,n){return i(e,r,n,t)},n[e].apply(n,arguments)}}lr("concat",fr),lr("flat",fr),lr("includes",fr),lr("indexOf",fr),lr("join",fr),lr("lastIndexOf",fr),lr("slice",fr),lr("toString",fr),lr("toLocaleString",fr),lr("every",pr),lr("filter",pr),lr("find",pr),lr("findIndex",pr),lr("flatMap",pr),lr("forEach",pr),lr("map",pr),lr("some",pr),lr("reduce",hr),lr("reduceRight",hr);var br,dr,vr=w("ObservableArrayAdministration",sr);function yr(e){return v(e)&&vr(e[z])}var gr={},mr="add",_r="delete";br=Symbol.iterator,dr=Symbol.toStringTag;var wr,Or,jr=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableMap"),this.enhancer_=void 0,this.name_=void 0,this[z]=gr,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=r,this.name_=n,b(Map)||e(18),this.keysAtom_=$("ObservableMap.keys()"),this.data_=new Map,this.hasMap_=new Map,this.merge(t)}var r=t.prototype;return r.has_=function(e){return this.data_.has(e)},r.has=function(e){var t=this;if(!rt.trackingDerivation)return this.has_(e);var r=this.hasMap_.get(e);if(!r){var n=r=new Ue(this.has_(e),G,"ObservableMap.key?",!1);this.hasMap_.set(e,n),It(n,(function(){return t.hasMap_.delete(e)}))}return r.get()},r.set=function(e,t){var r=this.has_(e);if(Xt(this)){var n=Jt(this,{type:r?or:mr,object:this,newValue:t,name:e});if(!n)return this;t=n.newValue}return r?this.updateValue_(e,t):this.addValue_(e,t),this},r.delete=function(e){var t=this;if((this.keysAtom_,Xt(this))&&!Jt(this,{type:_r,object:this,name:e}))return!1;if(this.has_(e)){var r=er(this),n=r?{observableKind:"map",debugObjectName:this.name_,type:_r,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return Wt((function(){t.keysAtom_.reportChanged(),t.updateHasMapEntry_(e,!1),t.data_.get(e).setNewValue_(void 0),t.data_.delete(e)})),r&&rr(this,n),!0}return!1},r.updateHasMapEntry_=function(e,t){var r=this.hasMap_.get(e);r&&r.setNewValue_(t)},r.updateValue_=function(e,t){var r=this.data_.get(e);if((t=r.prepareNewValue_(t))!==rt.UNCHANGED){var n=er(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:or,object:this,oldValue:r.value_,name:e,newValue:t}:null;r.setNewValue_(t),n&&rr(this,i)}},r.addValue_=function(e,t){var r=this;this.keysAtom_,Wt((function(){var n=new Ue(t,r.enhancer_,"ObservableMap.key",!1);r.data_.set(e,n),t=n.value_,r.updateHasMapEntry_(e,!0),r.keysAtom_.reportChanged()}));var n=er(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:mr,object:this,name:e,newValue:t}:null;n&&rr(this,i)},r.get=function(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)},r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.keys=function(){return this.keysAtom_.reportObserved(),this.data_.keys()},r.values=function(){var e=this,t=this.keys();return Xr({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:e.get(i)}}})},r.entries=function(){var e=this,t=this.keys();return Xr({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:[i,e.get(i)]}}})},r[br]=function(){return this.entries()},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value,o=i[0],a=i[1];e.call(t,a,o,this)}},r.merge=function(t){var r=this;return Pr(t)&&(t=new Map(t)),Wt((function(){y(t)?function(e){var t=Object.keys(e);if(!P)return t;var r=Object.getOwnPropertySymbols(e);return r.length?[].concat(t,r.filter((function(t){return a.propertyIsEnumerable.call(e,t)}))):t}(t).forEach((function(e){return r.set(e,t[e])})):Array.isArray(t)?t.forEach((function(e){var t=e[0],n=e[1];return r.set(t,n)})):O(t)?(t.constructor!==Map&&e(19,t),t.forEach((function(e,t){return r.set(t,e)}))):null!=t&&e(20,t)})),this},r.clear=function(){var e=this;Wt((function(){We((function(){for(var t,r=V(e.keys());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.replace=function(t){var r=this;return Wt((function(){for(var n,i=function(t){if(O(t)||Pr(t))return t;if(Array.isArray(t))return new Map(t);if(y(t)){var r=new Map;for(var n in t)r.set(n,t[n]);return r}return e(21,t)}(t),o=new Map,a=!1,s=V(r.data_.keys());!(n=s()).done;){var u=n.value;if(!i.has(u))if(r.delete(u))a=!0;else{var c=r.data_.get(u);o.set(u,c)}}for(var l,f=V(i.entries());!(l=f()).done;){var p=l.value,h=p[0],b=p[1],d=r.data_.has(h);if(r.set(h,b),r.data_.has(h)){var v=r.data_.get(h);o.set(h,v),d||(a=!0)}}if(!a)if(r.data_.size!==o.size)r.keysAtom_.reportChanged();else for(var g=r.data_.keys(),m=o.keys(),_=g.next(),w=m.next();!_.done;){if(_.value!==w.value){r.keysAtom_.reportChanged();break}_=g.next(),w=m.next()}r.data_=o})),this},r.toString=function(){return"[object ObservableMap]"},r.toJSON=function(){return Array.from(this)},r.observe_=function(e,t){return tr(this,e)},r.intercept_=function(e){return Zt(this,e)},I(t,[{key:"size",get:function(){return this.keysAtom_.reportObserved(),this.data_.size}},{key:dr,get:function(){return"Map"}}]),t}(),Pr=w("ObservableMap",jr);var Sr={};wr=Symbol.iterator,Or=Symbol.toStringTag;var Ar=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableSet"),this.name_=void 0,this[z]=Sr,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,b(Set)||e(22),this.atom_=$(this.name_),this.enhancer_=function(e,t){return r(e,t,n)},t&&this.replace(t)}var r=t.prototype;return r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.clear=function(){var e=this;Wt((function(){We((function(){for(var t,r=V(e.data_.values());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value;e.call(t,i,i,this)}},r.add=function(e){var t=this;if((this.atom_,Xt(this))&&!Jt(this,{type:mr,object:this,newValue:e}))return this;if(!this.has(e)){Wt((function(){t.data_.add(t.enhancer_(e,void 0)),t.atom_.reportChanged()}));var r=er(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:mr,object:this,newValue:e}:null;r&&rr(this,n)}return this},r.delete=function(e){var t=this;if(Xt(this)&&!Jt(this,{type:_r,object:this,oldValue:e}))return!1;if(this.has(e)){var r=er(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:_r,object:this,oldValue:e}:null;return Wt((function(){t.atom_.reportChanged(),t.data_.delete(e)})),r&&rr(this,n),!0}return!1},r.has=function(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))},r.entries=function(){var e=0,t=Array.from(this.keys()),r=Array.from(this.values());return Xr({next:function(){var n=e;return e+=1,nMr){for(var t=Mr;t=0&&r++}e=Qr(e),t=Qr(t);var s="[object Array]"===a;if(!s){if("object"!=typeof e||"object"!=typeof t)return!1;var u=e.constructor,c=t.constructor;if(u!==c&&!(b(u)&&u instanceof u&&b(c)&&c instanceof c)&&"constructor"in e&&"constructor"in t)return!1}if(0===r)return!1;r<0&&(r=-1),i=i||[];for(var l=(n=n||[]).length;l--;)if(n[l]===e)return i[l]===t;if(n.push(e),i.push(t),s){if((l=e.length)!==t.length)return!1;for(;l--;)if(!Yr(e[l],t[l],r-1,n,i))return!1}else{var f,p=Object.keys(e);if(l=p.length,Object.keys(t).length!==l)return!1;for(;l--;)if(!x(t,f=p[l])||!Yr(e[f],t[f],r-1,n,i))return!1}return n.pop(),i.pop(),!0}function Qr(e){return yr(e)?e.slice():O(e)||Pr(e)||j(e)||xr(e)?Array.from(e.entries()):e}function Xr(e){return e[Symbol.iterator]=Zr,e}function Zr(){return this}["Symbol","Map","Set","Symbol"].forEach((function(t){void 0===r()[t]&&e("MobX requires global '"+t+"' to be available or polyfilled")})),"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:function(e){return console.warn("[mobx.spy] Is a no-op in production builds"),function(){}},extras:{getDebugName:Kr},$mobx:z});var Jr;!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(Jr||(Jr={})); +/*! ***************************************************************************** + Copyright (c) Microsoft Corporation. -(function(l, r) { if (!l || l.getElementById('livereloadscript')) return; r = l.createElement('script'); r.async = 1; r.src = '//' + (self.location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1'; r.id = 'livereloadscript'; l.getElementsByTagName('head')[0].appendChild(r) })(self.document); -var JSpider = (function () { - 'use strict'; - - function die(error) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - throw new Error(typeof error === "number" ? "[MobX] minified error nr: " + error + (args.length ? " " + args.map(String).join(",") : "") + ". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts" : "[MobX] " + error); - } - - var mockGlobal = {}; - function getGlobal() { - if (typeof globalThis !== "undefined") { - return globalThis; - } - - if (typeof window !== "undefined") { - return window; - } - - if (typeof global !== "undefined") { - return global; - } - - if (typeof self !== "undefined") { - return self; - } - - return mockGlobal; - } - - var assign = Object.assign; - var getDescriptor = Object.getOwnPropertyDescriptor; - var defineProperty$2 = Object.defineProperty; - var objectPrototype = Object.prototype; - var EMPTY_ARRAY$1 = []; - Object.freeze(EMPTY_ARRAY$1); - var EMPTY_OBJECT$1 = {}; - Object.freeze(EMPTY_OBJECT$1); - var hasProxy = typeof Proxy !== "undefined"; - var plainObjectString$1 = /*#__PURE__*/Object.toString(); - function assertProxies() { - if (!hasProxy) { - die("Proxy not available"); - } - } - /** - * Makes sure that the provided function is invoked at most once. - */ - - function once(func) { - var invoked = false; - return function () { - if (invoked) return; - invoked = true; - return func.apply(this, arguments); - }; - } - var noop$1 = function noop() {}; - function isFunction$2(fn) { - return typeof fn === "function"; - } - function isStringish(value) { - var t = typeof value; - - switch (t) { - case "string": - case "symbol": - case "number": - return true; - } - - return false; - } - function isObject$2(value) { - return value !== null && typeof value === "object"; - } - function isPlainObject$1(value) { - var _proto$constructor; - - if (!isObject$2(value)) return false; - var proto = Object.getPrototypeOf(value); - if (proto == null) return true; - return ((_proto$constructor = proto.constructor) == null ? void 0 : _proto$constructor.toString()) === plainObjectString$1; - } // https://stackoverflow.com/a/37865170 - - function isGenerator(obj) { - var constructor = obj == null ? void 0 : obj.constructor; - if (!constructor) return false; - if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) return true; - return false; - } - function addHiddenProp(object, propName, value) { - defineProperty$2(object, propName, { - enumerable: false, - writable: true, - configurable: true, - value: value - }); - } - function addHiddenFinalProp$1(object, propName, value) { - defineProperty$2(object, propName, { - enumerable: false, - writable: false, - configurable: true, - value: value - }); - } - function createInstanceofPredicate(name, theClass) { - var propName = "isMobX" + name; - theClass.prototype[propName] = true; - return function (x) { - return isObject$2(x) && x[propName] === true; - }; - } - function isES6Map(thing) { - return thing instanceof Map; - } - function isES6Set(thing) { - return thing instanceof Set; - } - var hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefined"; - /** - * Returns the following: own enumerable keys and symbols. - */ - - function getPlainObjectKeys(object) { - var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway... - - if (!hasGetOwnPropertySymbols) return keys; - var symbols = Object.getOwnPropertySymbols(object); - if (!symbols.length) return keys; - return [].concat(keys, symbols.filter(function (s) { - return objectPrototype.propertyIsEnumerable.call(object, s); - })); - } // From Immer utils - // Returns all own keys, including non-enumerable and symbolic - - var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) { - return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj)); - } : - /* istanbul ignore next */ - Object.getOwnPropertyNames; - function toPrimitive(value) { - return value === null ? null : typeof value === "object" ? "" + value : value; - } - function hasProp(target, prop) { - return objectPrototype.hasOwnProperty.call(target, prop); - } // From Immer utils - - var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) { - // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274 - var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up - - ownKeys(target).forEach(function (key) { - res[key] = getDescriptor(target, key); - }); - return res; - }; - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _createForOfIteratorHelperLoose(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - var storedAnnotationsSymbol = /*#__PURE__*/Symbol("mobx-stored-annotations"); - /** - * Creates a function that acts as - * - decorator - * - annotation object - */ - - function createDecoratorAnnotation(annotation) { - function decorator(target, property) { - storeAnnotation(target, property, annotation); - } - - return Object.assign(decorator, annotation); - } - /** - * Stores annotation to prototype, - * so it can be inspected later by `makeObservable` called from constructor - */ - - function storeAnnotation(prototype, key, annotation) { - if (!hasProp(prototype, storedAnnotationsSymbol)) { - addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol])); - } // @override must override something - - if (!isOverride(annotation)) { - prototype[storedAnnotationsSymbol][key] = annotation; - } - } - /** - * Collects annotations from prototypes and stores them on target (instance) - */ - - - function collectStoredAnnotations(target) { - if (!hasProp(target, storedAnnotationsSymbol)) { - - - addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol])); - } - - return target[storedAnnotationsSymbol]; - } - - var $mobx = /*#__PURE__*/Symbol("mobx administration"); - var Atom = /*#__PURE__*/function () { - // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed - - /** - * Create a new atom. For debugging purposes it is recommended to give it a name. - * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management. - */ - function Atom(name_) { - if (name_ === void 0) { - name_ = "Atom"; - } - - this.name_ = void 0; - this.isPendingUnobservation_ = false; - this.isBeingObserved_ = false; - this.observers_ = new Set(); - this.diffValue_ = 0; - this.lastAccessedBy_ = 0; - this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_; - this.onBOL = void 0; - this.onBUOL = void 0; - this.name_ = name_; - } // onBecomeObservedListeners - - - var _proto = Atom.prototype; - - _proto.onBO = function onBO() { - if (this.onBOL) { - this.onBOL.forEach(function (listener) { - return listener(); - }); - } - }; - - _proto.onBUO = function onBUO() { - if (this.onBUOL) { - this.onBUOL.forEach(function (listener) { - return listener(); - }); - } - } - /** - * Invoke this method to notify mobx that your atom has been used somehow. - * Returns true if there is currently a reactive context. - */ - ; - - _proto.reportObserved = function reportObserved$1() { - return reportObserved(this); - } - /** - * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate. - */ - ; - - _proto.reportChanged = function reportChanged() { - startBatch(); - propagateChanged(this); - endBatch(); - }; - - _proto.toString = function toString() { - return this.name_; - }; - - return Atom; - }(); - var isAtom = /*#__PURE__*/createInstanceofPredicate("Atom", Atom); - function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { - if (onBecomeObservedHandler === void 0) { - onBecomeObservedHandler = noop$1; - } - - if (onBecomeUnobservedHandler === void 0) { - onBecomeUnobservedHandler = noop$1; - } - - var atom = new Atom(name); // default `noop` listener will not initialize the hook Set - - if (onBecomeObservedHandler !== noop$1) { - onBecomeObserved(atom, onBecomeObservedHandler); - } - - if (onBecomeUnobservedHandler !== noop$1) { - onBecomeUnobserved(atom, onBecomeUnobservedHandler); - } - - return atom; - } - - function identityComparer(a, b) { - return a === b; - } - - function structuralComparer(a, b) { - return deepEqual(a, b); - } - - function shallowComparer(a, b) { - return deepEqual(a, b, 1); - } - - function defaultComparer(a, b) { - return Object.is(a, b); - } - - var comparer = { - identity: identityComparer, - structural: structuralComparer, - "default": defaultComparer, - shallow: shallowComparer - }; - - function deepEnhancer(v, _, name) { - // it is an observable already, done - if (isObservable(v)) return v; // something that can be converted and mutated? - - if (Array.isArray(v)) return observable$1.array(v, { - name: name - }); - if (isPlainObject$1(v)) return observable$1.object(v, undefined, { - name: name - }); - if (isES6Map(v)) return observable$1.map(v, { - name: name - }); - if (isES6Set(v)) return observable$1.set(v, { - name: name - }); - - if (typeof v === "function" && !isAction(v) && !isFlow(v)) { - if (isGenerator(v)) { - return flow(v); - } else { - return autoAction(name, v); - } - } - - return v; - } - function shallowEnhancer(v, _, name) { - if (v === undefined || v === null) return v; - if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) return v; - if (Array.isArray(v)) return observable$1.array(v, { - name: name, - deep: false - }); - if (isPlainObject$1(v)) return observable$1.object(v, undefined, { - name: name, - deep: false - }); - if (isES6Map(v)) return observable$1.map(v, { - name: name, - deep: false - }); - if (isES6Set(v)) return observable$1.set(v, { - name: name, - deep: false - }); - } - function referenceEnhancer(newValue) { - // never turn into an observable - return newValue; - } - function refStructEnhancer(v, oldValue) { - if (deepEqual(v, oldValue)) return oldValue; - return v; - } - - var OVERRIDE = "override"; - function isOverride(annotation) { - return annotation.annotationType_ === OVERRIDE; - } - - function createActionAnnotation(name, options) { - return { - annotationType_: name, - options_: options, - make_: make_$1, - extend_: extend_$1 - }; - } - - function make_$1(adm, key, descriptor, source) { - var _this$options_; - - // bound - if ((_this$options_ = this.options_) == null ? void 0 : _this$options_.bound) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 1 - /* Break */ - ; - } // own - - - if (source === adm.target_) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 2 - /* Continue */ - ; - } // prototype - - - if (isAction(descriptor.value)) { - // A prototype could have been annotated already by other constructor, - // rest of the proto chain must be annotated already - return 1 - /* Break */ - ; - } - - var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false); - defineProperty$2(source, key, actionDescriptor); - return 2 - /* Continue */ - ; - } - - function extend_$1(adm, key, descriptor, proxyTrap) { - var actionDescriptor = createActionDescriptor(adm, this, key, descriptor); - return adm.defineProperty_(key, actionDescriptor, proxyTrap); - } - - function assertActionDescriptor(adm, _ref, key, _ref2) { - _ref.annotationType_; - _ref2.value; - } - - function createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes - safeDescriptors) { - var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3; - - if (safeDescriptors === void 0) { - safeDescriptors = globalState.safeDescriptors; - } - - assertActionDescriptor(adm, annotation, key, descriptor); - var value = descriptor.value; - - if ((_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.bound) { - var _adm$proxy_; - - value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); - } - - return { - value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false), - // Non-configurable for classes - // prevents accidental field redefinition in subclass - configurable: safeDescriptors ? adm.isPlainObject_ : true, - // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058 - enumerable: false, - // Non-obsevable, therefore non-writable - // Also prevents rewriting in subclass constructor - writable: safeDescriptors ? false : true - }; - } - - function createFlowAnnotation(name, options) { - return { - annotationType_: name, - options_: options, - make_: make_$2, - extend_: extend_$2 - }; - } - - function make_$2(adm, key, descriptor, source) { - var _this$options_; - - // own - if (source === adm.target_) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 2 - /* Continue */ - ; - } // prototype - // bound - must annotate protos to support super.flow() - - - if (((_this$options_ = this.options_) == null ? void 0 : _this$options_.bound) && !isFlow(adm.target_[key])) { - if (this.extend_(adm, key, descriptor, false) === null) return 0 - /* Cancel */ - ; - } - - if (isFlow(descriptor.value)) { - // A prototype could have been annotated already by other constructor, - // rest of the proto chain must be annotated already - return 1 - /* Break */ - ; - } - - var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false); - defineProperty$2(source, key, flowDescriptor); - return 2 - /* Continue */ - ; - } - - function extend_$2(adm, key, descriptor, proxyTrap) { - var _this$options_2; - - var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound); - return adm.defineProperty_(key, flowDescriptor, proxyTrap); - } - - function assertFlowDescriptor(adm, _ref, key, _ref2) { - _ref.annotationType_; - _ref2.value; - } - - function createFlowDescriptor(adm, annotation, key, descriptor, bound, // provides ability to disable safeDescriptors for prototypes - safeDescriptors) { - if (safeDescriptors === void 0) { - safeDescriptors = globalState.safeDescriptors; - } - - assertFlowDescriptor(adm, annotation, key, descriptor); - var value = descriptor.value; - - if (bound) { - var _adm$proxy_; - - value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); - } - - return { - value: flow(value), - // Non-configurable for classes - // prevents accidental field redefinition in subclass - configurable: safeDescriptors ? adm.isPlainObject_ : true, - // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058 - enumerable: false, - // Non-obsevable, therefore non-writable - // Also prevents rewriting in subclass constructor - writable: safeDescriptors ? false : true - }; - } - - function createComputedAnnotation(name, options) { - return { - annotationType_: name, - options_: options, - make_: make_$3, - extend_: extend_$3 - }; - } - - function make_$3(adm, key, descriptor) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 1 - /* Break */ - ; - } - - function extend_$3(adm, key, descriptor, proxyTrap) { - assertComputedDescriptor(adm, this, key, descriptor); - return adm.defineComputedProperty_(key, _extends({}, this.options_, { - get: descriptor.get, - set: descriptor.set - }), proxyTrap); - } - - function assertComputedDescriptor(adm, _ref, key, _ref2) { - _ref.annotationType_; - _ref2.get; - } - - function createObservableAnnotation(name, options) { - return { - annotationType_: name, - options_: options, - make_: make_$4, - extend_: extend_$4 - }; - } - - function make_$4(adm, key, descriptor) { - return this.extend_(adm, key, descriptor, false) === null ? 0 - /* Cancel */ - : 1 - /* Break */ - ; - } - - function extend_$4(adm, key, descriptor, proxyTrap) { - var _this$options_$enhanc, _this$options_; - - assertObservableDescriptor(adm, this); - return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap); - } - - function assertObservableDescriptor(adm, _ref, key, descriptor) { - _ref.annotationType_; - } - - var AUTO = "true"; - var autoAnnotation = /*#__PURE__*/createAutoAnnotation(); - function createAutoAnnotation(options) { - return { - annotationType_: AUTO, - options_: options, - make_: make_$5, - extend_: extend_$5 - }; - } - - function make_$5(adm, key, descriptor, source) { - var _this$options_3, _this$options_4; - - // getter -> computed - if (descriptor.get) { - return computed.make_(adm, key, descriptor, source); - } // lone setter -> action setter - - - if (descriptor.set) { - // TODO make action applicable to setter and delegate to action.make_ - var set = createAction(key.toString(), descriptor.set); // own - - if (source === adm.target_) { - return adm.defineProperty_(key, { - configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true, - set: set - }) === null ? 0 - /* Cancel */ - : 2 - /* Continue */ - ; - } // proto - - - defineProperty$2(source, key, { - configurable: true, - set: set - }); - return 2 - /* Continue */ - ; - } // function on proto -> autoAction/flow - - - if (source !== adm.target_ && typeof descriptor.value === "function") { - var _this$options_2; - - if (isGenerator(descriptor.value)) { - var _this$options_; - - var flowAnnotation = ((_this$options_ = this.options_) == null ? void 0 : _this$options_.autoBind) ? flow.bound : flow; - return flowAnnotation.make_(adm, key, descriptor, source); - } - - var actionAnnotation = ((_this$options_2 = this.options_) == null ? void 0 : _this$options_2.autoBind) ? autoAction.bound : autoAction; - return actionAnnotation.make_(adm, key, descriptor, source); - } // other -> observable - // Copy props from proto as well, see test: - // "decorate should work with Object.create" - - - var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable$1.ref : observable$1; // if function respect autoBind option - - if (typeof descriptor.value === "function" && ((_this$options_4 = this.options_) == null ? void 0 : _this$options_4.autoBind)) { - var _adm$proxy_; - - descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); - } - - return observableAnnotation.make_(adm, key, descriptor, source); - } - - function extend_$5(adm, key, descriptor, proxyTrap) { - var _this$options_5, _this$options_6; - - // getter -> computed - if (descriptor.get) { - return computed.extend_(adm, key, descriptor, proxyTrap); - } // lone setter -> action setter - - - if (descriptor.set) { - // TODO make action applicable to setter and delegate to action.extend_ - return adm.defineProperty_(key, { - configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true, - set: createAction(key.toString(), descriptor.set) - }, proxyTrap); - } // other -> observable - // if function respect autoBind option - - - if (typeof descriptor.value === "function" && ((_this$options_5 = this.options_) == null ? void 0 : _this$options_5.autoBind)) { - var _adm$proxy_2; - - descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_); - } - - var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable$1.ref : observable$1; - return observableAnnotation.extend_(adm, key, descriptor, proxyTrap); - } - - // in the majority of cases - - var defaultCreateObservableOptions = { - deep: true, - name: undefined, - defaultDecorator: undefined, - proxy: true - }; - Object.freeze(defaultCreateObservableOptions); - function asCreateObservableOptions(thing) { - return thing || defaultCreateObservableOptions; - } - var observableAnnotation = /*#__PURE__*/createObservableAnnotation("observable"); - var observableRefAnnotation = /*#__PURE__*/createObservableAnnotation("observable.ref", { - enhancer: referenceEnhancer - }); - var observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation("observable.shallow", { - enhancer: shallowEnhancer - }); - var observableStructAnnotation = /*#__PURE__*/createObservableAnnotation("observable.struct", { - enhancer: refStructEnhancer - }); - var observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation); - function getEnhancerFromOptions(options) { - return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator); - } - function getAnnotationFromOptions(options) { - var _options$defaultDecor; - - return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined; - } - function getEnhancerFromAnnotation(annotation) { - var _annotation$options_$, _annotation$options_; - - return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer; - } - /** - * Turns an object, array or function into a reactive structure. - * @param v the value which should become observable. - */ - - function createObservable(v, arg2, arg3) { - // @observable someProp; - if (isStringish(arg2)) { - storeAnnotation(v, arg2, observableAnnotation); - return; - } // already observable - ignore - - - if (isObservable(v)) return v; // plain object - - if (isPlainObject$1(v)) return observable$1.object(v, arg2, arg3); // Array - - if (Array.isArray(v)) return observable$1.array(v, arg2); // Map - - if (isES6Map(v)) return observable$1.map(v, arg2); // Set - - if (isES6Set(v)) return observable$1.set(v, arg2); // other object - ignore - - if (typeof v === "object" && v !== null) return v; // anything else - - return observable$1.box(v, arg2); - } - - Object.assign(createObservable, observableDecoratorAnnotation); - var observableFactories = { - box: function box(value, options) { - var o = asCreateObservableOptions(options); - return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals); - }, - array: function array(initialValues, options) { - var o = asCreateObservableOptions(options); - return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name); - }, - map: function map(initialValues, options) { - var o = asCreateObservableOptions(options); - return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name); - }, - set: function set(initialValues, options) { - var o = asCreateObservableOptions(options); - return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name); - }, - object: function object(props, decorators, options) { - return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators); - }, - ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation), - shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation), - deep: observableDecoratorAnnotation, - struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation) - }; // eslint-disable-next-line - - var observable$1 = /*#__PURE__*/assign(createObservable, observableFactories); - - var COMPUTED = "computed"; - var COMPUTED_STRUCT = "computed.struct"; - var computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED); - var computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, { - equals: comparer.structural - }); - /** - * Decorator for class properties: @computed get value() { return expr; }. - * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`; - */ - - var computed = function computed(arg1, arg2) { - if (isStringish(arg2)) { - // @computed - return storeAnnotation(arg1, arg2, computedAnnotation); - } - - if (isPlainObject$1(arg1)) { - // @computed({ options }) - return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1)); - } // computed(expr, options?) - - var opts = isPlainObject$1(arg2) ? arg2 : {}; - opts.get = arg1; - opts.name || (opts.name = arg1.name || ""); - /* for generated name */ - - return new ComputedValue(opts); - }; - Object.assign(computed, computedAnnotation); - computed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation); - - var _getDescriptor$config, _getDescriptor; - // mobx versions - - var currentActionId = 0; - var nextActionId$1 = 1; - var isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, "name")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object - - var tmpNameDescriptor = { - value: "action", - configurable: true, - writable: false, - enumerable: false - }; - function createAction(actionName, fn, autoAction, ref) { - if (autoAction === void 0) { - autoAction = false; - } - - function res() { - return executeAction(actionName, autoAction, fn, ref || this, arguments); - } - - res.isMobxAction = true; - - if (isFunctionNameConfigurable) { - tmpNameDescriptor.value = actionName; - Object.defineProperty(res, "name", tmpNameDescriptor); - } - - return res; - } - function executeAction(actionName, canRunAsDerivation, fn, scope, args) { - var runInfo = _startAction(actionName, canRunAsDerivation); - - try { - return fn.apply(scope, args); - } catch (err) { - runInfo.error_ = err; - throw err; - } finally { - _endAction(runInfo); - } - } - function _startAction(actionName, canRunAsDerivation, // true for autoAction - scope, args) { - var notifySpy_ = "production" !== "production" ; - var startTime_ = 0; - - var prevDerivation_ = globalState.trackingDerivation; - var runAsAction = !canRunAsDerivation || !prevDerivation_; - startBatch(); - var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow - - if (runAsAction) { - untrackedStart(); - prevAllowStateChanges_ = allowStateChangesStart(true); - } - - var prevAllowStateReads_ = allowStateReadsStart(true); - var runInfo = { - runAsAction_: runAsAction, - prevDerivation_: prevDerivation_, - prevAllowStateChanges_: prevAllowStateChanges_, - prevAllowStateReads_: prevAllowStateReads_, - notifySpy_: notifySpy_, - startTime_: startTime_, - actionId_: nextActionId$1++, - parentActionId_: currentActionId - }; - currentActionId = runInfo.actionId_; - return runInfo; - } - function _endAction(runInfo) { - if (currentActionId !== runInfo.actionId_) { - die(30); - } - - currentActionId = runInfo.parentActionId_; - - if (runInfo.error_ !== undefined) { - globalState.suppressReactionErrors = true; - } - - allowStateChangesEnd(runInfo.prevAllowStateChanges_); - allowStateReadsEnd(runInfo.prevAllowStateReads_); - endBatch(); - if (runInfo.runAsAction_) untrackedEnd(runInfo.prevDerivation_); - - globalState.suppressReactionErrors = false; - } - function allowStateChanges(allowStateChanges, func) { - var prev = allowStateChangesStart(allowStateChanges); - - try { - return func(); - } finally { - allowStateChangesEnd(prev); - } - } - function allowStateChangesStart(allowStateChanges) { - var prev = globalState.allowStateChanges; - globalState.allowStateChanges = allowStateChanges; - return prev; - } - function allowStateChangesEnd(prev) { - globalState.allowStateChanges = prev; - } - - var _Symbol$toPrimitive; - _Symbol$toPrimitive = Symbol.toPrimitive; - var ObservableValue = /*#__PURE__*/function (_Atom) { - _inheritsLoose(ObservableValue, _Atom); - - function ObservableValue(value, enhancer, name_, notifySpy, equals) { - var _this; - - if (name_ === void 0) { - name_ = "ObservableValue"; - } - - if (equals === void 0) { - equals = comparer["default"]; - } - - _this = _Atom.call(this, name_) || this; - _this.enhancer = void 0; - _this.name_ = void 0; - _this.equals = void 0; - _this.hasUnreportedChange_ = false; - _this.interceptors_ = void 0; - _this.changeListeners_ = void 0; - _this.value_ = void 0; - _this.dehancer = void 0; - _this.enhancer = enhancer; - _this.name_ = name_; - _this.equals = equals; - _this.value_ = enhancer(value, undefined, name_); - - return _this; - } - - var _proto = ObservableValue.prototype; - - _proto.dehanceValue = function dehanceValue(value) { - if (this.dehancer !== undefined) return this.dehancer(value); - return value; - }; - - _proto.set = function set(newValue) { - this.value_; - newValue = this.prepareNewValue_(newValue); - - if (newValue !== globalState.UNCHANGED) { - - this.setNewValue_(newValue); - } - }; - - _proto.prepareNewValue_ = function prepareNewValue_(newValue) { - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this, - type: UPDATE, - newValue: newValue - }); - if (!change) return globalState.UNCHANGED; - newValue = change.newValue; - } // apply modifier - - - newValue = this.enhancer(newValue, this.value_, this.name_); - return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue; - }; - - _proto.setNewValue_ = function setNewValue_(newValue) { - var oldValue = this.value_; - this.value_ = newValue; - this.reportChanged(); - - if (hasListeners(this)) { - notifyListeners(this, { - type: UPDATE, - object: this, - newValue: newValue, - oldValue: oldValue - }); - } - }; - - _proto.get = function get() { - this.reportObserved(); - return this.dehanceValue(this.value_); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - if (fireImmediately) listener({ - observableKind: "value", - debugObjectName: this.name_, - object: this, - type: UPDATE, - newValue: this.value_, - oldValue: undefined - }); - return registerListener(this, listener); - }; - - _proto.raw = function raw() { - // used by MST ot get undehanced value - return this.value_; - }; - - _proto.toJSON = function toJSON() { - return this.get(); - }; - - _proto.toString = function toString() { - return this.name_ + "[" + this.value_ + "]"; - }; - - _proto.valueOf = function valueOf() { - return toPrimitive(this.get()); - }; - - _proto[_Symbol$toPrimitive] = function () { - return this.valueOf(); - }; - - return ObservableValue; - }(Atom); - var isObservableValue = /*#__PURE__*/createInstanceofPredicate("ObservableValue", ObservableValue); - - var _Symbol$toPrimitive$1; - /** - * A node in the state dependency root that observes other nodes, and can be observed itself. - * - * ComputedValue will remember the result of the computation for the duration of the batch, or - * while being observed. - * - * During this time it will recompute only when one of its direct dependencies changed, - * but only when it is being accessed with `ComputedValue.get()`. - * - * Implementation description: - * 1. First time it's being accessed it will compute and remember result - * give back remembered result until 2. happens - * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3. - * 3. When it's being accessed, recompute if any shallow dependency changed. - * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step. - * go to step 2. either way - * - * If at any point it's outside batch and it isn't observed: reset everything and go to 1. - */ - - _Symbol$toPrimitive$1 = Symbol.toPrimitive; - var ComputedValue = /*#__PURE__*/function () { - // nodes we are looking at. Our value depends on these nodes - // during tracking it's an array with new observed observers - // to check for cycles - // N.B: unminified as it is used by MST - - /** - * Create a new computed value based on a function expression. - * - * The `name` property is for debug purposes only. - * - * The `equals` property specifies the comparer function to use to determine if a newly produced - * value differs from the previous value. Two comparers are provided in the library; `defaultComparer` - * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure. - * Structural comparison can be convenient if you always produce a new aggregated object and - * don't want to notify observers if it is structurally the same. - * This is useful for working with vectors, mouse coordinates etc. - */ - function ComputedValue(options) { - this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; - this.observing_ = []; - this.newObserving_ = null; - this.isBeingObserved_ = false; - this.isPendingUnobservation_ = false; - this.observers_ = new Set(); - this.diffValue_ = 0; - this.runId_ = 0; - this.lastAccessedBy_ = 0; - this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - this.unboundDepsCount_ = 0; - this.value_ = new CaughtException(null); - this.name_ = void 0; - this.triggeredBy_ = void 0; - this.isComputing_ = false; - this.isRunningSetter_ = false; - this.derivation = void 0; - this.setter_ = void 0; - this.isTracing_ = TraceMode.NONE; - this.scope_ = void 0; - this.equals_ = void 0; - this.requiresReaction_ = void 0; - this.keepAlive_ = void 0; - this.onBOL = void 0; - this.onBUOL = void 0; - if (!options.get) die(31); - this.derivation = options.get; - this.name_ = options.name || ("ComputedValue"); - - if (options.set) { - this.setter_ = createAction("ComputedValue-setter", options.set); - } - - this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer["default"]); - this.scope_ = options.context; - this.requiresReaction_ = !!options.requiresReaction; - this.keepAlive_ = !!options.keepAlive; - } - - var _proto = ComputedValue.prototype; - - _proto.onBecomeStale_ = function onBecomeStale_() { - propagateMaybeChanged(this); - }; - - _proto.onBO = function onBO() { - if (this.onBOL) { - this.onBOL.forEach(function (listener) { - return listener(); - }); - } - }; - - _proto.onBUO = function onBUO() { - if (this.onBUOL) { - this.onBUOL.forEach(function (listener) { - return listener(); - }); - } - } - /** - * Returns the current value of this computed value. - * Will evaluate its computation first if needed. - */ - ; - - _proto.get = function get() { - if (this.isComputing_) die(32, this.name_, this.derivation); - - if (globalState.inBatch === 0 && // !globalState.trackingDerivatpion && - this.observers_.size === 0 && !this.keepAlive_) { - if (shouldCompute(this)) { - this.warnAboutUntrackedRead_(); - startBatch(); // See perf test 'computed memoization' - - this.value_ = this.computeValue_(false); - endBatch(); - } - } else { - reportObserved(this); - - if (shouldCompute(this)) { - var prevTrackingContext = globalState.trackingContext; - if (this.keepAlive_ && !prevTrackingContext) globalState.trackingContext = this; - if (this.trackAndCompute()) propagateChangeConfirmed(this); - globalState.trackingContext = prevTrackingContext; - } - } - - var result = this.value_; - if (isCaughtException(result)) throw result.cause; - return result; - }; - - _proto.set = function set(value) { - if (this.setter_) { - if (this.isRunningSetter_) die(33, this.name_); - this.isRunningSetter_ = true; - - try { - this.setter_.call(this.scope_, value); - } finally { - this.isRunningSetter_ = false; - } - } else die(34, this.name_); - }; - - _proto.trackAndCompute = function trackAndCompute() { - // N.B: unminified as it is used by MST - var oldValue = this.value_; - var wasSuspended = - /* see #1208 */ - this.dependenciesState_ === IDerivationState_.NOT_TRACKING_; - var newValue = this.computeValue_(true); - - var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue); - - if (changed) { - this.value_ = newValue; - } - - return changed; - }; - - _proto.computeValue_ = function computeValue_(track) { - this.isComputing_ = true; // don't allow state changes during computation - - var prev = allowStateChangesStart(false); - var res; - - if (track) { - res = trackDerivedFunction(this, this.derivation, this.scope_); - } else { - if (globalState.disableErrorBoundaries === true) { - res = this.derivation.call(this.scope_); - } else { - try { - res = this.derivation.call(this.scope_); - } catch (e) { - res = new CaughtException(e); - } - } - } - - allowStateChangesEnd(prev); - this.isComputing_ = false; - return res; - }; - - _proto.suspend_ = function suspend_() { - if (!this.keepAlive_) { - clearObserving(this); - this.value_ = undefined; // don't hold on to computed value! - } - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - var _this = this; - - var firstTime = true; - var prevValue = undefined; - return autorun(function () { - // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place - var newValue = _this.get(); - - if (!firstTime || fireImmediately) { - var prevU = untrackedStart(); - listener({ - observableKind: "computed", - debugObjectName: _this.name_, - type: UPDATE, - object: _this, - newValue: newValue, - oldValue: prevValue - }); - untrackedEnd(prevU); - } - - firstTime = false; - prevValue = newValue; - }); - }; - - _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() { - return; - }; - - _proto.toString = function toString() { - return this.name_ + "[" + this.derivation.toString() + "]"; - }; - - _proto.valueOf = function valueOf() { - return toPrimitive(this.get()); - }; - - _proto[_Symbol$toPrimitive$1] = function () { - return this.valueOf(); - }; - - return ComputedValue; - }(); - var isComputedValue = /*#__PURE__*/createInstanceofPredicate("ComputedValue", ComputedValue); - - var IDerivationState_; - - (function (IDerivationState_) { - // before being run or (outside batch and not being observed) - // at this point derivation is not holding any data about dependency tree - IDerivationState_[IDerivationState_["NOT_TRACKING_"] = -1] = "NOT_TRACKING_"; // no shallow dependency changed since last computation - // won't recalculate derivation - // this is what makes mobx fast - - IDerivationState_[IDerivationState_["UP_TO_DATE_"] = 0] = "UP_TO_DATE_"; // some deep dependency changed, but don't know if shallow dependency changed - // will require to check first if UP_TO_DATE or POSSIBLY_STALE - // currently only ComputedValue will propagate POSSIBLY_STALE - // - // having this state is second big optimization: - // don't have to recompute on every dependency change, but only when it's needed - - IDerivationState_[IDerivationState_["POSSIBLY_STALE_"] = 1] = "POSSIBLY_STALE_"; // A shallow dependency has changed since last computation and the derivation - // will need to recompute when it's needed next. - - IDerivationState_[IDerivationState_["STALE_"] = 2] = "STALE_"; - })(IDerivationState_ || (IDerivationState_ = {})); - - var TraceMode; - - (function (TraceMode) { - TraceMode[TraceMode["NONE"] = 0] = "NONE"; - TraceMode[TraceMode["LOG"] = 1] = "LOG"; - TraceMode[TraceMode["BREAK"] = 2] = "BREAK"; - })(TraceMode || (TraceMode = {})); - - var CaughtException = function CaughtException(cause) { - this.cause = void 0; - this.cause = cause; // Empty - }; - function isCaughtException(e) { - return e instanceof CaughtException; - } - /** - * Finds out whether any dependency of the derivation has actually changed. - * If dependenciesState is 1 then it will recalculate dependencies, - * if any dependency changed it will propagate it by changing dependenciesState to 2. - * - * By iterating over the dependencies in the same order that they were reported and - * stopping on the first change, all the recalculations are only called for ComputedValues - * that will be tracked by derivation. That is because we assume that if the first x - * dependencies of the derivation doesn't change then the derivation should run the same way - * up until accessing x-th dependency. - */ - - function shouldCompute(derivation) { - switch (derivation.dependenciesState_) { - case IDerivationState_.UP_TO_DATE_: - return false; - - case IDerivationState_.NOT_TRACKING_: - case IDerivationState_.STALE_: - return true; - - case IDerivationState_.POSSIBLY_STALE_: - { - // state propagation can occur outside of action/reactive context #2195 - var prevAllowStateReads = allowStateReadsStart(true); - var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction. - - var obs = derivation.observing_, - l = obs.length; - - for (var i = 0; i < l; i++) { - var obj = obs[i]; - - if (isComputedValue(obj)) { - if (globalState.disableErrorBoundaries) { - obj.get(); - } else { - try { - obj.get(); - } catch (e) { - // we are not interested in the value *or* exception at this moment, but if there is one, notify all - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return true; - } - } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers. - // and `derivation` is an observer of `obj` - // invariantShouldCompute(derivation) - - - if (derivation.dependenciesState_ === IDerivationState_.STALE_) { - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return true; - } - } - } - - changeDependenciesStateTo0(derivation); - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return false; - } - } - } - function checkIfStateModificationsAreAllowed(atom) { - { - return; - } - } - /** - * Executes the provided function `f` and tracks which observables are being accessed. - * The tracking information is stored on the `derivation` object and the derivation is registered - * as observer of any of the accessed observables. - */ - - function trackDerivedFunction(derivation, f, context) { - var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps - // array will be trimmed by bindDependencies - - changeDependenciesStateTo0(derivation); - derivation.newObserving_ = new Array(derivation.observing_.length + 100); - derivation.unboundDepsCount_ = 0; - derivation.runId_ = ++globalState.runId; - var prevTracking = globalState.trackingDerivation; - globalState.trackingDerivation = derivation; - globalState.inBatch++; - var result; - - if (globalState.disableErrorBoundaries === true) { - result = f.call(context); - } else { - try { - result = f.call(context); - } catch (e) { - result = new CaughtException(e); - } - } - - globalState.inBatch--; - globalState.trackingDerivation = prevTracking; - bindDependencies(derivation); - allowStateReadsEnd(prevAllowStateReads); - return result; - } - /** - * diffs newObserving with observing. - * update observing to be newObserving with unique observables - * notify observers that become observed/unobserved - */ - - - function bindDependencies(derivation) { - // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1"); - var prevObserving = derivation.observing_; - var observing = derivation.observing_ = derivation.newObserving_; - var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; // Go through all new observables and check diffValue: (this list can contain duplicates): - // 0: first occurrence, change to 1 and keep it - // 1: extra occurrence, drop it - - var i0 = 0, - l = derivation.unboundDepsCount_; - - for (var i = 0; i < l; i++) { - var dep = observing[i]; - - if (dep.diffValue_ === 0) { - dep.diffValue_ = 1; - if (i0 !== i) observing[i0] = dep; - i0++; - } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined, - // not hitting the condition - - - if (dep.dependenciesState_ > lowestNewObservingDerivationState) { - lowestNewObservingDerivationState = dep.dependenciesState_; - } - } - - observing.length = i0; - derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614) - // Go through all old observables and check diffValue: (it is unique after last bindDependencies) - // 0: it's not in new observables, unobserve it - // 1: it keeps being observed, don't want to notify it. change to 0 - - l = prevObserving.length; - - while (l--) { - var _dep = prevObserving[l]; - - if (_dep.diffValue_ === 0) { - removeObserver(_dep, derivation); - } - - _dep.diffValue_ = 0; - } // Go through all new observables and check diffValue: (now it should be unique) - // 0: it was set to 0 in last loop. don't need to do anything. - // 1: it wasn't observed, let's observe it. set back to 0 - - - while (i0--) { - var _dep2 = observing[i0]; - - if (_dep2.diffValue_ === 1) { - _dep2.diffValue_ = 0; - addObserver(_dep2, derivation); - } - } // Some new observed derivations may become stale during this derivation computation - // so they have had no chance to propagate staleness (#916) - - - if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) { - derivation.dependenciesState_ = lowestNewObservingDerivationState; - derivation.onBecomeStale_(); - } - } - - function clearObserving(derivation) { - // invariant(globalState.inBatch > 0, "INTERNAL ERROR clearObserving should be called only inside batch"); - var obs = derivation.observing_; - derivation.observing_ = []; - var i = obs.length; - - while (i--) { - removeObserver(obs[i], derivation); - } - - derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_; - } - function untracked(action) { - var prev = untrackedStart(); - - try { - return action(); - } finally { - untrackedEnd(prev); - } - } - function untrackedStart() { - var prev = globalState.trackingDerivation; - globalState.trackingDerivation = null; - return prev; - } - function untrackedEnd(prev) { - globalState.trackingDerivation = prev; - } - function allowStateReadsStart(allowStateReads) { - var prev = globalState.allowStateReads; - globalState.allowStateReads = allowStateReads; - return prev; - } - function allowStateReadsEnd(prev) { - globalState.allowStateReads = prev; - } - /** - * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0 - * - */ - - function changeDependenciesStateTo0(derivation) { - if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) return; - derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_; - var obs = derivation.observing_; - var i = obs.length; - - while (i--) { - obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - } - } - var MobXGlobals = function MobXGlobals() { - this.version = 6; - this.UNCHANGED = {}; - this.trackingDerivation = null; - this.trackingContext = null; - this.runId = 0; - this.mobxGuid = 0; - this.inBatch = 0; - this.pendingUnobservations = []; - this.pendingReactions = []; - this.isRunningReactions = false; - this.allowStateChanges = false; - this.allowStateReads = true; - this.enforceActions = true; - this.spyListeners = []; - this.globalReactionErrorHandlers = []; - this.computedRequiresReaction = false; - this.reactionRequiresObservable = false; - this.observableRequiresReaction = false; - this.disableErrorBoundaries = false; - this.suppressReactionErrors = false; - this.useProxies = true; - this.verifyProxies = false; - this.safeDescriptors = true; - }; - var canMergeGlobalState = true; - var globalState = /*#__PURE__*/function () { - var global = /*#__PURE__*/getGlobal(); - if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) canMergeGlobalState = false; - if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) canMergeGlobalState = false; - - if (!canMergeGlobalState) { - setTimeout(function () { - { - die(35); - } - }, 1); - return new MobXGlobals(); - } else if (global.__mobxGlobals) { - global.__mobxInstanceCount += 1; - if (!global.__mobxGlobals.UNCHANGED) global.__mobxGlobals.UNCHANGED = {}; // make merge backward compatible - - return global.__mobxGlobals; - } else { - global.__mobxInstanceCount = 1; - return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals(); - } - }(); - function getGlobalState() { - return globalState; - } - // const list = observable.observers - // const map = observable.observersIndexes - // const l = list.length - // for (let i = 0; i < l; i++) { - // const id = list[i].__mapid - // if (i) { - // invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list") // for performance - // } else { - // invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldn't be held in map.") // for performance - // } - // } - // invariant( - // list.length === 0 || Object.keys(map).length === list.length - 1, - // "INTERNAL ERROR there is no junk in map" - // ) - // } - - function addObserver(observable, node) { - // invariant(node.dependenciesState !== -1, "INTERNAL ERROR, can add only dependenciesState !== -1"); - // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR add already added node"); - // invariantObservers(observable); - observable.observers_.add(node); - if (observable.lowestObserverState_ > node.dependenciesState_) observable.lowestObserverState_ = node.dependenciesState_; // invariantObservers(observable); - // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR didn't add node"); - } - function removeObserver(observable, node) { - // invariant(globalState.inBatch > 0, "INTERNAL ERROR, remove should be called only inside batch"); - // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR remove already removed node"); - // invariantObservers(observable); - observable.observers_["delete"](node); - - if (observable.observers_.size === 0) { - // deleting last observer - queueForUnobservation(observable); - } // invariantObservers(observable); - // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR remove already removed node2"); - - } - function queueForUnobservation(observable) { - if (observable.isPendingUnobservation_ === false) { - // invariant(observable._observers.length === 0, "INTERNAL ERROR, should only queue for unobservation unobserved observables"); - observable.isPendingUnobservation_ = true; - globalState.pendingUnobservations.push(observable); - } - } - /** - * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does. - * During a batch `onBecomeUnobserved` will be called at most once per observable. - * Avoids unnecessary recalculations. - */ - - function startBatch() { - globalState.inBatch++; - } - function endBatch() { - if (--globalState.inBatch === 0) { - runReactions(); // the batch is actually about to finish, all unobserving should happen here. - - var list = globalState.pendingUnobservations; - - for (var i = 0; i < list.length; i++) { - var observable = list[i]; - observable.isPendingUnobservation_ = false; - - if (observable.observers_.size === 0) { - if (observable.isBeingObserved_) { - // if this observable had reactive observers, trigger the hooks - observable.isBeingObserved_ = false; - observable.onBUO(); - } - - if (observable instanceof ComputedValue) { - // computed values are automatically teared down when the last observer leaves - // this process happens recursively, this computed might be the last observabe of another, etc.. - observable.suspend_(); - } - } - } - - globalState.pendingUnobservations = []; - } - } - function reportObserved(observable) { - var derivation = globalState.trackingDerivation; - - if (derivation !== null) { - /** - * Simple optimization, give each derivation run an unique id (runId) - * Check if last time this observable was accessed the same runId is used - * if this is the case, the relation is already known - */ - if (derivation.runId_ !== observable.lastAccessedBy_) { - observable.lastAccessedBy_ = derivation.runId_; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close... - - derivation.newObserving_[derivation.unboundDepsCount_++] = observable; - - if (!observable.isBeingObserved_ && globalState.trackingContext) { - observable.isBeingObserved_ = true; - observable.onBO(); - } - } - - return true; - } else if (observable.observers_.size === 0 && globalState.inBatch > 0) { - queueForUnobservation(observable); - } - - return false; - } // function invariantLOS(observable: IObservable, msg: string) { - // // it's expensive so better not run it in produciton. but temporarily helpful for testing - // const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2) - // if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState` - // throw new Error( - // "lowestObserverState is wrong for " + - // msg + - // " because " + - // min + - // " < " + - // observable.lowestObserverState - // ) - // } - - /** - * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly - * It will propagate changes to observers from previous run - * It's hard or maybe impossible (with reasonable perf) to get it right with current approach - * Hopefully self reruning autoruns aren't a feature people should depend on - * Also most basic use cases should be ok - */ - // Called by Atom when its value changes - - function propagateChanged(observable) { - // invariantLOS(observable, "changed start"); - if (observable.lowestObserverState_ === IDerivationState_.STALE_) return; - observable.lowestObserverState_ = IDerivationState_.STALE_; // Ideally we use for..of here, but the downcompiled version is really slow... - - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { - - d.onBecomeStale_(); - } - - d.dependenciesState_ = IDerivationState_.STALE_; - }); // invariantLOS(observable, "changed end"); - } // Called by ComputedValue when it recalculate and its value changed - - function propagateChangeConfirmed(observable) { - // invariantLOS(observable, "confirmed start"); - if (observable.lowestObserverState_ === IDerivationState_.STALE_) return; - observable.lowestObserverState_ = IDerivationState_.STALE_; - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) { - d.dependenciesState_ = IDerivationState_.STALE_; - } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date. - ) { - observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - } - }); // invariantLOS(observable, "confirmed end"); - } // Used by computed when its dependency changed, but we don't wan't to immediately recompute. - - function propagateMaybeChanged(observable) { - // invariantLOS(observable, "maybe start"); - if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) return; - observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_; - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { - d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_; - d.onBecomeStale_(); - } - }); // invariantLOS(observable, "maybe end"); - } - - var Reaction = /*#__PURE__*/function () { - // nodes we are looking at. Our value depends on these nodes - function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) { - if (name_ === void 0) { - name_ = "Reaction"; - } - - if (requiresObservable_ === void 0) { - requiresObservable_ = false; - } - - this.name_ = void 0; - this.onInvalidate_ = void 0; - this.errorHandler_ = void 0; - this.requiresObservable_ = void 0; - this.observing_ = []; - this.newObserving_ = []; - this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; - this.diffValue_ = 0; - this.runId_ = 0; - this.unboundDepsCount_ = 0; - this.isDisposed_ = false; - this.isScheduled_ = false; - this.isTrackPending_ = false; - this.isRunning_ = false; - this.isTracing_ = TraceMode.NONE; - this.name_ = name_; - this.onInvalidate_ = onInvalidate_; - this.errorHandler_ = errorHandler_; - this.requiresObservable_ = requiresObservable_; - } - - var _proto = Reaction.prototype; - - _proto.onBecomeStale_ = function onBecomeStale_() { - this.schedule_(); - }; - - _proto.schedule_ = function schedule_() { - if (!this.isScheduled_) { - this.isScheduled_ = true; - globalState.pendingReactions.push(this); - runReactions(); - } - }; - - _proto.isScheduled = function isScheduled() { - return this.isScheduled_; - } - /** - * internal, use schedule() if you intend to kick off a reaction - */ - ; - - _proto.runReaction_ = function runReaction_() { - if (!this.isDisposed_) { - startBatch(); - this.isScheduled_ = false; - var prev = globalState.trackingContext; - globalState.trackingContext = this; - - if (shouldCompute(this)) { - this.isTrackPending_ = true; - - try { - this.onInvalidate_(); - - if ("production" !== "production" && this.isTrackPending_ && isSpyEnabled()) ; - } catch (e) { - this.reportExceptionInDerivation_(e); - } - } - - globalState.trackingContext = prev; - endBatch(); - } - }; - - _proto.track = function track(fn) { - if (this.isDisposed_) { - return; // console.warn("Reaction already disposed") // Note: Not a warning / error in mobx 4 either - } - - startBatch(); - - this.isRunning_ = true; - var prevReaction = globalState.trackingContext; // reactions could create reactions... - - globalState.trackingContext = this; - var result = trackDerivedFunction(this, fn, undefined); - globalState.trackingContext = prevReaction; - this.isRunning_ = false; - this.isTrackPending_ = false; - - if (this.isDisposed_) { - // disposed during last run. Clean up everything that was bound after the dispose call. - clearObserving(this); - } - - if (isCaughtException(result)) this.reportExceptionInDerivation_(result.cause); - - endBatch(); - }; - - _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) { - var _this = this; - - if (this.errorHandler_) { - this.errorHandler_(error, this); - return; - } - - if (globalState.disableErrorBoundaries) throw error; - var message = "[mobx] uncaught error in '" + this + "'"; - - if (!globalState.suppressReactionErrors) { - console.error(message, error); - /** If debugging brought you here, please, read the above message :-). Tnx! */ - } // prettier-ignore - - globalState.globalReactionErrorHandlers.forEach(function (f) { - return f(error, _this); - }); - }; - - _proto.dispose = function dispose() { - if (!this.isDisposed_) { - this.isDisposed_ = true; - - if (!this.isRunning_) { - // if disposed while running, clean up later. Maybe not optimal, but rare case - startBatch(); - clearObserving(this); - endBatch(); - } - } - }; - - _proto.getDisposer_ = function getDisposer_() { - var r = this.dispose.bind(this); - r[$mobx] = this; - return r; - }; - - _proto.toString = function toString() { - return "Reaction[" + this.name_ + "]"; - }; - - _proto.trace = function trace$1(enterBreakPoint) { - if (enterBreakPoint === void 0) { - enterBreakPoint = false; - } - - trace(this, enterBreakPoint); - }; - - return Reaction; - }(); - /** - * Magic number alert! - * Defines within how many times a reaction is allowed to re-trigger itself - * until it is assumed that this is gonna be a never ending loop... - */ - - var MAX_REACTION_ITERATIONS = 100; - - var reactionScheduler = function reactionScheduler(f) { - return f(); - }; - - function runReactions() { - // Trampolining, if runReactions are already running, new reactions will be picked up - if (globalState.inBatch > 0 || globalState.isRunningReactions) return; - reactionScheduler(runReactionsHelper); - } - - function runReactionsHelper() { - globalState.isRunningReactions = true; - var allReactions = globalState.pendingReactions; - var iterations = 0; // While running reactions, new reactions might be triggered. - // Hence we work with two variables and check whether - // we converge to no remaining reactions after a while. - - while (allReactions.length > 0) { - if (++iterations === MAX_REACTION_ITERATIONS) { - console.error("[mobx] cycle in reaction: " + allReactions[0]); - allReactions.splice(0); // clear reactions - } - - var remainingReactions = allReactions.splice(0); - - for (var i = 0, l = remainingReactions.length; i < l; i++) { - remainingReactions[i].runReaction_(); - } - } - - globalState.isRunningReactions = false; - } - - var isReaction = /*#__PURE__*/createInstanceofPredicate("Reaction", Reaction); - - function isSpyEnabled() { - return "production" !== "production" ; - } - function spyReport(event) { - return; // dead code elimination can do the rest - } - function spyReportStart(event) { - return; - } - function spyReportEnd(change) { - return; - } - function spy(listener) { - { - console.warn("[mobx.spy] Is a no-op in production builds"); - return function () {}; - } - } - - var ACTION = "action"; - var ACTION_BOUND = "action.bound"; - var AUTOACTION = "autoAction"; - var AUTOACTION_BOUND = "autoAction.bound"; - var DEFAULT_ACTION_NAME = ""; - var actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION); - var actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, { - bound: true - }); - var autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, { - autoAction: true - }); - var autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, { - autoAction: true, - bound: true - }); - - function createActionFactory(autoAction) { - var res = function action(arg1, arg2) { - // action(fn() {}) - if (isFunction$2(arg1)) return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction); // action("name", fn() {}) - - if (isFunction$2(arg2)) return createAction(arg1, arg2, autoAction); // @action - - if (isStringish(arg2)) { - return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation); - } // action("name") & @action("name") - - - if (isStringish(arg1)) { - return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, { - name: arg1, - autoAction: autoAction - })); - } - }; - - return res; - } - - var action = /*#__PURE__*/createActionFactory(false); - Object.assign(action, actionAnnotation); - var autoAction = /*#__PURE__*/createActionFactory(true); - Object.assign(autoAction, autoActionAnnotation); - action.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation); - autoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation); - function runInAction(fn) { - return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined); - } - function isAction(thing) { - return isFunction$2(thing) && thing.isMobxAction === true; - } - - /** - * Creates a named reactive view and keeps it alive, so that the view is always - * updated if one of the dependencies changes, even when the view is not further used by something else. - * @param view The reactive view - * @returns disposer function, which can be used to stop the view from being updated in the future. - */ - - function autorun(view, opts) { - var _opts$name, _opts; - - if (opts === void 0) { - opts = EMPTY_OBJECT$1; - } - - var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : "Autorun"; - var runSync = !opts.scheduler && !opts.delay; - var reaction; - - if (runSync) { - // normal autorun - reaction = new Reaction(name, function () { - this.track(reactionRunner); - }, opts.onError, opts.requiresObservable); - } else { - var scheduler = createSchedulerFromOptions(opts); // debounced autorun - - var isScheduled = false; - reaction = new Reaction(name, function () { - if (!isScheduled) { - isScheduled = true; - scheduler(function () { - isScheduled = false; - if (!reaction.isDisposed_) reaction.track(reactionRunner); - }); - } - }, opts.onError, opts.requiresObservable); - } - - function reactionRunner() { - view(reaction); - } - - reaction.schedule_(); - return reaction.getDisposer_(); - } - - var run = function run(f) { - return f(); - }; - - function createSchedulerFromOptions(opts) { - return opts.scheduler ? opts.scheduler : opts.delay ? function (f) { - return setTimeout(f, opts.delay); - } : run; - } - - function reaction(expression, effect, opts) { - var _opts$name2; - - if (opts === void 0) { - opts = EMPTY_OBJECT$1; - } - - var name = (_opts$name2 = opts.name) != null ? _opts$name2 : "Reaction"; - var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect); - var runSync = !opts.scheduler && !opts.delay; - var scheduler = createSchedulerFromOptions(opts); - var firstTime = true; - var isScheduled = false; - var value; - var oldValue = undefined; // only an issue with fireImmediately - - var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer["default"]; - var r = new Reaction(name, function () { - if (firstTime || runSync) { - reactionRunner(); - } else if (!isScheduled) { - isScheduled = true; - scheduler(reactionRunner); - } - }, opts.onError, opts.requiresObservable); - - function reactionRunner() { - isScheduled = false; - if (r.isDisposed_) return; - var changed = false; - r.track(function () { - var nextValue = allowStateChanges(false, function () { - return expression(r); - }); - changed = firstTime || !equals(value, nextValue); - oldValue = value; - value = nextValue; - }); - if (firstTime && opts.fireImmediately) effectAction(value, oldValue, r);else if (!firstTime && changed) effectAction(value, oldValue, r); - firstTime = false; - } - - r.schedule_(); - return r.getDisposer_(); - } - - function wrapErrorHandler(errorHandler, baseFn) { - return function () { - try { - return baseFn.apply(this, arguments); - } catch (e) { - errorHandler.call(this, e); - } - }; - } - - var ON_BECOME_OBSERVED = "onBO"; - var ON_BECOME_UNOBSERVED = "onBUO"; - function onBecomeObserved(thing, arg2, arg3) { - return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3); - } - function onBecomeUnobserved(thing, arg2, arg3) { - return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3); - } - - function interceptHook(hook, thing, arg2, arg3) { - var atom = typeof arg3 === "function" ? getAtom(thing, arg2) : getAtom(thing); - var cb = isFunction$2(arg3) ? arg3 : arg2; - var listenersKey = hook + "L"; - - if (atom[listenersKey]) { - atom[listenersKey].add(cb); - } else { - atom[listenersKey] = new Set([cb]); - } - - return function () { - var hookListeners = atom[listenersKey]; - - if (hookListeners) { - hookListeners["delete"](cb); - - if (hookListeners.size === 0) { - delete atom[listenersKey]; - } - } - }; - } - - function extendObservable(target, properties, annotations, options) { - - - var descriptors = getOwnPropertyDescriptors(properties); - var adm = asObservableObject(target, options)[$mobx]; - startBatch(); - - try { - ownKeys(descriptors).forEach(function (key) { - adm.extend_(key, descriptors[key], // must pass "undefined" for { key: undefined } - !annotations ? true : key in annotations ? annotations[key] : true); - }); - } finally { - endBatch(); - } - - return target; - } - - var generatorId = 0; - function FlowCancellationError() { - this.message = "FLOW_CANCELLED"; - } - FlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype); - var flowAnnotation = /*#__PURE__*/createFlowAnnotation("flow"); - var flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation("flow.bound", { - bound: true - }); - var flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) { - // @flow - if (isStringish(arg2)) { - return storeAnnotation(arg1, arg2, flowAnnotation); - } // flow(fn) - var generator = arg1; - var name = generator.name || ""; // Implementation based on https://github.com/tj/co/blob/master/index.js - - var res = function res() { - var ctx = this; - var args = arguments; - var runId = ++generatorId; - var gen = action(name + " - runid: " + runId + " - init", generator).apply(ctx, args); - var rejector; - var pendingPromise = undefined; - var promise = new Promise(function (resolve, reject) { - var stepId = 0; - rejector = reject; - - function onFulfilled(res) { - pendingPromise = undefined; - var ret; - - try { - ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.next).call(gen, res); - } catch (e) { - return reject(e); - } - - next(ret); - } - - function onRejected(err) { - pendingPromise = undefined; - var ret; - - try { - ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen["throw"]).call(gen, err); - } catch (e) { - return reject(e); - } - - next(ret); - } - - function next(ret) { - if (isFunction$2(ret == null ? void 0 : ret.then)) { - // an async iterator - ret.then(next, reject); - return; - } - - if (ret.done) return resolve(ret.value); - pendingPromise = Promise.resolve(ret.value); - return pendingPromise.then(onFulfilled, onRejected); - } - - onFulfilled(undefined); // kick off the process - }); - promise.cancel = action(name + " - runid: " + runId + " - cancel", function () { - try { - if (pendingPromise) cancelPromise(pendingPromise); // Finally block can return (or yield) stuff.. - - var _res = gen["return"](undefined); // eat anything that promise would do, it's cancelled! - - - var yieldedPromise = Promise.resolve(_res.value); - yieldedPromise.then(noop$1, noop$1); - cancelPromise(yieldedPromise); // maybe it can be cancelled :) - // reject our original promise - - rejector(new FlowCancellationError()); - } catch (e) { - rejector(e); // there could be a throwing finally block - } - }); - return promise; - }; - - res.isMobXFlow = true; - return res; - }, flowAnnotation); - flow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation); - - function cancelPromise(promise) { - if (isFunction$2(promise.cancel)) promise.cancel(); - } - function isFlow(fn) { - return (fn == null ? void 0 : fn.isMobXFlow) === true; - } - - function interceptReads(thing, propOrHandler, handler) { - var target; - - if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) { - target = getAdministration(thing); - } else if (isObservableObject(thing)) { - target = getAdministration(thing, propOrHandler); - } else ; - target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler; - return function () { - target.dehancer = undefined; - }; - } - - function intercept(thing, propOrHandler, handler) { - if (isFunction$2(handler)) return interceptProperty(thing, propOrHandler, handler);else return interceptInterceptable(thing, propOrHandler); - } - - function interceptInterceptable(thing, handler) { - return getAdministration(thing).intercept_(handler); - } - - function interceptProperty(thing, property, handler) { - return getAdministration(thing, property).intercept_(handler); - } - - function _isObservable(value, property) { - if (!value) return false; - - if (property !== undefined) { - - if (isObservableObject(value)) { - return value[$mobx].values_.has(property); - } - - return false; - } // For first check, see #701 - - - return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value); - } - - function isObservable(value) { - return _isObservable(value); - } - - function keys(obj) { - if (isObservableObject(obj)) { - return obj[$mobx].keys_(); - } - - if (isObservableMap(obj) || isObservableSet(obj)) { - return Array.from(obj.keys()); - } - - if (isObservableArray(obj)) { - return obj.map(function (_, index) { - return index; - }); - } - - die(5); - } - function values(obj) { - if (isObservableObject(obj)) { - return keys(obj).map(function (key) { - return obj[key]; - }); - } - - if (isObservableMap(obj)) { - return keys(obj).map(function (key) { - return obj.get(key); - }); - } - - if (isObservableSet(obj)) { - return Array.from(obj.values()); - } - - if (isObservableArray(obj)) { - return obj.slice(); - } - - die(6); - } - function entries(obj) { - if (isObservableObject(obj)) { - return keys(obj).map(function (key) { - return [key, obj[key]]; - }); - } - - if (isObservableMap(obj)) { - return keys(obj).map(function (key) { - return [key, obj.get(key)]; - }); - } - - if (isObservableSet(obj)) { - return Array.from(obj.entries()); - } - - if (isObservableArray(obj)) { - return obj.map(function (key, index) { - return [index, key]; - }); - } - - die(7); - } - function set(obj, key, value) { - if (arguments.length === 2 && !isObservableSet(obj)) { - startBatch(); - var _values = key; - - try { - for (var _key in _values) { - set(obj, _key, _values[_key]); - } - } finally { - endBatch(); - } - - return; - } - - if (isObservableObject(obj)) { - obj[$mobx].set_(key, value); - } else if (isObservableMap(obj)) { - obj.set(key, value); - } else if (isObservableSet(obj)) { - obj.add(key); - } else if (isObservableArray(obj)) { - if (typeof key !== "number") key = parseInt(key, 10); - if (key < 0) die("Invalid index: '" + key + "'"); - startBatch(); - if (key >= obj.length) obj.length = key + 1; - obj[key] = value; - endBatch(); - } else die(8); - } - function apiDefineProperty(obj, key, descriptor) { - if (isObservableObject(obj)) { - return obj[$mobx].defineProperty_(key, descriptor); - } - - die(39); - } - - function observe(thing, propOrCb, cbOrFire, fireImmediately) { - if (isFunction$2(cbOrFire)) return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);else return observeObservable(thing, propOrCb, cbOrFire); - } - - function observeObservable(thing, listener, fireImmediately) { - return getAdministration(thing).observe_(listener, fireImmediately); - } - - function observeObservableProperty(thing, property, listener, fireImmediately) { - return getAdministration(thing, property).observe_(listener, fireImmediately); - } - - function trace() { - die("trace() is not available in production builds"); - var enterBreakPoint = false; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - if (typeof args[args.length - 1] === "boolean") enterBreakPoint = args.pop(); - var derivation = getAtomFromArgs(args); - - if (!derivation) { - return die("'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly"); - } - - if (derivation.isTracing_ === TraceMode.NONE) { - console.log("[mobx.trace] '" + derivation.name_ + "' tracing enabled"); - } - - derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG; - } - - function getAtomFromArgs(args) { - switch (args.length) { - case 0: - return globalState.trackingDerivation; - - case 1: - return getAtom(args[0]); - - case 2: - return getAtom(args[0], args[1]); - } - } - - /** - * During a transaction no views are updated until the end of the transaction. - * The transaction will be run synchronously nonetheless. - * - * @param action a function that updates some reactive state - * @returns any value that was returned by the 'action' parameter. - */ - - function transaction(action, thisArg) { - if (thisArg === void 0) { - thisArg = undefined; - } - - startBatch(); - - try { - return action.apply(thisArg); - } finally { - endBatch(); - } - } - - function getAdm(target) { - return target[$mobx]; - } // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects, - // and skip either the internal values map, or the base object with its property descriptors! - - - var objectProxyTraps = { - has: function has(target, name) { - return getAdm(target).has_(name); - }, - get: function get(target, name) { - return getAdm(target).get_(name); - }, - set: function set(target, name, value) { - var _getAdm$set_; - - if (!isStringish(name)) return false; - - - return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true; - }, - deleteProperty: function deleteProperty(target, name) { - var _getAdm$delete_; - - if (!isStringish(name)) return false; // null (intercepted) -> true (success) - - return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true; - }, - defineProperty: function defineProperty(target, name, descriptor) { - var _getAdm$definePropert; - - - return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true; - }, - ownKeys: function ownKeys(target) { - return getAdm(target).ownKeys_(); - }, - preventExtensions: function preventExtensions(target) { - die(13); - } - }; - function asDynamicObservableObject(target, options) { - var _target$$mobx, _target$$mobx$proxy_; - - assertProxies(); - target = asObservableObject(target, options); - return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps); - } - - function hasInterceptors(interceptable) { - return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0; - } - function registerInterceptor(interceptable, handler) { - var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []); - interceptors.push(handler); - return once(function () { - var idx = interceptors.indexOf(handler); - if (idx !== -1) interceptors.splice(idx, 1); - }); - } - function interceptChange(interceptable, change) { - var prevU = untrackedStart(); - - try { - // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950 - var interceptors = [].concat(interceptable.interceptors_ || []); - - for (var i = 0, l = interceptors.length; i < l; i++) { - change = interceptors[i](change); - if (change && !change.type) die(14); - if (!change) break; - } - - return change; - } finally { - untrackedEnd(prevU); - } - } - - function hasListeners(listenable) { - return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0; - } - function registerListener(listenable, handler) { - var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []); - listeners.push(handler); - return once(function () { - var idx = listeners.indexOf(handler); - if (idx !== -1) listeners.splice(idx, 1); - }); - } - function notifyListeners(listenable, change) { - var prevU = untrackedStart(); - var listeners = listenable.changeListeners_; - if (!listeners) return; - listeners = listeners.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i](change); - } - - untrackedEnd(prevU); - } - - function makeObservable(target, annotations, options) { - var adm = asObservableObject(target, options)[$mobx]; - startBatch(); - - try { - var _annotations; - - // Default to decorators - (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target); // Annotate - - ownKeys(annotations).forEach(function (key) { - return adm.make_(key, annotations[key]); - }); - } finally { - endBatch(); - } - - return target; - } // proto[keysSymbol] = new Set() - - var SPLICE = "splice"; - var UPDATE = "update"; - var MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859 - - var arrayTraps = { - get: function get(target, name) { - var adm = target[$mobx]; - if (name === $mobx) return adm; - if (name === "length") return adm.getArrayLength_(); - - if (typeof name === "string" && !isNaN(name)) { - return adm.get_(parseInt(name)); - } - - if (hasProp(arrayExtensions, name)) { - return arrayExtensions[name]; - } - - return target[name]; - }, - set: function set(target, name, value) { - var adm = target[$mobx]; - - if (name === "length") { - adm.setArrayLength_(value); - } - - if (typeof name === "symbol" || isNaN(name)) { - target[name] = value; - } else { - // numeric string - adm.set_(parseInt(name), value); - } - - return true; - }, - preventExtensions: function preventExtensions() { - die(15); - } - }; - var ObservableArrayAdministration = /*#__PURE__*/function () { - // this is the prop that gets proxied, so can't replace it! - function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) { - if (name === void 0) { - name = "ObservableArray"; - } - - this.owned_ = void 0; - this.legacyMode_ = void 0; - this.atom_ = void 0; - this.values_ = []; - this.interceptors_ = void 0; - this.changeListeners_ = void 0; - this.enhancer_ = void 0; - this.dehancer = void 0; - this.proxy_ = void 0; - this.lastKnownLength_ = 0; - this.owned_ = owned_; - this.legacyMode_ = legacyMode_; - this.atom_ = new Atom(name); - - this.enhancer_ = function (newV, oldV) { - return enhancer(newV, oldV, "ObservableArray[..]"); - }; - } - - var _proto = ObservableArrayAdministration.prototype; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) return this.dehancer(value); - return value; - }; - - _proto.dehanceValues_ = function dehanceValues_(values) { - if (this.dehancer !== undefined && values.length > 0) return values.map(this.dehancer); - return values; - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - if (fireImmediately === void 0) { - fireImmediately = false; - } - - if (fireImmediately) { - listener({ - observableKind: "array", - object: this.proxy_, - debugObjectName: this.atom_.name_, - type: "splice", - index: 0, - added: this.values_.slice(), - addedCount: this.values_.length, - removed: [], - removedCount: 0 - }); - } - - return registerListener(this, listener); - }; - - _proto.getArrayLength_ = function getArrayLength_() { - this.atom_.reportObserved(); - return this.values_.length; - }; - - _proto.setArrayLength_ = function setArrayLength_(newLength) { - if (typeof newLength !== "number" || newLength < 0) die("Out of range: " + newLength); - var currentLength = this.values_.length; - if (newLength === currentLength) return;else if (newLength > currentLength) { - var newItems = new Array(newLength - currentLength); - - for (var i = 0; i < newLength - currentLength; i++) { - newItems[i] = undefined; - } // No Array.fill everywhere... - - - this.spliceWithArray_(currentLength, 0, newItems); - } else this.spliceWithArray_(newLength, currentLength - newLength); - }; - - _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) { - if (oldLength !== this.lastKnownLength_) die(16); - this.lastKnownLength_ += delta; - if (this.legacyMode_ && delta > 0) reserveArrayBuffer(oldLength + delta + 1); - }; - - _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) { - var _this = this; - - checkIfStateModificationsAreAllowed(this.atom_); - var length = this.values_.length; - if (index === undefined) index = 0;else if (index > length) index = length;else if (index < 0) index = Math.max(0, length + index); - if (arguments.length === 1) deleteCount = length - index;else if (deleteCount === undefined || deleteCount === null) deleteCount = 0;else deleteCount = Math.max(0, Math.min(deleteCount, length - index)); - if (newItems === undefined) newItems = EMPTY_ARRAY$1; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_, - type: SPLICE, - index: index, - removedCount: deleteCount, - added: newItems - }); - if (!change) return EMPTY_ARRAY$1; - deleteCount = change.removedCount; - newItems = change.added; - } - - newItems = newItems.length === 0 ? newItems : newItems.map(function (v) { - return _this.enhancer_(v, undefined); - }); - - if (this.legacyMode_ || "production" !== "production") { - var lengthDelta = newItems.length - deleteCount; - this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified - } - - var res = this.spliceItemsIntoValues_(index, deleteCount, newItems); - if (deleteCount !== 0 || newItems.length !== 0) this.notifyArraySplice_(index, newItems, res); - return this.dehanceValues_(res); - }; - - _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) { - if (newItems.length < MAX_SPLICE_SIZE) { - var _this$values_; - - return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems)); - } else { - var res = this.values_.slice(index, index + deleteCount); - var oldItems = this.values_.slice(index + deleteCount); - this.values_.length = index + newItems.length - deleteCount; - - for (var i = 0; i < newItems.length; i++) { - this.values_[index + i] = newItems[i]; - } - - for (var _i = 0; _i < oldItems.length; _i++) { - this.values_[index + newItems.length + _i] = oldItems[_i]; - } - - return res; - } - }; - - _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) { - var notifySpy = !this.owned_ && isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "array", - object: this.proxy_, - type: UPDATE, - debugObjectName: this.atom_.name_, - index: index, - newValue: newValue, - oldValue: oldValue - } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't - this.atom_.reportChanged(); - if (notify) notifyListeners(this, change); - }; - - _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) { - var notifySpy = !this.owned_ && isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "array", - object: this.proxy_, - debugObjectName: this.atom_.name_, - type: SPLICE, - index: index, - removed: removed, - added: added, - removedCount: removed.length, - addedCount: added.length - } : null; - this.atom_.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe - - if (notify) notifyListeners(this, change); - }; - - _proto.get_ = function get_(index) { - if (index < this.values_.length) { - this.atom_.reportObserved(); - return this.dehanceValue_(this.values_[index]); - } - - console.warn("[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + this.values_.length + "). Please check length first. Out of bound indices will not be tracked by MobX"); - }; - - _proto.set_ = function set_(index, newValue) { - var values = this.values_; - - if (index < values.length) { - // update at index in range - checkIfStateModificationsAreAllowed(this.atom_); - var oldValue = values[index]; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: UPDATE, - object: this.proxy_, - index: index, - newValue: newValue - }); - if (!change) return; - newValue = change.newValue; - } - - newValue = this.enhancer_(newValue, oldValue); - var changed = newValue !== oldValue; - - if (changed) { - values[index] = newValue; - this.notifyArrayChildUpdate_(index, newValue, oldValue); - } - } else if (index === values.length) { - // add a new item - this.spliceWithArray_(index, 0, [newValue]); - } else { - // out of bounds - die(17, index, values.length); - } - }; - - return ObservableArrayAdministration; - }(); - function createObservableArray(initialValues, enhancer, name, owned) { - if (name === void 0) { - name = "ObservableArray"; - } - - if (owned === void 0) { - owned = false; - } - - assertProxies(); - var adm = new ObservableArrayAdministration(name, enhancer, owned, false); - addHiddenFinalProp$1(adm.values_, $mobx, adm); - var proxy = new Proxy(adm.values_, arrayTraps); - adm.proxy_ = proxy; - - if (initialValues && initialValues.length) { - var prev = allowStateChangesStart(true); - adm.spliceWithArray_(0, 0, initialValues); - allowStateChangesEnd(prev); - } - - return proxy; - } // eslint-disable-next-line - - var arrayExtensions = { - clear: function clear() { - return this.splice(0); - }, - replace: function replace(newItems) { - var adm = this[$mobx]; - return adm.spliceWithArray_(0, adm.values_.length, newItems); - }, - // Used by JSON.stringify - toJSON: function toJSON() { - return this.slice(); - }, - - /* - * functions that do alter the internal structure of the array, (based on lib.es6.d.ts) - * since these functions alter the inner structure of the array, the have side effects. - * Because the have side effects, they should not be used in computed function, - * and for that reason the do not call dependencyState.notifyObserved - */ - splice: function splice(index, deleteCount) { - for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - newItems[_key - 2] = arguments[_key]; - } - - var adm = this[$mobx]; - - switch (arguments.length) { - case 0: - return []; - - case 1: - return adm.spliceWithArray_(index); - - case 2: - return adm.spliceWithArray_(index, deleteCount); - } - - return adm.spliceWithArray_(index, deleteCount, newItems); - }, - spliceWithArray: function spliceWithArray(index, deleteCount, newItems) { - return this[$mobx].spliceWithArray_(index, deleteCount, newItems); - }, - push: function push() { - var adm = this[$mobx]; - - for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - items[_key2] = arguments[_key2]; - } - - adm.spliceWithArray_(adm.values_.length, 0, items); - return adm.values_.length; - }, - pop: function pop() { - return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0]; - }, - shift: function shift() { - return this.splice(0, 1)[0]; - }, - unshift: function unshift() { - var adm = this[$mobx]; - - for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - items[_key3] = arguments[_key3]; - } - - adm.spliceWithArray_(0, 0, items); - return adm.values_.length; - }, - reverse: function reverse() { - // reverse by default mutates in place before returning the result - // which makes it both a 'derivation' and a 'mutation'. - if (globalState.trackingDerivation) { - die(37, "reverse"); - } - - this.replace(this.slice().reverse()); - return this; - }, - sort: function sort() { - // sort by default mutates in place before returning the result - // which goes against all good practices. Let's not change the array in place! - if (globalState.trackingDerivation) { - die(37, "sort"); - } - - var copy = this.slice(); - copy.sort.apply(copy, arguments); - this.replace(copy); - return this; - }, - remove: function remove(value) { - var adm = this[$mobx]; - var idx = adm.dehanceValues_(adm.values_).indexOf(value); - - if (idx > -1) { - this.splice(idx, 1); - return true; - } - - return false; - } - }; - /** - * Wrap function from prototype - * Without this, everything works as well, but this works - * faster as everything works on unproxied values - */ - - addArrayExtension("concat", simpleFunc); - addArrayExtension("flat", simpleFunc); - addArrayExtension("includes", simpleFunc); - addArrayExtension("indexOf", simpleFunc); - addArrayExtension("join", simpleFunc); - addArrayExtension("lastIndexOf", simpleFunc); - addArrayExtension("slice", simpleFunc); - addArrayExtension("toString", simpleFunc); - addArrayExtension("toLocaleString", simpleFunc); // map - - addArrayExtension("every", mapLikeFunc); - addArrayExtension("filter", mapLikeFunc); - addArrayExtension("find", mapLikeFunc); - addArrayExtension("findIndex", mapLikeFunc); - addArrayExtension("flatMap", mapLikeFunc); - addArrayExtension("forEach", mapLikeFunc); - addArrayExtension("map", mapLikeFunc); - addArrayExtension("some", mapLikeFunc); // reduce - - addArrayExtension("reduce", reduceLikeFunc); - addArrayExtension("reduceRight", reduceLikeFunc); - - function addArrayExtension(funcName, funcFactory) { - if (typeof Array.prototype[funcName] === "function") { - arrayExtensions[funcName] = funcFactory(funcName); - } - } // Report and delegate to dehanced array - - - function simpleFunc(funcName) { - return function () { - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); - return dehancedValues[funcName].apply(dehancedValues, arguments); - }; - } // Make sure callbacks recieve correct array arg #2326 - - - function mapLikeFunc(funcName) { - return function (callback, thisArg) { - var _this2 = this; - - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); - return dehancedValues[funcName](function (element, index) { - return callback.call(thisArg, element, index, _this2); - }); - }; - } // Make sure callbacks recieve correct array arg #2326 - - - function reduceLikeFunc(funcName) { - return function () { - var _this3 = this; - - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); // #2432 - reduce behavior depends on arguments.length - - var callback = arguments[0]; - - arguments[0] = function (accumulator, currentValue, index) { - return callback(accumulator, currentValue, index, _this3); - }; - - return dehancedValues[funcName].apply(dehancedValues, arguments); - }; - } - - var isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration); - function isObservableArray(thing) { - return isObject$2(thing) && isObservableArrayAdministration(thing[$mobx]); - } - - var _Symbol$iterator, _Symbol$toStringTag; - var ObservableMapMarker = {}; - var ADD = "add"; - var DELETE = "delete"; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54 - // But: https://github.com/mobxjs/mobx/issues/1556 - - _Symbol$iterator = Symbol.iterator; - _Symbol$toStringTag = Symbol.toStringTag; - var ObservableMap = /*#__PURE__*/function () { - // hasMap, not hashMap >-). - function ObservableMap(initialData, enhancer_, name_) { - if (enhancer_ === void 0) { - enhancer_ = deepEnhancer; - } - - if (name_ === void 0) { - name_ = "ObservableMap"; - } - - this.enhancer_ = void 0; - this.name_ = void 0; - this[$mobx] = ObservableMapMarker; - this.data_ = void 0; - this.hasMap_ = void 0; - this.keysAtom_ = void 0; - this.interceptors_ = void 0; - this.changeListeners_ = void 0; - this.dehancer = void 0; - this.enhancer_ = enhancer_; - this.name_ = name_; - - if (!isFunction$2(Map)) { - die(18); - } - - this.keysAtom_ = createAtom("ObservableMap.keys()"); - this.data_ = new Map(); - this.hasMap_ = new Map(); - this.merge(initialData); - } - - var _proto = ObservableMap.prototype; - - _proto.has_ = function has_(key) { - return this.data_.has(key); - }; - - _proto.has = function has(key) { - var _this = this; - - if (!globalState.trackingDerivation) return this.has_(key); - var entry = this.hasMap_.get(key); - - if (!entry) { - var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, "ObservableMap.key?", false); - this.hasMap_.set(key, newEntry); - onBecomeUnobserved(newEntry, function () { - return _this.hasMap_["delete"](key); - }); - } - - return entry.get(); - }; - - _proto.set = function set(key, value) { - var hasKey = this.has_(key); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: hasKey ? UPDATE : ADD, - object: this, - newValue: value, - name: key - }); - if (!change) return this; - value = change.newValue; - } - - if (hasKey) { - this.updateValue_(key, value); - } else { - this.addValue_(key, value); - } - - return this; - }; - - _proto["delete"] = function _delete(key) { - var _this2 = this; - - checkIfStateModificationsAreAllowed(this.keysAtom_); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: DELETE, - object: this, - name: key - }); - if (!change) return false; - } - - if (this.has_(key)) { - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - - var _change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: DELETE, - object: this, - oldValue: this.data_.get(key).value_, - name: key - } : null; - transaction(function () { - _this2.keysAtom_.reportChanged(); - - _this2.updateHasMapEntry_(key, false); - - var observable = _this2.data_.get(key); - - observable.setNewValue_(undefined); - - _this2.data_["delete"](key); - }); - if (notify) notifyListeners(this, _change); - return true; - } - - return false; - }; - - _proto.updateHasMapEntry_ = function updateHasMapEntry_(key, value) { - var entry = this.hasMap_.get(key); - - if (entry) { - entry.setNewValue_(value); - } - }; - - _proto.updateValue_ = function updateValue_(key, newValue) { - var observable = this.data_.get(key); - newValue = observable.prepareNewValue_(newValue); - - if (newValue !== globalState.UNCHANGED) { - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: UPDATE, - object: this, - oldValue: observable.value_, - name: key, - newValue: newValue - } : null; - observable.setNewValue_(newValue); - if (notify) notifyListeners(this, change); - } - }; - - _proto.addValue_ = function addValue_(key, newValue) { - var _this3 = this; - - checkIfStateModificationsAreAllowed(this.keysAtom_); - transaction(function () { - var observable = new ObservableValue(newValue, _this3.enhancer_, "ObservableMap.key", false); - - _this3.data_.set(key, observable); - - newValue = observable.value_; // value might have been changed - - _this3.updateHasMapEntry_(key, true); - - _this3.keysAtom_.reportChanged(); - }); - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: ADD, - object: this, - name: key, - newValue: newValue - } : null; - if (notify) notifyListeners(this, change); - }; - - _proto.get = function get(key) { - if (this.has(key)) return this.dehanceValue_(this.data_.get(key).get()); - return this.dehanceValue_(undefined); - }; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) { - return this.dehancer(value); - } - - return value; - }; - - _proto.keys = function keys() { - this.keysAtom_.reportObserved(); - return this.data_.keys(); - }; - - _proto.values = function values() { - var self = this; - var keys = this.keys(); - return makeIterable({ - next: function next() { - var _keys$next = keys.next(), - done = _keys$next.done, - value = _keys$next.value; - - return { - done: done, - value: done ? undefined : self.get(value) - }; - } - }); - }; - - _proto.entries = function entries() { - var self = this; - var keys = this.keys(); - return makeIterable({ - next: function next() { - var _keys$next2 = keys.next(), - done = _keys$next2.done, - value = _keys$next2.value; - - return { - done: done, - value: done ? undefined : [value, self.get(value)] - }; - } - }); - }; - - _proto[_Symbol$iterator] = function () { - return this.entries(); - }; - - _proto.forEach = function forEach(callback, thisArg) { - for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) { - var _step$value = _step.value, - key = _step$value[0], - value = _step$value[1]; - callback.call(thisArg, value, key, this); - } - } - /** Merge another object into this object, returns this. */ - ; - - _proto.merge = function merge(other) { - var _this4 = this; - - if (isObservableMap(other)) { - other = new Map(other); - } - - transaction(function () { - if (isPlainObject$1(other)) getPlainObjectKeys(other).forEach(function (key) { - return _this4.set(key, other[key]); - });else if (Array.isArray(other)) other.forEach(function (_ref) { - var key = _ref[0], - value = _ref[1]; - return _this4.set(key, value); - });else if (isES6Map(other)) { - if (other.constructor !== Map) die(19, other); - other.forEach(function (value, key) { - return _this4.set(key, value); - }); - } else if (other !== null && other !== undefined) die(20, other); - }); - return this; - }; - - _proto.clear = function clear() { - var _this5 = this; - - transaction(function () { - untracked(function () { - for (var _iterator2 = _createForOfIteratorHelperLoose(_this5.keys()), _step2; !(_step2 = _iterator2()).done;) { - var key = _step2.value; - - _this5["delete"](key); - } - }); - }); - }; - - _proto.replace = function replace(values) { - var _this6 = this; - - // Implementation requirements: - // - respect ordering of replacement map - // - allow interceptors to run and potentially prevent individual operations - // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions) - // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!) - // - note that result map may differ from replacement map due to the interceptors - transaction(function () { - // Convert to map so we can do quick key lookups - var replacementMap = convertToMap(values); - var orderedData = new Map(); // Used for optimization - - var keysReportChangedCalled = false; // Delete keys that don't exist in replacement map - // if the key deletion is prevented by interceptor - // add entry at the beginning of the result map - - for (var _iterator3 = _createForOfIteratorHelperLoose(_this6.data_.keys()), _step3; !(_step3 = _iterator3()).done;) { - var key = _step3.value; - - // Concurrently iterating/deleting keys - // iterator should handle this correctly - if (!replacementMap.has(key)) { - var deleted = _this6["delete"](key); // Was the key removed? - - - if (deleted) { - // _keysAtom.reportChanged() was already called - keysReportChangedCalled = true; - } else { - // Delete prevented by interceptor - var value = _this6.data_.get(key); - - orderedData.set(key, value); - } - } - } // Merge entries - - - for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) { - var _step4$value = _step4.value, - _key = _step4$value[0], - _value = _step4$value[1]; - - // We will want to know whether a new key is added - var keyExisted = _this6.data_.has(_key); // Add or update value - - - _this6.set(_key, _value); // The addition could have been prevent by interceptor - - - if (_this6.data_.has(_key)) { - // The update could have been prevented by interceptor - // and also we want to preserve existing values - // so use value from _data map (instead of replacement map) - var _value2 = _this6.data_.get(_key); - - orderedData.set(_key, _value2); // Was a new key added? - - if (!keyExisted) { - // _keysAtom.reportChanged() was already called - keysReportChangedCalled = true; - } - } - } // Check for possible key order change - - - if (!keysReportChangedCalled) { - if (_this6.data_.size !== orderedData.size) { - // If size differs, keys are definitely modified - _this6.keysAtom_.reportChanged(); - } else { - var iter1 = _this6.data_.keys(); - - var iter2 = orderedData.keys(); - var next1 = iter1.next(); - var next2 = iter2.next(); - - while (!next1.done) { - if (next1.value !== next2.value) { - _this6.keysAtom_.reportChanged(); - - break; - } - - next1 = iter1.next(); - next2 = iter2.next(); - } - } - } // Use correctly ordered map - - - _this6.data_ = orderedData; - }); - return this; - }; - - _proto.toString = function toString() { - return "[object ObservableMap]"; - }; - - _proto.toJSON = function toJSON() { - return Array.from(this); - }; - - /** - * Observes this object. Triggers for the events 'add', 'update' and 'delete'. - * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe - * for callback details - */ - _proto.observe_ = function observe_(listener, fireImmediately) { - return registerListener(this, listener); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _createClass(ObservableMap, [{ - key: "size", - get: function get() { - this.keysAtom_.reportObserved(); - return this.data_.size; - } - }, { - key: _Symbol$toStringTag, - get: function get() { - return "Map"; - } - }]); - - return ObservableMap; - }(); // eslint-disable-next-line - - var isObservableMap = /*#__PURE__*/createInstanceofPredicate("ObservableMap", ObservableMap); - - function convertToMap(dataStructure) { - if (isES6Map(dataStructure) || isObservableMap(dataStructure)) { - return dataStructure; - } else if (Array.isArray(dataStructure)) { - return new Map(dataStructure); - } else if (isPlainObject$1(dataStructure)) { - var map = new Map(); - - for (var key in dataStructure) { - map.set(key, dataStructure[key]); - } - - return map; - } else { - return die(21, dataStructure); - } - } - - var _Symbol$iterator$1, _Symbol$toStringTag$1; - var ObservableSetMarker = {}; - _Symbol$iterator$1 = Symbol.iterator; - _Symbol$toStringTag$1 = Symbol.toStringTag; - var ObservableSet = /*#__PURE__*/function () { - function ObservableSet(initialData, enhancer, name_) { - if (enhancer === void 0) { - enhancer = deepEnhancer; - } - - if (name_ === void 0) { - name_ = "ObservableSet"; - } - - this.name_ = void 0; - this[$mobx] = ObservableSetMarker; - this.data_ = new Set(); - this.atom_ = void 0; - this.changeListeners_ = void 0; - this.interceptors_ = void 0; - this.dehancer = void 0; - this.enhancer_ = void 0; - this.name_ = name_; - - if (!isFunction$2(Set)) { - die(22); - } - - this.atom_ = createAtom(this.name_); - - this.enhancer_ = function (newV, oldV) { - return enhancer(newV, oldV, name_); - }; - - if (initialData) { - this.replace(initialData); - } - } - - var _proto = ObservableSet.prototype; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) { - return this.dehancer(value); - } - - return value; - }; - - _proto.clear = function clear() { - var _this = this; - - transaction(function () { - untracked(function () { - for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) { - var value = _step.value; - - _this["delete"](value); - } - }); - }); - }; - - _proto.forEach = function forEach(callbackFn, thisArg) { - for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) { - var value = _step2.value; - callbackFn.call(thisArg, value, value, this); - } - }; - - _proto.add = function add(value) { - var _this2 = this; - - checkIfStateModificationsAreAllowed(this.atom_); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: ADD, - object: this, - newValue: value - }); - if (!change) return this; // ideally, value = change.value would be done here, so that values can be - // changed by interceptor. Same applies for other Set and Map api's. - } - - if (!this.has(value)) { - transaction(function () { - _this2.data_.add(_this2.enhancer_(value, undefined)); - - _this2.atom_.reportChanged(); - }); - var notifySpy = "production" !== "production" ; - var notify = hasListeners(this); - - var _change = notify || notifySpy ? { - observableKind: "set", - debugObjectName: this.name_, - type: ADD, - object: this, - newValue: value - } : null; - if (notify) notifyListeners(this, _change); - } - - return this; - }; - - _proto["delete"] = function _delete(value) { - var _this3 = this; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: DELETE, - object: this, - oldValue: value - }); - if (!change) return false; - } - - if (this.has(value)) { - var notifySpy = "production" !== "production" ; - var notify = hasListeners(this); - - var _change2 = notify || notifySpy ? { - observableKind: "set", - debugObjectName: this.name_, - type: DELETE, - object: this, - oldValue: value - } : null; - transaction(function () { - _this3.atom_.reportChanged(); - - _this3.data_["delete"](value); - }); - if (notify) notifyListeners(this, _change2); - return true; - } - - return false; - }; - - _proto.has = function has(value) { - this.atom_.reportObserved(); - return this.data_.has(this.dehanceValue_(value)); - }; - - _proto.entries = function entries() { - var nextIndex = 0; - var keys = Array.from(this.keys()); - var values = Array.from(this.values()); - return makeIterable({ - next: function next() { - var index = nextIndex; - nextIndex += 1; - return index < values.length ? { - value: [keys[index], values[index]], - done: false - } : { - done: true - }; - } - }); - }; - - _proto.keys = function keys() { - return this.values(); - }; - - _proto.values = function values() { - this.atom_.reportObserved(); - var self = this; - var nextIndex = 0; - var observableValues = Array.from(this.data_.values()); - return makeIterable({ - next: function next() { - return nextIndex < observableValues.length ? { - value: self.dehanceValue_(observableValues[nextIndex++]), - done: false - } : { - done: true - }; - } - }); - }; - - _proto.replace = function replace(other) { - var _this4 = this; - - if (isObservableSet(other)) { - other = new Set(other); - } - - transaction(function () { - if (Array.isArray(other)) { - _this4.clear(); - - other.forEach(function (value) { - return _this4.add(value); - }); - } else if (isES6Set(other)) { - _this4.clear(); - - other.forEach(function (value) { - return _this4.add(value); - }); - } else if (other !== null && other !== undefined) { - die("Cannot initialize set from " + other); - } - }); - return this; - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - return registerListener(this, listener); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.toJSON = function toJSON() { - return Array.from(this); - }; - - _proto.toString = function toString() { - return "[object ObservableSet]"; - }; - - _proto[_Symbol$iterator$1] = function () { - return this.values(); - }; - - _createClass(ObservableSet, [{ - key: "size", - get: function get() { - this.atom_.reportObserved(); - return this.data_.size; - } - }, { - key: _Symbol$toStringTag$1, - get: function get() { - return "Set"; - } - }]); - - return ObservableSet; - }(); // eslint-disable-next-line - - var isObservableSet = /*#__PURE__*/createInstanceofPredicate("ObservableSet", ObservableSet); - - var descriptorCache = /*#__PURE__*/Object.create(null); - var REMOVE = "remove"; - var ObservableObjectAdministration = /*#__PURE__*/function () { - function ObservableObjectAdministration(target_, values_, name_, // Used anytime annotation is not explicitely provided - defaultAnnotation_) { - if (values_ === void 0) { - values_ = new Map(); - } - - if (defaultAnnotation_ === void 0) { - defaultAnnotation_ = autoAnnotation; - } - - this.target_ = void 0; - this.values_ = void 0; - this.name_ = void 0; - this.defaultAnnotation_ = void 0; - this.keysAtom_ = void 0; - this.changeListeners_ = void 0; - this.interceptors_ = void 0; - this.proxy_ = void 0; - this.isPlainObject_ = void 0; - this.appliedAnnotations_ = void 0; - this.pendingKeys_ = void 0; - this.target_ = target_; - this.values_ = values_; - this.name_ = name_; - this.defaultAnnotation_ = defaultAnnotation_; - this.keysAtom_ = new Atom("ObservableObject.keys"); // Optimization: we use this frequently - - this.isPlainObject_ = isPlainObject$1(this.target_); - } - - var _proto = ObservableObjectAdministration.prototype; - - _proto.getObservablePropValue_ = function getObservablePropValue_(key) { - return this.values_.get(key).get(); - }; - - _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) { - var observable = this.values_.get(key); - - if (observable instanceof ComputedValue) { - observable.set(newValue); - return true; - } // intercept - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: UPDATE, - object: this.proxy_ || this.target_, - name: key, - newValue: newValue - }); - if (!change) return null; - newValue = change.newValue; - } - - newValue = observable.prepareNewValue_(newValue); // notify spy & observers - - if (newValue !== globalState.UNCHANGED) { - var notify = hasListeners(this); - var notifySpy = "production" !== "production" ; - - var _change = notify || notifySpy ? { - type: UPDATE, - observableKind: "object", - debugObjectName: this.name_, - object: this.proxy_ || this.target_, - oldValue: observable.value_, - name: key, - newValue: newValue - } : null; - observable.setNewValue_(newValue); - if (notify) notifyListeners(this, _change); - } - - return true; - }; - - _proto.get_ = function get_(key) { - if (globalState.trackingDerivation && !hasProp(this.target_, key)) { - // Key doesn't exist yet, subscribe for it in case it's added later - this.has_(key); - } - - return this.target_[key]; - } - /** - * @param {PropertyKey} key - * @param {any} value - * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is - * @param {boolean} proxyTrap whether it's called from proxy trap - * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor - */ - ; - - _proto.set_ = function set_(key, value, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - // Don't use .has(key) - we care about own - if (hasProp(this.target_, key)) { - // Existing prop - if (this.values_.has(key)) { - // Observable (can be intercepted) - return this.setObservablePropValue_(key, value); - } else if (proxyTrap) { - // Non-observable - proxy - return Reflect.set(this.target_, key, value); - } else { - // Non-observable - this.target_[key] = value; - return true; - } - } else { - // New prop - return this.extend_(key, { - value: value, - enumerable: true, - writable: true, - configurable: true - }, this.defaultAnnotation_, proxyTrap); - } - } // Trap for "in" - ; - - _proto.has_ = function has_(key) { - if (!globalState.trackingDerivation) { - // Skip key subscription outside derivation - return key in this.target_; - } - - this.pendingKeys_ || (this.pendingKeys_ = new Map()); - var entry = this.pendingKeys_.get(key); - - if (!entry) { - entry = new ObservableValue(key in this.target_, referenceEnhancer, "ObservableObject.key?", false); - this.pendingKeys_.set(key, entry); - } - - return entry.get(); - } - /** - * @param {PropertyKey} key - * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop - */ - ; - - _proto.make_ = function make_(key, annotation) { - if (annotation === true) { - annotation = this.defaultAnnotation_; - } - - if (annotation === false) { - return; - } - - if (!(key in this.target_)) { - var _this$target_$storedA; - - // Throw on missing key, except for decorators: - // Decorator annotations are collected from whole prototype chain. - // When called from super() some props may not exist yet. - // However we don't have to worry about missing prop, - // because the decorator must have been applied to something. - if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) == null ? void 0 : _this$target_$storedA[key]) { - return; // will be annotated by subclass constructor - } else { - die(1, annotation.annotationType_, this.name_ + "." + key.toString()); - } - } - - var source = this.target_; - - while (source && source !== objectPrototype) { - var descriptor = getDescriptor(source, key); - - if (descriptor) { - var outcome = annotation.make_(this, key, descriptor, source); - if (outcome === 0 - /* Cancel */ - ) return; - if (outcome === 1 - /* Break */ - ) break; - } - - source = Object.getPrototypeOf(source); - } - - recordAnnotationApplied(this, annotation, key); - } - /** - * @param {PropertyKey} key - * @param {PropertyDescriptor} descriptor - * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is - * @param {boolean} proxyTrap whether it's called from proxy trap - * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor - */ - ; - - _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - if (annotation === true) { - annotation = this.defaultAnnotation_; - } - - if (annotation === false) { - return this.defineProperty_(key, descriptor, proxyTrap); - } - var outcome = annotation.extend_(this, key, descriptor, proxyTrap); - - if (outcome) { - recordAnnotationApplied(this, annotation, key); - } - - return outcome; - } - /** - * @param {PropertyKey} key - * @param {PropertyDescriptor} descriptor - * @param {boolean} proxyTrap whether it's called from proxy trap - * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor - */ - ; - - _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - try { - startBatch(); // Delete - - var deleteOutcome = this.delete_(key); - - if (!deleteOutcome) { - // Failure or intercepted - return deleteOutcome; - } // ADD interceptor - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || this.target_, - name: key, - type: ADD, - newValue: descriptor.value - }); - if (!change) return null; - var newValue = change.newValue; - - if (descriptor.value !== newValue) { - descriptor = _extends({}, descriptor, { - value: newValue - }); - } - } // Define - - - if (proxyTrap) { - if (!Reflect.defineProperty(this.target_, key, descriptor)) { - return false; - } - } else { - defineProperty$2(this.target_, key, descriptor); - } // Notify - - - this.notifyPropertyAddition_(key, descriptor.value); - } finally { - endBatch(); - } - - return true; - } // If original descriptor becomes relevant, move this to annotation directly - ; - - _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - try { - startBatch(); // Delete - - var deleteOutcome = this.delete_(key); - - if (!deleteOutcome) { - // Failure or intercepted - return deleteOutcome; - } // ADD interceptor - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || this.target_, - name: key, - type: ADD, - newValue: value - }); - if (!change) return null; - value = change.newValue; - } - - var cachedDescriptor = getCachedObservablePropDescriptor(key); - var descriptor = { - configurable: globalState.safeDescriptors ? this.isPlainObject_ : true, - enumerable: true, - get: cachedDescriptor.get, - set: cachedDescriptor.set - }; // Define - - if (proxyTrap) { - if (!Reflect.defineProperty(this.target_, key, descriptor)) { - return false; - } - } else { - defineProperty$2(this.target_, key, descriptor); - } - - var observable = new ObservableValue(value, enhancer, "production" !== "production" ? this.name_ + "." + key.toString() : "ObservableObject.key", false); - this.values_.set(key, observable); // Notify (value possibly changed by ObservableValue) - - this.notifyPropertyAddition_(key, observable.value_); - } finally { - endBatch(); - } - - return true; - } // If original descriptor becomes relevant, move this to annotation directly - ; - - _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - try { - startBatch(); // Delete - - var deleteOutcome = this.delete_(key); - - if (!deleteOutcome) { - // Failure or intercepted - return deleteOutcome; - } // ADD interceptor - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || this.target_, - name: key, - type: ADD, - newValue: undefined - }); - if (!change) return null; - } - - options.name || (options.name = "production" !== "production" ? this.name_ + "." + key.toString() : "ObservableObject.key"); - options.context = this.proxy_ || this.target_; - var cachedDescriptor = getCachedObservablePropDescriptor(key); - var descriptor = { - configurable: globalState.safeDescriptors ? this.isPlainObject_ : true, - enumerable: false, - get: cachedDescriptor.get, - set: cachedDescriptor.set - }; // Define - - if (proxyTrap) { - if (!Reflect.defineProperty(this.target_, key, descriptor)) { - return false; - } - } else { - defineProperty$2(this.target_, key, descriptor); - } - - this.values_.set(key, new ComputedValue(options)); // Notify - - this.notifyPropertyAddition_(key, undefined); - } finally { - endBatch(); - } - - return true; - } - /** - * @param {PropertyKey} key - * @param {PropertyDescriptor} descriptor - * @param {boolean} proxyTrap whether it's called from proxy trap - * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor - */ - ; - - _proto.delete_ = function delete_(key, proxyTrap) { - if (proxyTrap === void 0) { - proxyTrap = false; - } - - // No such prop - if (!hasProp(this.target_, key)) { - return true; - } // Intercept - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || this.target_, - name: key, - type: REMOVE - }); // Cancelled - - if (!change) return null; - } // Delete - - - try { - var _this$pendingKeys_, _this$pendingKeys_$ge; - - startBatch(); - var notify = hasListeners(this); - var notifySpy = "production" !== "production" && isSpyEnabled(); - var observable = this.values_.get(key); // Value needed for spies/listeners - - var value = undefined; // Optimization: don't pull the value unless we will need it - - if (!observable && (notify || notifySpy)) { - var _getDescriptor; - - value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value; - } // delete prop (do first, may fail) - - - if (proxyTrap) { - if (!Reflect.deleteProperty(this.target_, key)) { - return false; - } - } else { - delete this.target_[key]; - } // Allow re-annotating this field - - - if ("production" !== "production") ; // Clear observable - - - if (observable) { - this.values_["delete"](key); // for computed, value is undefined - - if (observable instanceof ObservableValue) { - value = observable.value_; - } // Notify: autorun(() => obj[key]), see #1796 - - - propagateChanged(observable); - } // Notify "keys/entries/values" observers - - - this.keysAtom_.reportChanged(); // Notify "has" observers - // "in" as it may still exist in proto - - (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_); // Notify spies/listeners - - if (notify || notifySpy) { - var _change2 = { - type: REMOVE, - observableKind: "object", - object: this.proxy_ || this.target_, - debugObjectName: this.name_, - oldValue: value, - name: key - }; - if ("production" !== "production" && notifySpy) ; - if (notify) notifyListeners(this, _change2); - if ("production" !== "production" && notifySpy) ; - } - } finally { - endBatch(); - } - - return true; - } - /** - * Observes this object. Triggers for the events 'add', 'update' and 'delete'. - * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe - * for callback details - */ - ; - - _proto.observe_ = function observe_(callback, fireImmediately) { - return registerListener(this, callback); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) { - var _this$pendingKeys_2, _this$pendingKeys_2$g; - - var notify = hasListeners(this); - var notifySpy = "production" !== "production" ; - - if (notify || notifySpy) { - var change = notify || notifySpy ? { - type: ADD, - observableKind: "object", - debugObjectName: this.name_, - object: this.proxy_ || this.target_, - name: key, - newValue: value - } : null; - if (notify) notifyListeners(this, change); - } - - (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true); // Notify "keys/entries/values" observers - - this.keysAtom_.reportChanged(); - }; - - _proto.ownKeys_ = function ownKeys_() { - this.keysAtom_.reportObserved(); - return ownKeys(this.target_); - }; - - _proto.keys_ = function keys_() { - // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change. - // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap. - // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object) - // We choose to over-report in Object.keys(object), because: - // - typically it's used with simple data objects - // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected - this.keysAtom_.reportObserved(); - return Object.keys(this.target_); - }; - - return ObservableObjectAdministration; - }(); - function asObservableObject(target, options) { - var _options$name; - - if (hasProp(target, $mobx)) { - - return target; - } - var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : "ObservableObject"; - var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options)); - addHiddenProp(target, $mobx, adm); - return target; - } - var isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration); - - function getCachedObservablePropDescriptor(key) { - return descriptorCache[key] || (descriptorCache[key] = { - get: function get() { - return this[$mobx].getObservablePropValue_(key); - }, - set: function set(value) { - return this[$mobx].setObservablePropValue_(key, value); - } - }); - } - - function isObservableObject(thing) { - if (isObject$2(thing)) { - return isObservableObjectAdministration(thing[$mobx]); - } - - return false; - } - function recordAnnotationApplied(adm, annotation, key) { - var _adm$target_$storedAn; - - - (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key]; - } - - /** - * This array buffer contains two lists of properties, so that all arrays - * can recycle their property definitions, which significantly improves performance of creating - * properties on the fly. - */ - - var OBSERVABLE_ARRAY_BUFFER_SIZE = 0; // Typescript workaround to make sure ObservableArray extends Array - - var StubArray = function StubArray() {}; - - function inherit(ctor, proto) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(ctor.prototype, proto); - } else if (ctor.prototype.__proto__ !== undefined) { - ctor.prototype.__proto__ = proto; - } else { - ctor.prototype = proto; - } - } - - inherit(StubArray, Array.prototype); // Weex proto freeze protection was here, - // but it is unclear why the hack is need as MobX never changed the prototype - // anyway, so removed it in V6 - - var LegacyObservableArray = /*#__PURE__*/function (_StubArray) { - _inheritsLoose(LegacyObservableArray, _StubArray); - - function LegacyObservableArray(initialValues, enhancer, name, owned) { - var _this; - - if (name === void 0) { - name = "ObservableArray"; - } - - if (owned === void 0) { - owned = false; - } - - _this = _StubArray.call(this) || this; - var adm = new ObservableArrayAdministration(name, enhancer, owned, true); - adm.proxy_ = _assertThisInitialized(_this); - addHiddenFinalProp$1(_assertThisInitialized(_this), $mobx, adm); - - if (initialValues && initialValues.length) { - var prev = allowStateChangesStart(true); // @ts-ignore - - _this.spliceWithArray(0, 0, initialValues); - - allowStateChangesEnd(prev); - } - - return _this; - } - - var _proto = LegacyObservableArray.prototype; - - _proto.concat = function concat() { - this[$mobx].atom_.reportObserved(); - - for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { - arrays[_key] = arguments[_key]; - } - - return Array.prototype.concat.apply(this.slice(), //@ts-ignore - arrays.map(function (a) { - return isObservableArray(a) ? a.slice() : a; - })); - }; - - _proto[Symbol.iterator] = function () { - var self = this; - var nextIndex = 0; - return makeIterable({ - next: function next() { - // @ts-ignore - return nextIndex < self.length ? { - value: self[nextIndex++], - done: false - } : { - done: true, - value: undefined - }; - } - }); - }; - - _createClass(LegacyObservableArray, [{ - key: "length", - get: function get() { - return this[$mobx].getArrayLength_(); - }, - set: function set(newLength) { - this[$mobx].setArrayLength_(newLength); - } - }, { - key: Symbol.toStringTag, - get: function get() { - return "Array"; - } - }]); - - return LegacyObservableArray; - }(StubArray); - - Object.entries(arrayExtensions).forEach(function (_ref) { - var prop = _ref[0], - fn = _ref[1]; - if (prop !== "concat") addHiddenProp(LegacyObservableArray.prototype, prop, fn); - }); - - function createArrayEntryDescriptor(index) { - return { - enumerable: false, - configurable: true, - get: function get() { - return this[$mobx].get_(index); - }, - set: function set(value) { - this[$mobx].set_(index, value); - } - }; - } - - function createArrayBufferItem(index) { - defineProperty$2(LegacyObservableArray.prototype, "" + index, createArrayEntryDescriptor(index)); - } - - function reserveArrayBuffer(max) { - if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) { - for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) { - createArrayBufferItem(index); - } - - OBSERVABLE_ARRAY_BUFFER_SIZE = max; - } - } - reserveArrayBuffer(1000); - function createLegacyArray(initialValues, enhancer, name) { - return new LegacyObservableArray(initialValues, enhancer, name); - } - - function getAtom(thing, property) { - if (typeof thing === "object" && thing !== null) { - if (isObservableArray(thing)) { - if (property !== undefined) die(23); - return thing[$mobx].atom_; - } - - if (isObservableSet(thing)) { - return thing[$mobx]; - } - - if (isObservableMap(thing)) { - if (property === undefined) return thing.keysAtom_; - var observable = thing.data_.get(property) || thing.hasMap_.get(property); - if (!observable) die(25, property, getDebugName(thing)); - return observable; - } - - if (isObservableObject(thing)) { - if (!property) return die(26); - - var _observable = thing[$mobx].values_.get(property); - - if (!_observable) die(27, property, getDebugName(thing)); - return _observable; - } - - if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { - return thing; - } - } else if (isFunction$2(thing)) { - if (isReaction(thing[$mobx])) { - // disposer function - return thing[$mobx]; - } - } - - die(28); - } - function getAdministration(thing, property) { - if (!thing) die(29); - if (property !== undefined) return getAdministration(getAtom(thing, property)); - if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) return thing; - if (isObservableMap(thing) || isObservableSet(thing)) return thing; - if (thing[$mobx]) return thing[$mobx]; - die(24, thing); - } - function getDebugName(thing, property) { - var named; - - if (property !== undefined) { - named = getAtom(thing, property); - } else if (isAction(thing)) { - return thing.name; - } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) { - named = getAdministration(thing); - } else { - // valid for arrays as well - named = getAtom(thing); - } - - return named.name_; - } - - var toString$1 = objectPrototype.toString; - function deepEqual(a, b, depth) { - if (depth === void 0) { - depth = -1; - } - - return eq$1(a, b, depth); - } // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289 - // Internal recursive comparison function for `isEqual`. - - function eq$1(a, b, depth, aStack, bStack) { - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). - if (a === b) return a !== 0 || 1 / a === 1 / b; // `null` or `undefined` only equal to itself (strict comparison). - - if (a == null || b == null) return false; // `NaN`s are equivalent, but non-reflexive. - - if (a !== a) return b !== b; // Exhaust primitive checks - - var type = typeof a; - if (!isFunction$2(type) && type !== "object" && typeof b != "object") return false; // Compare `[[Class]]` names. - - var className = toString$1.call(a); - if (className !== toString$1.call(b)) return false; - - switch (className) { - // Strings, numbers, regular expressions, dates, and booleans are compared by value. - case "[object RegExp]": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') - - case "[object String]": - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - return "" + a === "" + b; - - case "[object Number]": - // `NaN`s are equivalent, but non-reflexive. - // Object(NaN) is equivalent to NaN. - if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. - - return +a === 0 ? 1 / +a === 1 / b : +a === +b; - - case "[object Date]": - case "[object Boolean]": - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - return +a === +b; - - case "[object Symbol]": - return typeof Symbol !== "undefined" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b); - - case "[object Map]": - case "[object Set]": - // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level. - // Hide this extra level by increasing the depth. - if (depth >= 0) { - depth++; - } - - break; - } // Unwrap any wrapped objects. - - - a = unwrap(a); - b = unwrap(b); - var areArrays = className === "[object Array]"; - - if (!areArrays) { - if (typeof a != "object" || typeof b != "object") return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s - // from different frames are. - - var aCtor = a.constructor, - bCtor = b.constructor; - - if (aCtor !== bCtor && !(isFunction$2(aCtor) && aCtor instanceof aCtor && isFunction$2(bCtor) && bCtor instanceof bCtor) && "constructor" in a && "constructor" in b) { - return false; - } - } - - if (depth === 0) { - return false; - } else if (depth < 0) { - depth = -1; - } // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - // Initializing stack of traversed objects. - // It's done here since we only need them for objects and arrays comparison. - - - aStack = aStack || []; - bStack = bStack || []; - var length = aStack.length; - - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (aStack[length] === a) return bStack[length] === b; - } // Add the first object to the stack of traversed objects. - - - aStack.push(a); - bStack.push(b); // Recursively compare objects and arrays. - - if (areArrays) { - // Compare array lengths to determine if a deep comparison is necessary. - length = a.length; - if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. - - while (length--) { - if (!eq$1(a[length], b[length], depth - 1, aStack, bStack)) return false; - } - } else { - // Deep compare objects. - var keys = Object.keys(a); - var key; - length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. - - if (Object.keys(b).length !== length) return false; - - while (length--) { - // Deep compare each member - key = keys[length]; - if (!(hasProp(b, key) && eq$1(a[key], b[key], depth - 1, aStack, bStack))) return false; - } - } // Remove the first object from the stack of traversed objects. - - - aStack.pop(); - bStack.pop(); - return true; - } - - function unwrap(a) { - if (isObservableArray(a)) return a.slice(); - if (isES6Map(a) || isObservableMap(a)) return Array.from(a.entries()); - if (isES6Set(a) || isObservableSet(a)) return Array.from(a.entries()); - return a; - } - - function makeIterable(iterator) { - iterator[Symbol.iterator] = getSelf; - return iterator; - } - - function getSelf() { - return this; - } - - /** - * (c) Michel Weststrate 2015 - 2020 - * MIT Licensed - * - * Welcome to the mobx sources! To get an global overview of how MobX internally works, - * this is a good place to start: - * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74 - * - * Source folders: - * =============== - * - * - api/ Most of the public static methods exposed by the module can be found here. - * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here. - * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`. - * - utils/ Utility stuff. - * - */ - ["Symbol", "Map", "Set", "Symbol"].forEach(function (m) { - var g = getGlobal(); - - if (typeof g[m] === "undefined") { - die("MobX requires global '" + m + "' to be available or polyfilled"); - } - }); - - if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "object") { - // See: https://github.com/andykog/mobx-devtools/ - __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({ - spy: spy, - extras: { - getDebugName: getDebugName - }, - $mobx: $mobx - }); - } - - var livelinessChecking = "warn"; - /** - * Returns the current liveliness checking mode. - * - * @returns `"warn"`, `"error"` or `"ignore"` - */ - function getLivelinessChecking() { - return livelinessChecking; - } - - /** - * @hidden - */ - var Hook; - (function (Hook) { - Hook["afterCreate"] = "afterCreate"; - Hook["afterAttach"] = "afterAttach"; - Hook["afterCreationFinalization"] = "afterCreationFinalization"; - Hook["beforeDetach"] = "beforeDetach"; - Hook["beforeDestroy"] = "beforeDestroy"; - })(Hook || (Hook = {})); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$1 = function(d, b) { - extendStatics$1 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics$1(d, b); - }; - - function __extends$1(d, b) { - extendStatics$1(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - } - - function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - } - - function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - } - - /** - * Returns the _actual_ type of the given tree node. (Or throws) - * - * @param object - * @returns - */ - function getType(object) { - return getStateTreeNode(object).type; - } - /** - * Applies a JSON-patch to the given model instance or bails out if the patch couldn't be applied - * See [patches](https://github.com/mobxjs/mobx-state-tree#patches) for more details. - * - * Can apply a single past, or an array of patches. - * - * @param target - * @param patch - * @returns - */ - function applyPatch(target, patch) { - getStateTreeNode(target).applyPatches(asArray(patch)); - } - /** - * Applies a snapshot to a given model instances. Patch and snapshot listeners will be invoked as usual. - * - * @param target - * @param snapshot - * @returns - */ - function applySnapshot(target, snapshot) { - return getStateTreeNode(target).applySnapshot(snapshot); - } - /** - * Calculates a snapshot from the given model instance. The snapshot will always reflect the latest state but use - * structural sharing where possible. Doesn't require MobX transactions to be completed. - * - * @param target - * @param applyPostProcess If true (the default) then postProcessSnapshot gets applied. - * @returns - */ - function getSnapshot(target, applyPostProcess) { - if (applyPostProcess === void 0) { applyPostProcess = true; } - var node = getStateTreeNode(target); - if (applyPostProcess) - return node.snapshot; - return freeze(node.type.getSnapshot(node, false)); - } - /** - * Given an object in a model tree, returns the root object of that tree. - * - * Please note that in child nodes access to the root is only possible - * once the `afterAttach` hook has fired. - * - * @param target - * @returns - */ - function getRoot(target) { - return getStateTreeNode(target).root.storedValue; - } - /** - * Returns the path of the given object in the model tree - * - * @param target - * @returns - */ - function getPath(target) { - return getStateTreeNode(target).path; - } - /** - * Returns the identifier of the target node. - * This is the *string normalized* identifier, which might not match the type of the identifier attribute - * - * @param target - * @returns - */ - function getIdentifier(target) { - return getStateTreeNode(target).identifier; - } - /** - * Removes a model element from the state tree, and mark it as end-of-life; the element should not be used anymore - */ - function destroy(target) { - var node = getStateTreeNode(target); - if (node.isRoot) - node.die(); - else - node.parent.removeChild(node.subpath); - } - - /** - * @internal - * @hidden - */ - var BaseNode = /** @class */ (function () { - function BaseNode(type, parent, subpath, environment) { - Object.defineProperty(this, "type", { - enumerable: true, - configurable: true, - writable: true, - value: type - }); - Object.defineProperty(this, "environment", { - enumerable: true, - configurable: true, - writable: true, - value: environment - }); - Object.defineProperty(this, "_escapedSubpath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_subpath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_subpathUponDeath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_pathUponDeath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "storedValue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); // usually the same type as the value, but not always (such as with references) - Object.defineProperty(this, "aliveAtom", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_state", { - enumerable: true, - configurable: true, - writable: true, - value: NodeLifeCycle.INITIALIZING - }); - Object.defineProperty(this, "_hookSubscribers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_parent", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "pathAtom", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.environment = environment; - this.baseSetParent(parent, subpath); - } - Object.defineProperty(BaseNode.prototype, "subpath", { - get: function () { - return this._subpath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "subpathUponDeath", { - get: function () { - return this._subpathUponDeath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "pathUponDeath", { - get: function () { - return this._pathUponDeath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "value", { - get: function () { - return this.type.getValue(this); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "state", { - get: function () { - return this._state; - }, - set: function (val) { - var wasAlive = this.isAlive; - this._state = val; - var isAlive = this.isAlive; - if (this.aliveAtom && wasAlive !== isAlive) { - this.aliveAtom.reportChanged(); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "fireInternalHook", { - enumerable: false, - configurable: true, - writable: true, - value: function (name) { - if (this._hookSubscribers) { - this._hookSubscribers.emit(name, this, name); - } - } - }); - Object.defineProperty(BaseNode.prototype, "registerHook", { - enumerable: false, - configurable: true, - writable: true, - value: function (hook, hookHandler) { - if (!this._hookSubscribers) { - this._hookSubscribers = new EventHandlers(); - } - return this._hookSubscribers.register(hook, hookHandler); - } - }); - Object.defineProperty(BaseNode.prototype, "parent", { - get: function () { - return this._parent; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "baseSetParent", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath) { - this._parent = parent; - this._subpath = subpath; - this._escapedSubpath = undefined; // regenerate when needed - if (this.pathAtom) { - this.pathAtom.reportChanged(); - } - } - }); - Object.defineProperty(BaseNode.prototype, "path", { - /* - * Returns (escaped) path representation as string - */ - get: function () { - return this.getEscapedPath(true); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "getEscapedPath", { - enumerable: false, - configurable: true, - writable: true, - value: function (reportObserved) { - if (reportObserved) { - if (!this.pathAtom) { - this.pathAtom = createAtom("path"); - } - this.pathAtom.reportObserved(); - } - if (!this.parent) - return ""; - // regenerate escaped subpath if needed - if (this._escapedSubpath === undefined) { - this._escapedSubpath = !this._subpath ? "" : escapeJsonPath(this._subpath); - } - return this.parent.getEscapedPath(reportObserved) + "/" + this._escapedSubpath; - } - }); - Object.defineProperty(BaseNode.prototype, "isRoot", { - get: function () { - return this.parent === null; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "isAlive", { - get: function () { - return this.state !== NodeLifeCycle.DEAD; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "isDetaching", { - get: function () { - return this.state === NodeLifeCycle.DETACHING; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "observableIsAlive", { - get: function () { - if (!this.aliveAtom) { - this.aliveAtom = createAtom("alive"); - } - this.aliveAtom.reportObserved(); - return this.isAlive; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseNode.prototype, "baseFinalizeCreation", { - enumerable: false, - configurable: true, - writable: true, - value: function (whenFinalized) { - // goal: afterCreate hooks runs depth-first. After attach runs parent first, so on afterAttach the parent has completed already - if (this.state === NodeLifeCycle.CREATED) { - if (this.parent) { - if (this.parent.state !== NodeLifeCycle.FINALIZED) { - // parent not ready yet, postpone - return; - } - this.fireHook(Hook.afterAttach); - } - this.state = NodeLifeCycle.FINALIZED; - if (whenFinalized) { - whenFinalized(); - } - } - } - }); - Object.defineProperty(BaseNode.prototype, "baseFinalizeDeath", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._hookSubscribers) { - this._hookSubscribers.clearAll(); - } - this._subpathUponDeath = this._subpath; - this._pathUponDeath = this.getEscapedPath(false); - this.baseSetParent(null, ""); - this.state = NodeLifeCycle.DEAD; - } - }); - Object.defineProperty(BaseNode.prototype, "baseAboutToDie", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.fireHook(Hook.beforeDestroy); - } - }); - return BaseNode; - }()); - - /** - * @internal - * @hidden - */ - var ScalarNode = /** @class */ (function (_super) { - __extends$1(ScalarNode, _super); - function ScalarNode(simpleType, parent, subpath, environment, initialSnapshot) { - var _this = _super.call(this, simpleType, parent, subpath, environment) || this; - try { - _this.storedValue = simpleType.createNewInstance(initialSnapshot); - } - catch (e) { - // short-cut to die the instance, to avoid the snapshot computed starting to throw... - _this.state = NodeLifeCycle.DEAD; - throw e; - } - _this.state = NodeLifeCycle.CREATED; - // for scalar nodes there's no point in firing this event since it would fire on the constructor, before - // anybody can actually register for/listen to it - // this.fireHook(Hook.AfterCreate) - _this.finalizeCreation(); - return _this; - } - Object.defineProperty(ScalarNode.prototype, "root", { - get: function () { - // future optimization: store root ref in the node and maintain it - if (!this.parent) - throw fail$1("This scalar node is not part of a tree"); - return this.parent.root; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ScalarNode.prototype, "setParent", { - enumerable: false, - configurable: true, - writable: true, - value: function (newParent, subpath) { - var parentChanged = this.parent !== newParent; - var subpathChanged = this.subpath !== subpath; - if (!parentChanged && !subpathChanged) { - return; - } - this.environment = undefined; // use parent's - this.baseSetParent(this.parent, subpath); - } - }); - Object.defineProperty(ScalarNode.prototype, "snapshot", { - get: function () { - return freeze(this.getSnapshot()); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ScalarNode.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.type.getSnapshot(this); - } - }); - Object.defineProperty(ScalarNode.prototype, "toString", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var path = (this.isAlive ? this.path : this.pathUponDeath) || ""; - return this.type.name + "@" + path + (this.isAlive ? "" : " [dead]"); - } - }); - Object.defineProperty(ScalarNode.prototype, "die", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) - return; - this.aboutToDie(); - this.finalizeDeath(); - } - }); - Object.defineProperty(ScalarNode.prototype, "finalizeCreation", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.baseFinalizeCreation(); - } - }); - Object.defineProperty(ScalarNode.prototype, "aboutToDie", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.baseAboutToDie(); - } - }); - Object.defineProperty(ScalarNode.prototype, "finalizeDeath", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.baseFinalizeDeath(); - } - }); - Object.defineProperty(ScalarNode.prototype, "fireHook", { - enumerable: false, - configurable: true, - writable: true, - value: function (name) { - this.fireInternalHook(name); - } - }); - return ScalarNode; - }(BaseNode)); - ScalarNode.prototype.die = action(ScalarNode.prototype.die); - - var nextNodeId = 1; - var snapshotReactionOptions = { - onError: function (e) { - throw e; - } - }; - /** - * @internal - * @hidden - */ - var ObjectNode = /** @class */ (function (_super) { - __extends$1(ObjectNode, _super); - function ObjectNode(complexType, parent, subpath, environment, initialValue) { - var _this = _super.call(this, complexType, parent, subpath, environment) || this; - Object.defineProperty(_this, "nodeId", { - enumerable: true, - configurable: true, - writable: true, - value: ++nextNodeId - }); - Object.defineProperty(_this, "identifierAttribute", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "identifier", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); // Identifier is always normalized to string, even if the identifier property isn't - Object.defineProperty(_this, "unnormalizedIdentifier", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "identifierCache", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "isProtectionEnabled", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(_this, "middlewares", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_applyPatches", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_applySnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_autoUnbox", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); // unboxing is disabled when reading child nodes - Object.defineProperty(_this, "_isRunningAction", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); // only relevant for root - Object.defineProperty(_this, "_hasSnapshotReaction", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(_this, "_observableInstanceState", { - enumerable: true, - configurable: true, - writable: true, - value: 0 /* UNINITIALIZED */ - }); - Object.defineProperty(_this, "_childNodes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_initialSnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_cachedInitialSnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_cachedInitialSnapshotCreated", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(_this, "_snapshotComputed", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_snapshotUponDeath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // #region internal event handling - Object.defineProperty(_this, "_internalEvents", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - _this._snapshotComputed = computed(function () { return freeze(_this.getSnapshot()); }); - _this.unbox = _this.unbox.bind(_this); - _this._initialSnapshot = freeze(initialValue); - _this.identifierAttribute = complexType.identifierAttribute; - if (!parent) { - _this.identifierCache = new IdentifierCache(); - } - _this._childNodes = complexType.initializeChildNodes(_this, _this._initialSnapshot); - // identifier can not be changed during lifecycle of a node - // so we safely can read it from initial snapshot - _this.identifier = null; - _this.unnormalizedIdentifier = null; - if (_this.identifierAttribute && _this._initialSnapshot) { - var id = _this._initialSnapshot[_this.identifierAttribute]; - if (id === undefined) { - // try with the actual node if not (for optional identifiers) - var childNode = _this._childNodes[_this.identifierAttribute]; - if (childNode) { - id = childNode.value; - } - } - if (typeof id !== "string" && typeof id !== "number") { - throw fail$1("Instance identifier '" + _this.identifierAttribute + "' for type '" + _this.type.name + "' must be a string or a number"); - } - // normalize internal identifier to string - _this.identifier = normalizeIdentifier(id); - _this.unnormalizedIdentifier = id; - } - if (!parent) { - _this.identifierCache.addNodeToCache(_this); - } - else { - parent.root.identifierCache.addNodeToCache(_this); - } - return _this; - } - Object.defineProperty(ObjectNode.prototype, "applyPatches", { - enumerable: false, - configurable: true, - writable: true, - value: function (patches) { - this.createObservableInstanceIfNeeded(); - this._applyPatches(patches); - } - }); - Object.defineProperty(ObjectNode.prototype, "applySnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - this.createObservableInstanceIfNeeded(); - this._applySnapshot(snapshot); - } - }); - Object.defineProperty(ObjectNode.prototype, "createObservableInstanceIfNeeded", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._observableInstanceState === 0 /* UNINITIALIZED */) { - this.createObservableInstance(); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "createObservableInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var e_1, _a; - this._observableInstanceState = 1 /* CREATING */; - // make sure the parent chain is created as well - // array with parent chain from parent to child - var parentChain = []; - var parent = this.parent; - // for performance reasons we never go back further than the most direct - // uninitialized parent - // this is done to avoid traversing the whole tree to the root when using - // the same reference again - while (parent && - parent._observableInstanceState === 0 /* UNINITIALIZED */) { - parentChain.unshift(parent); - parent = parent.parent; - } - try { - // initialize the uninitialized parent chain from parent to child - for (var parentChain_1 = __values(parentChain), parentChain_1_1 = parentChain_1.next(); !parentChain_1_1.done; parentChain_1_1 = parentChain_1.next()) { - var p = parentChain_1_1.value; - p.createObservableInstanceIfNeeded(); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (parentChain_1_1 && !parentChain_1_1.done && (_a = parentChain_1.return)) _a.call(parentChain_1); - } - finally { if (e_1) throw e_1.error; } - } - var type = this.type; - try { - this.storedValue = type.createNewInstance(this._childNodes); - this.preboot(); - this._isRunningAction = true; - type.finalizeNewInstance(this, this.storedValue); - } - catch (e) { - // short-cut to die the instance, to avoid the snapshot computed starting to throw... - this.state = NodeLifeCycle.DEAD; - throw e; - } - finally { - this._isRunningAction = false; - } - this._observableInstanceState = 2 /* CREATED */; - this._snapshotComputed.trackAndCompute(); - if (this.isRoot) - this._addSnapshotReaction(); - this._childNodes = EMPTY_OBJECT; - this.state = NodeLifeCycle.CREATED; - this.fireHook(Hook.afterCreate); - this.finalizeCreation(); - } - }); - Object.defineProperty(ObjectNode.prototype, "root", { - get: function () { - var parent = this.parent; - return parent ? parent.root : this; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectNode.prototype, "clearParent", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.parent) - return; - // detach if attached - this.fireHook(Hook.beforeDetach); - var previousState = this.state; - this.state = NodeLifeCycle.DETACHING; - var root = this.root; - var newEnv = root.environment; - var newIdCache = root.identifierCache.splitCache(this); - try { - this.parent.removeChild(this.subpath); - this.baseSetParent(null, ""); - this.environment = newEnv; - this.identifierCache = newIdCache; - } - finally { - this.state = previousState; - } - } - }); - Object.defineProperty(ObjectNode.prototype, "setParent", { - enumerable: false, - configurable: true, - writable: true, - value: function (newParent, subpath) { - var parentChanged = newParent !== this.parent; - var subpathChanged = subpath !== this.subpath; - if (!parentChanged && !subpathChanged) { - return; - } - if (parentChanged) { - // attach to new parent - this.environment = undefined; // will use root's - newParent.root.identifierCache.mergeCache(this); - this.baseSetParent(newParent, subpath); - this.fireHook(Hook.afterAttach); - } - else if (subpathChanged) { - // moving to a new subpath on the same parent - this.baseSetParent(this.parent, subpath); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "fireHook", { - enumerable: false, - configurable: true, - writable: true, - value: function (name) { - var _this = this; - this.fireInternalHook(name); - var fn = this.storedValue && - typeof this.storedValue === "object" && - this.storedValue[name]; - if (typeof fn === "function") { - // we check for it to allow old mobx peer dependencies that don't have the method to work (even when still bugged) - if (runInAction) { - runInAction(function () { - fn.apply(_this.storedValue); - }); - } - else { - fn.apply(this.storedValue); - } - } - } - }); - Object.defineProperty(ObjectNode.prototype, "snapshot", { - // advantage of using computed for a snapshot is that nicely respects transactions etc. - get: function () { - return this._snapshotComputed.get(); - }, - enumerable: false, - configurable: true - }); - // NOTE: we use this method to get snapshot without creating @computed overhead - Object.defineProperty(ObjectNode.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.isAlive) - return this._snapshotUponDeath; - return this._observableInstanceState === 2 /* CREATED */ - ? this._getActualSnapshot() - : this._getCachedInitialSnapshot(); - } - }); - Object.defineProperty(ObjectNode.prototype, "_getActualSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.type.getSnapshot(this); - } - }); - Object.defineProperty(ObjectNode.prototype, "_getCachedInitialSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this._cachedInitialSnapshotCreated) { - var type = this.type; - var childNodes = this._childNodes; - var snapshot = this._initialSnapshot; - this._cachedInitialSnapshot = type.processInitialSnapshot(childNodes, snapshot); - this._cachedInitialSnapshotCreated = true; - } - return this._cachedInitialSnapshot; - } - }); - Object.defineProperty(ObjectNode.prototype, "isRunningAction", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._isRunningAction) - return true; - if (this.isRoot) - return false; - return this.parent.isRunningAction(); - } - }); - Object.defineProperty(ObjectNode.prototype, "assertAlive", { - enumerable: false, - configurable: true, - writable: true, - value: function (context) { - var livelinessChecking = getLivelinessChecking(); - if (!this.isAlive && livelinessChecking !== "ignore") { - var error = this._getAssertAliveError(context); - switch (livelinessChecking) { - case "error": - throw fail$1(error); - case "warn": - warnError(error); - } - } - } - }); - Object.defineProperty(ObjectNode.prototype, "_getAssertAliveError", { - enumerable: false, - configurable: true, - writable: true, - value: function (context) { - var escapedPath = this.getEscapedPath(false) || this.pathUponDeath || ""; - var subpath = (context.subpath && escapeJsonPath(context.subpath)) || ""; - var actionContext = context.actionContext || getCurrentActionContext(); - // try to use a real action context if possible since it includes the action name - if (actionContext && actionContext.type !== "action" && actionContext.parentActionEvent) { - actionContext = actionContext.parentActionEvent; - } - var actionFullPath = ""; - if (actionContext && actionContext.name != null) { - // try to use the context, and if it not available use the node one - var actionPath = (actionContext && actionContext.context && getPath(actionContext.context)) || - escapedPath; - actionFullPath = actionPath + "." + actionContext.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: '" + escapedPath + "', Subpath: '" + subpath + "', Action: '" + actionFullPath + "'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."; - } - }); - Object.defineProperty(ObjectNode.prototype, "getChildNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (subpath) { - this.assertAlive({ - subpath: subpath - }); - this._autoUnbox = false; - try { - return this._observableInstanceState === 2 /* CREATED */ - ? this.type.getChildNode(this, subpath) - : this._childNodes[subpath]; - } - finally { - this._autoUnbox = true; - } - } - }); - Object.defineProperty(ObjectNode.prototype, "getChildren", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.assertAlive(EMPTY_OBJECT); - this._autoUnbox = false; - try { - return this._observableInstanceState === 2 /* CREATED */ - ? this.type.getChildren(this) - : convertChildNodesToArray(this._childNodes); - } - finally { - this._autoUnbox = true; - } - } - }); - Object.defineProperty(ObjectNode.prototype, "getChildType", { - enumerable: false, - configurable: true, - writable: true, - value: function (propertyName) { - return this.type.getChildType(propertyName); - } - }); - Object.defineProperty(ObjectNode.prototype, "isProtected", { - get: function () { - return this.root.isProtectionEnabled; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectNode.prototype, "assertWritable", { - enumerable: false, - configurable: true, - writable: true, - value: function (context) { - this.assertAlive(context); - if (!this.isRunningAction() && this.isProtected) { - throw fail$1("Cannot modify '" + this + "', the object is protected and can only be modified by using an action."); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "removeChild", { - enumerable: false, - configurable: true, - writable: true, - value: function (subpath) { - this.type.removeChild(this, subpath); - } - }); - // bound on the constructor - Object.defineProperty(ObjectNode.prototype, "unbox", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNode) { - if (!childNode) - return childNode; - this.assertAlive({ - subpath: childNode.subpath || childNode.subpathUponDeath - }); - return this._autoUnbox ? childNode.value : childNode; - } - }); - Object.defineProperty(ObjectNode.prototype, "toString", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var path = (this.isAlive ? this.path : this.pathUponDeath) || ""; - var identifier = this.identifier ? "(id: " + this.identifier + ")" : ""; - return this.type.name + "@" + path + identifier + (this.isAlive ? "" : " [dead]"); - } - }); - Object.defineProperty(ObjectNode.prototype, "finalizeCreation", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var _this = this; - this.baseFinalizeCreation(function () { - var e_2, _a; - try { - for (var _b = __values(_this.getChildren()), _c = _b.next(); !_c.done; _c = _b.next()) { - var child = _c.value; - child.finalizeCreation(); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_2) throw e_2.error; } - } - _this.fireInternalHook(Hook.afterCreationFinalization); - }); - } - }); - Object.defineProperty(ObjectNode.prototype, "detach", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.isAlive) - throw fail$1("Error while detaching, node is not alive."); - this.clearParent(); - } - }); - Object.defineProperty(ObjectNode.prototype, "preboot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var self = this; - this._applyPatches = createActionInvoker(this.storedValue, "@APPLY_PATCHES", function (patches) { - patches.forEach(function (patch) { - if (!patch.path) { - self.type.applySnapshot(self, patch.value); - return; - } - var parts = splitJsonPath(patch.path); - var node = resolveNodeByPathParts(self, parts.slice(0, -1)); - node.applyPatchLocally(parts[parts.length - 1], patch); - }); - }); - this._applySnapshot = createActionInvoker(this.storedValue, "@APPLY_SNAPSHOT", function (snapshot) { - // if the snapshot is the same as the current one, avoid performing a reconcile - if (snapshot === self.snapshot) - return; - // else, apply it by calling the type logic - return self.type.applySnapshot(self, snapshot); - }); - addHiddenFinalProp(this.storedValue, "$treenode", this); - addHiddenFinalProp(this.storedValue, "toJSON", toJSON); - } - }); - Object.defineProperty(ObjectNode.prototype, "die", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) - return; - this.aboutToDie(); - this.finalizeDeath(); - } - }); - Object.defineProperty(ObjectNode.prototype, "aboutToDie", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._observableInstanceState === 0 /* UNINITIALIZED */) { - return; - } - this.getChildren().forEach(function (node) { - node.aboutToDie(); - }); - // beforeDestroy should run before the disposers since else we could end up in a situation where - // a disposer added with addDisposer at this stage (beforeDestroy) is actually never released - this.baseAboutToDie(); - this._internalEventsEmit("dispose" /* Dispose */); - this._internalEventsClear("dispose" /* Dispose */); - } - }); - Object.defineProperty(ObjectNode.prototype, "finalizeDeath", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - // invariant: not called directly but from "die" - this.getChildren().forEach(function (node) { - node.finalizeDeath(); - }); - this.root.identifierCache.notifyDied(this); - // "kill" the computed prop and just store the last snapshot - var snapshot = this.snapshot; - this._snapshotUponDeath = snapshot; - this._internalEventsClearAll(); - this.baseFinalizeDeath(); - } - }); - Object.defineProperty(ObjectNode.prototype, "onSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (onChange) { - this._addSnapshotReaction(); - return this._internalEventsRegister("snapshot" /* Snapshot */, onChange); - } - }); - Object.defineProperty(ObjectNode.prototype, "emitSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - this._internalEventsEmit("snapshot" /* Snapshot */, snapshot); - } - }); - Object.defineProperty(ObjectNode.prototype, "onPatch", { - enumerable: false, - configurable: true, - writable: true, - value: function (handler) { - return this._internalEventsRegister("patch" /* Patch */, handler); - } - }); - Object.defineProperty(ObjectNode.prototype, "emitPatch", { - enumerable: false, - configurable: true, - writable: true, - value: function (basePatch, source) { - if (this._internalEventsHasSubscribers("patch" /* Patch */)) { - var localizedPatch = extend({}, basePatch, { - path: source.path.substr(this.path.length) + "/" + basePatch.path // calculate the relative path of the patch - }); - var _a = __read(splitPatch(localizedPatch), 2), patch = _a[0], reversePatch = _a[1]; - this._internalEventsEmit("patch" /* Patch */, patch, reversePatch); - } - if (this.parent) - this.parent.emitPatch(basePatch, source); - } - }); - Object.defineProperty(ObjectNode.prototype, "hasDisposer", { - enumerable: false, - configurable: true, - writable: true, - value: function (disposer) { - return this._internalEventsHas("dispose" /* Dispose */, disposer); - } - }); - Object.defineProperty(ObjectNode.prototype, "addDisposer", { - enumerable: false, - configurable: true, - writable: true, - value: function (disposer) { - if (!this.hasDisposer(disposer)) { - this._internalEventsRegister("dispose" /* Dispose */, disposer, true); - return; - } - throw fail$1("cannot add a disposer when it is already registered for execution"); - } - }); - Object.defineProperty(ObjectNode.prototype, "removeDisposer", { - enumerable: false, - configurable: true, - writable: true, - value: function (disposer) { - if (!this._internalEventsHas("dispose" /* Dispose */, disposer)) { - throw fail$1("cannot remove a disposer which was never registered for execution"); - } - this._internalEventsUnregister("dispose" /* Dispose */, disposer); - } - }); - Object.defineProperty(ObjectNode.prototype, "removeMiddleware", { - enumerable: false, - configurable: true, - writable: true, - value: function (middleware) { - if (this.middlewares) { - var index = this.middlewares.indexOf(middleware); - if (index >= 0) { - this.middlewares.splice(index, 1); - } - } - } - }); - Object.defineProperty(ObjectNode.prototype, "addMiddleWare", { - enumerable: false, - configurable: true, - writable: true, - value: function (handler, includeHooks) { - var _this = this; - if (includeHooks === void 0) { includeHooks = true; } - var middleware = { handler: handler, includeHooks: includeHooks }; - if (!this.middlewares) - this.middlewares = [middleware]; - else - this.middlewares.push(middleware); - return function () { - _this.removeMiddleware(middleware); - }; - } - }); - Object.defineProperty(ObjectNode.prototype, "applyPatchLocally", { - enumerable: false, - configurable: true, - writable: true, - value: function (subpath, patch) { - this.assertWritable({ - subpath: subpath - }); - this.createObservableInstanceIfNeeded(); - this.type.applyPatchLocally(this, subpath, patch); - } - }); - Object.defineProperty(ObjectNode.prototype, "_addSnapshotReaction", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var _this = this; - if (!this._hasSnapshotReaction) { - var snapshotDisposer = reaction(function () { return _this.snapshot; }, function (snapshot) { return _this.emitSnapshot(snapshot); }, snapshotReactionOptions); - this.addDisposer(snapshotDisposer); - this._hasSnapshotReaction = true; - } - } - }); - // we proxy the methods to avoid creating an EventHandlers instance when it is not needed - Object.defineProperty(ObjectNode.prototype, "_internalEventsHasSubscribers", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - return !!this._internalEvents && this._internalEvents.hasSubscribers(event); - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsRegister", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, eventHandler, atTheBeginning) { - if (atTheBeginning === void 0) { atTheBeginning = false; } - if (!this._internalEvents) { - this._internalEvents = new EventHandlers(); - } - return this._internalEvents.register(event, eventHandler, atTheBeginning); - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsHas", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, eventHandler) { - return !!this._internalEvents && this._internalEvents.has(event, eventHandler); - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsUnregister", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, eventHandler) { - if (this._internalEvents) { - this._internalEvents.unregister(event, eventHandler); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsEmit", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - if (this._internalEvents) { - (_a = this._internalEvents).emit.apply(_a, __spread([event], args)); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsClear", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - if (this._internalEvents) { - this._internalEvents.clear(event); - } - } - }); - Object.defineProperty(ObjectNode.prototype, "_internalEventsClearAll", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this._internalEvents) { - this._internalEvents.clearAll(); - } - } - }); - return ObjectNode; - }(BaseNode)); - ObjectNode.prototype.createObservableInstance = action(ObjectNode.prototype.createObservableInstance); - ObjectNode.prototype.detach = action(ObjectNode.prototype.detach); - ObjectNode.prototype.die = action(ObjectNode.prototype.die); - - var _a; - /** - * @internal - * @hidden - */ - var TypeFlags; - (function (TypeFlags) { - TypeFlags[TypeFlags["String"] = 1] = "String"; - TypeFlags[TypeFlags["Number"] = 2] = "Number"; - TypeFlags[TypeFlags["Boolean"] = 4] = "Boolean"; - TypeFlags[TypeFlags["Date"] = 8] = "Date"; - TypeFlags[TypeFlags["Literal"] = 16] = "Literal"; - TypeFlags[TypeFlags["Array"] = 32] = "Array"; - TypeFlags[TypeFlags["Map"] = 64] = "Map"; - TypeFlags[TypeFlags["Object"] = 128] = "Object"; - TypeFlags[TypeFlags["Frozen"] = 256] = "Frozen"; - TypeFlags[TypeFlags["Optional"] = 512] = "Optional"; - TypeFlags[TypeFlags["Reference"] = 1024] = "Reference"; - TypeFlags[TypeFlags["Identifier"] = 2048] = "Identifier"; - TypeFlags[TypeFlags["Late"] = 4096] = "Late"; - TypeFlags[TypeFlags["Refinement"] = 8192] = "Refinement"; - TypeFlags[TypeFlags["Union"] = 16384] = "Union"; - TypeFlags[TypeFlags["Null"] = 32768] = "Null"; - TypeFlags[TypeFlags["Undefined"] = 65536] = "Undefined"; - TypeFlags[TypeFlags["Integer"] = 131072] = "Integer"; - TypeFlags[TypeFlags["Custom"] = 262144] = "Custom"; - TypeFlags[TypeFlags["SnapshotProcessor"] = 524288] = "SnapshotProcessor"; - })(TypeFlags || (TypeFlags = {})); - /** - * @internal - * @hidden - */ - var cannotDetermineSubtype = "cannotDetermine"; - /** @hidden */ - var $type = Symbol("$type"); - /** - * A base type produces a MST node (Node in the state tree) - * - * @internal - * @hidden - */ - var BaseType = /** @class */ (function () { - function BaseType(name) { - Object.defineProperty(this, _a, { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // these are just to make inner types avaialable to inherited classes - Object.defineProperty(this, "C", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "S", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "T", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "N", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "isType", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = name; - } - Object.defineProperty(BaseType.prototype, "create", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot, environment) { - typecheckInternal(this, snapshot); - return this.instantiate(null, "", environment, snapshot).value; - } - }); - Object.defineProperty(BaseType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, applyPostProcess) { - // istanbul ignore next - throw fail$1("unimplemented method"); - } - }); - Object.defineProperty(BaseType.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return type === this; - } - }); - Object.defineProperty(BaseType.prototype, "validate", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var node = getStateTreeNodeSafe(value); - if (node) { - var valueType = getType(value); - return this.isAssignableFrom(valueType) - ? typeCheckSuccess() - : typeCheckFailure(context, value); - // it is tempting to compare snapshots, but in that case we should always clone on assignments... - } - return this.isValidSnapshot(value, context); - } - }); - Object.defineProperty(BaseType.prototype, "is", { - enumerable: false, - configurable: true, - writable: true, - value: function (thing) { - return this.validate(thing, [{ path: "", type: this }]).length === 0; - } - }); - Object.defineProperty(BaseType.prototype, "Type", { - get: function () { - // istanbul ignore next - throw fail$1("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: false, - configurable: true - }); - Object.defineProperty(BaseType.prototype, "TypeWithoutSTN", { - get: function () { - // istanbul ignore next - throw fail$1("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: false, - configurable: true - }); - Object.defineProperty(BaseType.prototype, "SnapshotType", { - get: function () { - // istanbul ignore next - throw fail$1("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: false, - configurable: true - }); - Object.defineProperty(BaseType.prototype, "CreationType", { - get: function () { - // istanbul ignore next - throw fail$1("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: false, - configurable: true - }); - return BaseType; - }()); - _a = $type; - BaseType.prototype.create = action(BaseType.prototype.create); - /** - * A complex type produces a MST node (Node in the state tree) - * - * @internal - * @hidden - */ - var ComplexType = /** @class */ (function (_super) { - __extends$1(ComplexType, _super); - function ComplexType(name) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "identifierAttribute", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - return _this; - } - Object.defineProperty(ComplexType.prototype, "create", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot, environment) { - if (snapshot === void 0) { snapshot = this.getDefaultSnapshot(); } - return _super.prototype.create.call(this, snapshot, environment); - } - }); - Object.defineProperty(ComplexType.prototype, "getValue", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - node.createObservableInstanceIfNeeded(); - return node.storedValue; - } - }); - Object.defineProperty(ComplexType.prototype, "tryToReconcileNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue) { - if (current.isDetaching) - return false; - if (current.snapshot === newValue) { - // newValue is the current snapshot of the node, noop - return true; - } - if (isStateTreeNode(newValue) && getStateTreeNode(newValue) === current) { - // the current node is the same as the new one - return true; - } - if (current.type === this && - isMutable(newValue) && - !isStateTreeNode(newValue) && - (!current.identifierAttribute || - current.identifier === - normalizeIdentifier(newValue[current.identifierAttribute]))) { - // the newValue has no node, so can be treated like a snapshot - // we can reconcile - current.applySnapshot(newValue); - return true; - } - return false; - } - }); - Object.defineProperty(ComplexType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - var nodeReconciled = this.tryToReconcileNode(current, newValue); - if (nodeReconciled) { - current.setParent(parent, subpath); - return current; - } - // current node cannot be recycled in any way - current.die(); // noop if detaching - // attempt to reuse the new one - if (isStateTreeNode(newValue) && this.isAssignableFrom(getType(newValue))) { - // newValue is a Node as well, move it here.. - var newNode = getStateTreeNode(newValue); - newNode.setParent(parent, subpath); - return newNode; - } - // nothing to do, we have to create a new node - return this.instantiate(parent, subpath, undefined, newValue); - } - }); - Object.defineProperty(ComplexType.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return null; - } - }); - return ComplexType; - }(BaseType)); - ComplexType.prototype.create = action(ComplexType.prototype.create); - /** - * @internal - * @hidden - */ - var SimpleType = /** @class */ (function (_super) { - __extends$1(SimpleType, _super); - function SimpleType() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(SimpleType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - return snapshot; - } - }); - Object.defineProperty(SimpleType.prototype, "getValue", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - // if we ever find a case where scalar nodes can be accessed without iterating through its parent - // uncomment this to make sure the parent chain is created when this is accessed - // if (node.parent) { - // node.parent.createObservableInstanceIfNeeded() - // } - return node.storedValue; - } - }); - Object.defineProperty(SimpleType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return node.storedValue; - } - }); - Object.defineProperty(SimpleType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - // reconcile only if type and value are still the same, and only if the node is not detaching - if (!current.isDetaching && current.type === this && current.storedValue === newValue) { - return current; - } - var res = this.instantiate(parent, subpath, undefined, newValue); - current.die(); // noop if detaching - return res; - } - }); - Object.defineProperty(SimpleType.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return null; - } - }); - return SimpleType; - }(BaseType)); - /** - * Returns if a given value represents a type. - * - * @param value Value to check. - * @returns `true` if the value is a type. - */ - function isType(value) { - return typeof value === "object" && value && value.isType === true; - } - - /** @class */ ((function () { - function RunningAction(hooks, call) { - Object.defineProperty(this, "hooks", { - enumerable: true, - configurable: true, - writable: true, - value: hooks - }); - Object.defineProperty(this, "call", { - enumerable: true, - configurable: true, - writable: true, - value: call - }); - Object.defineProperty(this, "flowsPending", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "running", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - if (hooks) { - hooks.onStart(call); - } - } - Object.defineProperty(RunningAction.prototype, "finish", { - enumerable: false, - configurable: true, - writable: true, - value: function (error) { - if (this.running) { - this.running = false; - if (this.hooks) { - this.hooks.onFinish(this.call, error); - } - } - } - }); - Object.defineProperty(RunningAction.prototype, "incFlowsPending", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.flowsPending++; - } - }); - Object.defineProperty(RunningAction.prototype, "decFlowsPending", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.flowsPending--; - } - }); - Object.defineProperty(RunningAction.prototype, "hasFlowsPending", { - get: function () { - return this.flowsPending > 0; - }, - enumerable: false, - configurable: true - }); - return RunningAction; - })()); - - var nextActionId = 1; - var currentActionContext; - /** - * @internal - * @hidden - */ - function getCurrentActionContext() { - return currentActionContext; - } - /** - * @internal - * @hidden - */ - function getNextActionId() { - return nextActionId++; - } - // TODO: optimize away entire action context if there is no middleware in tree? - /** - * @internal - * @hidden - */ - function runWithActionContext(context, fn) { - var node = getStateTreeNode(context.context); - if (context.type === "action") { - node.assertAlive({ - actionContext: context - }); - } - var baseIsRunningAction = node._isRunningAction; - node._isRunningAction = true; - var previousContext = currentActionContext; - currentActionContext = context; - try { - return runMiddleWares(node, context, fn); - } - finally { - currentActionContext = previousContext; - node._isRunningAction = baseIsRunningAction; - } - } - /** - * @internal - * @hidden - */ - function getParentActionContext(parentContext) { - if (!parentContext) - return undefined; - if (parentContext.type === "action") - return parentContext; - return parentContext.parentActionEvent; - } - /** - * @internal - * @hidden - */ - function createActionInvoker(target, name, fn) { - var res = function () { - var id = getNextActionId(); - var parentContext = currentActionContext; - var parentActionContext = getParentActionContext(parentContext); - return runWithActionContext({ - type: "action", - name: name, - id: id, - args: argsToArray(arguments), - context: target, - tree: getRoot(target), - rootId: parentContext ? parentContext.rootId : id, - parentId: parentContext ? parentContext.id : 0, - allParentIds: parentContext - ? __spread(parentContext.allParentIds, [parentContext.id]) : [], - parentEvent: parentContext, - parentActionEvent: parentActionContext - }, fn); - }; - res._isMSTAction = true; - return res; - } - var CollectedMiddlewares = /** @class */ (function () { - function CollectedMiddlewares(node, fn) { - Object.defineProperty(this, "arrayIndex", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "inArrayIndex", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "middlewares", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - // we just push middleware arrays into an array of arrays to avoid making copies - if (fn.$mst_middleware) { - this.middlewares.push(fn.$mst_middleware); - } - var n = node; - // Find all middlewares. Optimization: cache this? - while (n) { - if (n.middlewares) - this.middlewares.push(n.middlewares); - n = n.parent; - } - } - Object.defineProperty(CollectedMiddlewares.prototype, "isEmpty", { - get: function () { - return this.middlewares.length <= 0; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CollectedMiddlewares.prototype, "getNextMiddleware", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var array = this.middlewares[this.arrayIndex]; - if (!array) - return undefined; - var item = array[this.inArrayIndex++]; - if (!item) { - this.arrayIndex++; - this.inArrayIndex = 0; - return this.getNextMiddleware(); - } - return item; - } - }); - return CollectedMiddlewares; - }()); - function runMiddleWares(node, baseCall, originalFn) { - var middlewares = new CollectedMiddlewares(node, originalFn); - // Short circuit - if (middlewares.isEmpty) - return action(originalFn).apply(null, baseCall.args); - var result = null; - function runNextMiddleware(call) { - var middleware = middlewares.getNextMiddleware(); - var handler = middleware && middleware.handler; - if (!handler) { - return action(originalFn).apply(null, call.args); - } - // skip hooks if asked to - if (!middleware.includeHooks && Hook[call.name]) { - return runNextMiddleware(call); - } - function next(call2, callback) { - // the result can contain - // - the non manipulated return value from an action - // - the non manipulated abort value - // - one of the above but manipulated through the callback function - result = runNextMiddleware(call2); - if (callback) { - result = callback(result); - } - } - function abort(value) { - // overwrite the result - // can be manipulated through middlewares earlier in the queue using the callback fn - result = value; - } - handler(call, next, abort); - return result; - } - return runNextMiddleware(baseCall); - } - - function safeStringify(value) { - try { - return JSON.stringify(value); - } - catch (e) { - // istanbul ignore next - return ""; - } - } - /** - * @internal - * @hidden - */ - function prettyPrintValue(value) { - return typeof value === "function" - ? "" - : isStateTreeNode(value) - ? "<" + value + ">" - : "`" + safeStringify(value) + "`"; - } - function shortenPrintValue(valueInString) { - return valueInString.length < 280 - ? valueInString - : valueInString.substring(0, 272) + "......" + valueInString.substring(valueInString.length - 8); - } - function toErrorString(error) { - var value = error.value; - var type = error.context[error.context.length - 1].type; - var fullPath = error.context - .map(function (_a) { - var path = _a.path; - return path; - }) - .filter(function (path) { return path.length > 0; }) - .join("/"); - var pathPrefix = fullPath.length > 0 ? "at path \"/" + fullPath + "\" " : ""; - var currentTypename = isStateTreeNode(value) - ? "value of type " + getStateTreeNode(value).type.name + ":" - : isPrimitive(value) - ? "value" - : "snapshot"; - var isSnapshotCompatible = type && isStateTreeNode(value) && type.is(getStateTreeNode(value).snapshot); - return ("" + pathPrefix + currentTypename + " " + prettyPrintValue(value) + " is not assignable " + (type ? "to type: `" + type.name + "`" : "") + - (error.message ? " (" + error.message + ")" : "") + - (type - ? isPrimitiveType(type) || isPrimitive(value) - ? "." - : ", expected an instance of `" + type.name + "` or a snapshot like `" + type.describe() + "` instead." + - (isSnapshotCompatible - ? " (Note that a snapshot of the provided value is compatible with the targeted type)" - : "") - : ".")); - } - /** - * @internal - * @hidden - */ - function getContextForPath(context, path, type) { - return context.concat([{ path: path, type: type }]); - } - /** - * @internal - * @hidden - */ - function typeCheckSuccess() { - return EMPTY_ARRAY; - } - /** - * @internal - * @hidden - */ - function typeCheckFailure(context, value, message) { - return [{ context: context, value: value, message: message }]; - } - /** - * @internal - * @hidden - */ - function flattenTypeErrors(errors) { - return errors.reduce(function (a, i) { return a.concat(i); }, []); - } - // TODO; doublecheck: typecheck should only needed to be invoked from: type.create and array / map / value.property will change - /** - * @internal - * @hidden - */ - function typecheckInternal(type, value) { - // runs typeChecking if it is in dev-mode or through a process.env.ENABLE_TYPE_CHECK flag - if (isTypeCheckingEnabled()) { - typecheck(type, value); - } - } - /** - * Run's the typechecker for the given type on the given value, which can be a snapshot or an instance. - * Throws if the given value is not according the provided type specification. - * Use this if you need typechecks even in a production build (by default all automatic runtime type checks will be skipped in production builds) - * - * @param type Type to check against. - * @param value Value to be checked, either a snapshot or an instance. - */ - function typecheck(type, value) { - var errors = type.validate(value, [{ path: "", type: type }]); - if (errors.length > 0) { - throw fail$1(validationErrorsToString(type, value, errors)); - } - } - function validationErrorsToString(type, value, errors) { - if (errors.length === 0) { - return undefined; - } - return ("Error while converting " + shortenPrintValue(prettyPrintValue(value)) + " to `" + type.name + "`:\n\n " + errors.map(toErrorString).join("\n ")); - } - - var identifierCacheId = 0; - /** - * @internal - * @hidden - */ - var IdentifierCache = /** @class */ (function () { - function IdentifierCache() { - Object.defineProperty(this, "cacheId", { - enumerable: true, - configurable: true, - writable: true, - value: identifierCacheId++ - }); - // n.b. in cache all identifiers are normalized to strings - Object.defineProperty(this, "cache", { - enumerable: true, - configurable: true, - writable: true, - value: observable$1.map() - }); - // last time the cache (array) for a given time changed - // n.b. it is not really the time, but just an integer that gets increased after each modification to the array - Object.defineProperty(this, "lastCacheModificationPerId", { - enumerable: true, - configurable: true, - writable: true, - value: observable$1.map() - }); - } - Object.defineProperty(IdentifierCache.prototype, "updateLastCacheModificationPerId", { - enumerable: false, - configurable: true, - writable: true, - value: function (identifier) { - var lcm = this.lastCacheModificationPerId.get(identifier); - // we start at 1 since 0 means no update since cache creation - this.lastCacheModificationPerId.set(identifier, lcm === undefined ? 1 : lcm + 1); - } - }); - Object.defineProperty(IdentifierCache.prototype, "getLastCacheModificationPerId", { - enumerable: false, - configurable: true, - writable: true, - value: function (identifier) { - var modificationId = this.lastCacheModificationPerId.get(identifier) || 0; - return this.cacheId + "-" + modificationId; - } - }); - Object.defineProperty(IdentifierCache.prototype, "addNodeToCache", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, lastCacheUpdate) { - if (lastCacheUpdate === void 0) { lastCacheUpdate = true; } - if (node.identifierAttribute) { - var identifier = node.identifier; - if (!this.cache.has(identifier)) { - this.cache.set(identifier, observable$1.array([], mobxShallow)); - } - var set = this.cache.get(identifier); - if (set.indexOf(node) !== -1) - throw fail$1("Already registered"); - set.push(node); - if (lastCacheUpdate) { - this.updateLastCacheModificationPerId(identifier); - } - } - } - }); - Object.defineProperty(IdentifierCache.prototype, "mergeCache", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var _this = this; - values(node.identifierCache.cache).forEach(function (nodes) { - return nodes.forEach(function (child) { - _this.addNodeToCache(child); - }); - }); - } - }); - Object.defineProperty(IdentifierCache.prototype, "notifyDied", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - if (node.identifierAttribute) { - var id = node.identifier; - var set = this.cache.get(id); - if (set) { - set.remove(node); - // remove empty sets from cache - if (!set.length) { - this.cache.delete(id); - } - this.updateLastCacheModificationPerId(node.identifier); - } - } - } - }); - Object.defineProperty(IdentifierCache.prototype, "splitCache", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var _this = this; - var res = new IdentifierCache(); - var basePath = node.path; - entries(this.cache).forEach(function (_a) { - var _b = __read(_a, 2), id = _b[0], nodes = _b[1]; - var modified = false; - for (var i = nodes.length - 1; i >= 0; i--) { - if (nodes[i].path.indexOf(basePath) === 0) { - res.addNodeToCache(nodes[i], false); // no need to update lastUpdated since it is a whole new cache - nodes.splice(i, 1); - modified = true; - } - } - if (modified) { - _this.updateLastCacheModificationPerId(id); - } - }); - return res; - } - }); - Object.defineProperty(IdentifierCache.prototype, "has", { - enumerable: false, - configurable: true, - writable: true, - value: function (type, identifier) { - var set = this.cache.get(identifier); - if (!set) - return false; - return set.some(function (candidate) { return type.isAssignableFrom(candidate.type); }); - } - }); - Object.defineProperty(IdentifierCache.prototype, "resolve", { - enumerable: false, - configurable: true, - writable: true, - value: function (type, identifier) { - var set = this.cache.get(identifier); - if (!set) - return null; - var matches = set.filter(function (candidate) { return type.isAssignableFrom(candidate.type); }); - switch (matches.length) { - case 0: - return null; - case 1: - return matches[0]; - default: - throw fail$1("Cannot resolve a reference to type '" + type.name + "' with id: '" + identifier + "' unambigously, there are multiple candidates: " + matches - .map(function (n) { return n.path; }) - .join(", ")); - } - } - }); - return IdentifierCache; - }()); - - /** - * @internal - * @hidden - */ - function createObjectNode(type, parent, subpath, environment, initialValue) { - var existingNode = getStateTreeNodeSafe(initialValue); - if (existingNode) { - if (existingNode.parent) { - // istanbul ignore next - throw fail$1("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 '" + (parent ? parent.path : "") + "/" + subpath + "', but it lives already at '" + existingNode.path + "'"); - } - if (parent) { - existingNode.setParent(parent, subpath); - } - // else it already has no parent since it is a pre-requisite - return existingNode; - } - // not a node, a snapshot - return new ObjectNode(type, parent, subpath, environment, initialValue); - } - /** - * @internal - * @hidden - */ - function createScalarNode(type, parent, subpath, environment, initialValue) { - return new ScalarNode(type, parent, subpath, environment, initialValue); - } - /** - * @internal - * @hidden - */ - function isNode(value) { - return value instanceof ScalarNode || value instanceof ObjectNode; - } - - /** - * @internal - * @hidden - */ - var NodeLifeCycle; - (function (NodeLifeCycle) { - NodeLifeCycle[NodeLifeCycle["INITIALIZING"] = 0] = "INITIALIZING"; - NodeLifeCycle[NodeLifeCycle["CREATED"] = 1] = "CREATED"; - NodeLifeCycle[NodeLifeCycle["FINALIZED"] = 2] = "FINALIZED"; - NodeLifeCycle[NodeLifeCycle["DETACHING"] = 3] = "DETACHING"; - NodeLifeCycle[NodeLifeCycle["DEAD"] = 4] = "DEAD"; // no coming back from this one - })(NodeLifeCycle || (NodeLifeCycle = {})); - /** - * Returns true if the given value is a node in a state tree. - * More precisely, that is, if the value is an instance of a - * `types.model`, `types.array` or `types.map`. - * - * @param value - * @returns true if the value is a state tree node. - */ - function isStateTreeNode(value) { - return !!(value && value.$treenode); - } - /** - * @internal - * @hidden - */ - function getStateTreeNode(value) { - if (!isStateTreeNode(value)) { - // istanbul ignore next - throw fail$1("Value " + value + " is no MST Node"); - } - return value.$treenode; - } - /** - * @internal - * @hidden - */ - function getStateTreeNodeSafe(value) { - return (value && value.$treenode) || null; - } - /** - * @internal - * @hidden - */ - function toJSON() { - return getStateTreeNode(this).snapshot; - } - /** - * @internal - * @hidden - */ - function resolveNodeByPathParts(base, pathParts, failIfResolveFails) { - if (failIfResolveFails === void 0) { failIfResolveFails = true; } - var current = base; - for (var i = 0; i < pathParts.length; i++) { - var part = pathParts[i]; - if (part === "..") { - current = current.parent; - if (current) - continue; // not everything has a parent - } - else if (part === ".") { - continue; - } - else if (current) { - if (current instanceof ScalarNode) { - // check if the value of a scalar resolves to a state tree node (e.g. references) - // then we can continue resolving... - try { - var value = current.value; - if (isStateTreeNode(value)) { - current = getStateTreeNode(value); - // fall through - } - } - catch (e) { - if (!failIfResolveFails) { - return undefined; - } - throw e; - } - } - if (current instanceof ObjectNode) { - var subType = current.getChildType(part); - if (subType) { - current = current.getChildNode(part); - if (current) - continue; - } - } - } - if (failIfResolveFails) - throw fail$1("Could not resolve '" + part + "' in path '" + (joinJsonPath(pathParts.slice(0, i)) || "/") + "' while resolving '" + joinJsonPath(pathParts) + "'"); - else - return undefined; - } - return current; - } - /** - * @internal - * @hidden - */ - function convertChildNodesToArray(childNodes) { - if (!childNodes) - return EMPTY_ARRAY; - var keys = Object.keys(childNodes); - if (!keys.length) - return EMPTY_ARRAY; - var result = new Array(keys.length); - keys.forEach(function (key, index) { - result[index] = childNodes[key]; - }); - return result; - } - - var plainObjectString = Object.toString(); - /** - * @internal - * @hidden - */ - var EMPTY_ARRAY = Object.freeze([]); - /** - * @internal - * @hidden - */ - var EMPTY_OBJECT = Object.freeze({}); - /** - * @internal - * @hidden - */ - var mobxShallow = getGlobalState().useProxies - ? { deep: false } - : { deep: false, proxy: false }; - Object.freeze(mobxShallow); - /** - * @internal - * @hidden - */ - function fail$1(message) { - if (message === void 0) { message = "Illegal state"; } - return new Error("[mobx-state-tree] " + message); - } - /** - * @internal - * @hidden - */ - function identity$2(_) { - return _; - } - /** - * pollyfill (for IE) suggested in MDN: - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger - * @internal - * @hidden - */ - var isInteger = Number.isInteger || - function (value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; - }; - /** - * @internal - * @hidden - */ - function isArray$2(val) { - return Array.isArray(val) || isObservableArray(val); - } - /** - * @internal - * @hidden - */ - function asArray(val) { - if (!val) - return EMPTY_ARRAY; - if (isArray$2(val)) - return val; - return [val]; - } - /** - * @internal - * @hidden - */ - function extend(a) { - var b = []; - for (var _i = 1; _i < arguments.length; _i++) { - b[_i - 1] = arguments[_i]; - } - for (var i = 0; i < b.length; i++) { - var current = b[i]; - for (var key in current) - a[key] = current[key]; - } - return a; - } - /** - * @internal - * @hidden - */ - function isPlainObject(value) { - var _a; - if (value === null || typeof value !== "object") - return false; - var proto = Object.getPrototypeOf(value); - if (proto == null) - return true; - return ((_a = proto.constructor) === null || _a === void 0 ? void 0 : _a.toString()) === plainObjectString; - } - /** - * @internal - * @hidden - */ - function isMutable(value) { - return (value !== null && - typeof value === "object" && - !(value instanceof Date) && - !(value instanceof RegExp)); - } - /** - * @internal - * @hidden - */ - function isPrimitive(value, includeDate) { - if (includeDate === void 0) { includeDate = true; } - if (value === null || value === undefined) - return true; - if (typeof value === "string" || - typeof value === "number" || - typeof value === "boolean" || - (includeDate && value instanceof Date)) - return true; - return false; - } - /** - * @internal - * @hidden - * Freeze a value and return it (if not in production) - */ - function freeze(value) { - return value; - } - /** - * @internal - * @hidden - * Recursively freeze a value (if not in production) - */ - function deepFreeze(value) { - return value; - } - /** - * @internal - * @hidden - */ - function isSerializable(value) { - return typeof value !== "function"; - } - /** - * @internal - * @hidden - */ - function defineProperty$1(object, key, descriptor) { - isObservableObject(object) - ? apiDefineProperty(object, key, descriptor) - : Object.defineProperty(object, key, descriptor); - } - /** - * @internal - * @hidden - */ - function addHiddenFinalProp(object, propName, value) { - defineProperty$1(object, propName, { - enumerable: false, - writable: false, - configurable: true, - value: value - }); - } - /** - * @internal - * @hidden - */ - var EventHandler = /** @class */ (function () { - function EventHandler() { - Object.defineProperty(this, "handlers", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - } - Object.defineProperty(EventHandler.prototype, "hasSubscribers", { - get: function () { - return this.handlers.length > 0; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(EventHandler.prototype, "register", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn, atTheBeginning) { - var _this = this; - if (atTheBeginning === void 0) { atTheBeginning = false; } - if (atTheBeginning) { - this.handlers.unshift(fn); - } - else { - this.handlers.push(fn); - } - return function () { - _this.unregister(fn); - }; - } - }); - Object.defineProperty(EventHandler.prototype, "has", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - return this.handlers.indexOf(fn) >= 0; - } - }); - Object.defineProperty(EventHandler.prototype, "unregister", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var index = this.handlers.indexOf(fn); - if (index >= 0) { - this.handlers.splice(index, 1); - } - } - }); - Object.defineProperty(EventHandler.prototype, "clear", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.handlers.length = 0; - } - }); - Object.defineProperty(EventHandler.prototype, "emit", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // make a copy just in case it changes - var handlers = this.handlers.slice(); - handlers.forEach(function (f) { return f.apply(void 0, __spread(args)); }); - } - }); - return EventHandler; - }()); - /** - * @internal - * @hidden - */ - var EventHandlers = /** @class */ (function () { - function EventHandlers() { - Object.defineProperty(this, "eventHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - } - Object.defineProperty(EventHandlers.prototype, "hasSubscribers", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - var handler = this.eventHandlers && this.eventHandlers[event]; - return !!handler && handler.hasSubscribers; - } - }); - Object.defineProperty(EventHandlers.prototype, "register", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, fn, atTheBeginning) { - if (atTheBeginning === void 0) { atTheBeginning = false; } - if (!this.eventHandlers) { - this.eventHandlers = {}; - } - var handler = this.eventHandlers[event]; - if (!handler) { - handler = this.eventHandlers[event] = new EventHandler(); - } - return handler.register(fn, atTheBeginning); - } - }); - Object.defineProperty(EventHandlers.prototype, "has", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, fn) { - var handler = this.eventHandlers && this.eventHandlers[event]; - return !!handler && handler.has(fn); - } - }); - Object.defineProperty(EventHandlers.prototype, "unregister", { - enumerable: false, - configurable: true, - writable: true, - value: function (event, fn) { - var handler = this.eventHandlers && this.eventHandlers[event]; - if (handler) { - handler.unregister(fn); - } - } - }); - Object.defineProperty(EventHandlers.prototype, "clear", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - if (this.eventHandlers) { - delete this.eventHandlers[event]; - } - } - }); - Object.defineProperty(EventHandlers.prototype, "clearAll", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - this.eventHandlers = undefined; - } - }); - Object.defineProperty(EventHandlers.prototype, "emit", { - enumerable: false, - configurable: true, - writable: true, - value: function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var handler = this.eventHandlers && this.eventHandlers[event]; - if (handler) { - (_a = handler).emit.apply(_a, __spread(args)); - } - } - }); - return EventHandlers; - }()); - /** - * @internal - * @hidden - */ - function argsToArray(args) { - var res = new Array(args.length); - for (var i = 0; i < args.length; i++) - res[i] = args[i]; - return res; - } - /** - * @internal - * @hidden - */ - function stringStartsWith(str, beginning) { - return str.indexOf(beginning) === 0; - } - /** - * @internal - * @hidden - */ - function warnError(msg) { - console.warn(new Error("[mobx-state-tree] " + msg)); - } - /** - * @internal - * @hidden - */ - function isTypeCheckingEnabled() { - return ((typeof process !== "undefined" && process.env && process.env.ENABLE_TYPE_CHECK === "true")); - } - - /** - * @internal - * @hidden - */ - function splitPatch(patch) { - if (!("oldValue" in patch)) - throw fail$1("Patches without `oldValue` field cannot be inversed"); - return [stripPatch(patch), invertPatch(patch)]; - } - /** - * @internal - * @hidden - */ - function stripPatch(patch) { - // strips `oldvalue` information from the patch, so that it becomes a patch conform the json-patch spec - // this removes the ability to undo the patch - switch (patch.op) { - case "add": - return { op: "add", path: patch.path, value: patch.value }; - case "remove": - return { op: "remove", path: patch.path }; - case "replace": - return { op: "replace", path: patch.path, value: patch.value }; - } - } - function invertPatch(patch) { - switch (patch.op) { - case "add": - return { - op: "remove", - path: patch.path - }; - case "remove": - return { - op: "add", - path: patch.path, - value: patch.oldValue - }; - case "replace": - return { - op: "replace", - path: patch.path, - value: patch.oldValue - }; - } - } - /** - * Simple simple check to check it is a number. - */ - function isNumber(x) { - return typeof x === "number"; - } - /** - * Escape slashes and backslashes. - * - * http://tools.ietf.org/html/rfc6901 - */ - function escapeJsonPath(path) { - if (isNumber(path) === true) { - return "" + path; - } - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) - return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); - } - /** - * Unescape slashes and backslashes. - */ - function unescapeJsonPath(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); - } - /** - * Generates a json-path compliant json path from path parts. - * - * @param path - * @returns - */ - function joinJsonPath(path) { - // `/` refers to property with an empty name, while `` refers to root itself! - if (path.length === 0) - return ""; - var getPathStr = function (p) { return p.map(escapeJsonPath).join("/"); }; - if (path[0] === "." || path[0] === "..") { - // relative - return getPathStr(path); - } - else { - // absolute - return "/" + getPathStr(path); - } - } - /** - * Splits and decodes a json path into several parts. - * - * @param path - * @returns - */ - function splitJsonPath(path) { - // `/` refers to property with an empty name, while `` refers to root itself! - var parts = path.split("/").map(unescapeJsonPath); - var valid = path === "" || - path === "." || - path === ".." || - stringStartsWith(path, "/") || - stringStartsWith(path, "./") || - stringStartsWith(path, "../"); - if (!valid) { - throw fail$1("a json path must be either rooted, empty or relative, but got '" + path + "'"); - } - // '/a/b/c' -> ["a", "b", "c"] - // '../../b/c' -> ["..", "..", "b", "c"] - // '' -> [] - // '/' -> [''] - // './a' -> [".", "a"] - // /./a' -> [".", "a"] equivalent to './a' - if (parts[0] === "") { - parts.shift(); - } - return parts; - } - - var SnapshotProcessor = /** @class */ (function (_super) { - __extends$1(SnapshotProcessor, _super); - function SnapshotProcessor(_subtype, _processors, name) { - var _this = _super.call(this, name || _subtype.name) || this; - Object.defineProperty(_this, "_subtype", { - enumerable: true, - configurable: true, - writable: true, - value: _subtype - }); - Object.defineProperty(_this, "_processors", { - enumerable: true, - configurable: true, - writable: true, - value: _processors - }); - return _this; - } - Object.defineProperty(SnapshotProcessor.prototype, "flags", { - get: function () { - return this._subtype.flags | TypeFlags.SnapshotProcessor; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SnapshotProcessor.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "snapshotProcessor(" + this._subtype.describe() + ")"; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "preProcessSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (sn) { - if (this._processors.preProcessor) { - return this._processors.preProcessor.call(null, sn); - } - return sn; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "postProcessSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (sn) { - if (this._processors.postProcessor) { - return this._processors.postProcessor.call(null, sn); - } - return sn; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "_fixNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var _this = this; - // the node has to use these methods rather than the original type ones - proxyNodeTypeMethods(node.type, this, "create"); - var oldGetSnapshot = node.getSnapshot; - node.getSnapshot = function () { - return _this.postProcessSnapshot(oldGetSnapshot.call(node)); - }; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var processedInitialValue = isStateTreeNode(initialValue) - ? initialValue - : this.preProcessSnapshot(initialValue); - var node = this._subtype.instantiate(parent, subpath, environment, processedInitialValue); - this._fixNode(node); - return node; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - var node = this._subtype.reconcile(current, isStateTreeNode(newValue) ? newValue : this.preProcessSnapshot(newValue), parent, subpath); - if (node !== current) { - this._fixNode(node); - } - return node; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, applyPostProcess) { - if (applyPostProcess === void 0) { applyPostProcess = true; } - var sn = this._subtype.getSnapshot(node); - return applyPostProcess ? this.postProcessSnapshot(sn) : sn; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var processedSn = this.preProcessSnapshot(value); - return this._subtype.validate(processedSn, context); - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subtype; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "is", { - enumerable: false, - configurable: true, - writable: true, - value: function (thing) { - var value = isType(thing) - ? this._subtype - : isStateTreeNode(thing) - ? getSnapshot(thing, false) - : this.preProcessSnapshot(thing); - return this._subtype.validate(value, [{ path: "", type: this._subtype }]).length === 0; - } - }); - Object.defineProperty(SnapshotProcessor.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this._subtype.isAssignableFrom(type); - } - }); - return SnapshotProcessor; - }(BaseType)); - function proxyNodeTypeMethods(nodeType, snapshotProcessorType) { - var e_1, _a; - var methods = []; - for (var _i = 2; _i < arguments.length; _i++) { - methods[_i - 2] = arguments[_i]; - } - try { - for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var method = methods_1_1.value; - nodeType[method] = snapshotProcessorType[method].bind(snapshotProcessorType); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1.return)) _a.call(methods_1); - } - finally { if (e_1) throw e_1.error; } - } - } - /** - * `types.snapshotProcessor` - Runs a pre/post snapshot processor before/after serializing a given type. - * - * Example: - * ```ts - * const Todo1 = types.model({ text: types.string }) - * // in the backend the text type must be null when empty - * interface BackendTodo { - * text: string | null - * } - * const Todo2 = types.snapshotProcessor(Todo1, { - * // from snapshot to instance - * preProcessor(sn: BackendTodo) { - * return { - * text: sn.text || ""; - * } - * }, - * // from instance to snapshot - * postProcessor(sn): BackendTodo { - * return { - * text: !sn.text ? null : sn.text - * } - * } - * }) - * ``` - * - * @param type Type to run the processors over. - * @param processors Processors to run. - * @param name Type name, or undefined to inherit the inner type one. - * @returns - */ - function snapshotProcessor(type, processors, name) { - return new SnapshotProcessor(type, processors, name); - } - - var needsIdentifierError = "Map.put can only be used to store complex values that have an identifier type attribute"; - function tryCollectModelTypes(type, modelTypes) { - var e_1, _a; - var subtypes = type.getSubTypes(); - if (subtypes === cannotDetermineSubtype) { - return false; - } - if (subtypes) { - var subtypesArray = asArray(subtypes); - try { - for (var subtypesArray_1 = __values(subtypesArray), subtypesArray_1_1 = subtypesArray_1.next(); !subtypesArray_1_1.done; subtypesArray_1_1 = subtypesArray_1.next()) { - var subtype = subtypesArray_1_1.value; - if (!tryCollectModelTypes(subtype, modelTypes)) - return false; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (subtypesArray_1_1 && !subtypesArray_1_1.done && (_a = subtypesArray_1.return)) _a.call(subtypesArray_1); - } - finally { if (e_1) throw e_1.error; } - } - } - if (type instanceof ModelType) { - modelTypes.push(type); - } - return true; - } - /** - * @internal - * @hidden - */ - var MapIdentifierMode; - (function (MapIdentifierMode) { - MapIdentifierMode[MapIdentifierMode["UNKNOWN"] = 0] = "UNKNOWN"; - MapIdentifierMode[MapIdentifierMode["YES"] = 1] = "YES"; - MapIdentifierMode[MapIdentifierMode["NO"] = 2] = "NO"; - })(MapIdentifierMode || (MapIdentifierMode = {})); - var MSTMap = /** @class */ (function (_super) { - __extends$1(MSTMap, _super); - function MSTMap(initialData) { - return _super.call(this, initialData, observable$1.ref.enhancer) || this; - } - Object.defineProperty(MSTMap.prototype, "get", { - enumerable: false, - configurable: true, - writable: true, - value: function (key) { - // maybe this is over-enthousiastic? normalize numeric keys to strings - return _super.prototype.get.call(this, "" + key); - } - }); - Object.defineProperty(MSTMap.prototype, "has", { - enumerable: false, - configurable: true, - writable: true, - value: function (key) { - return _super.prototype.has.call(this, "" + key); - } - }); - Object.defineProperty(MSTMap.prototype, "delete", { - enumerable: false, - configurable: true, - writable: true, - value: function (key) { - return _super.prototype.delete.call(this, "" + key); - } - }); - Object.defineProperty(MSTMap.prototype, "set", { - enumerable: false, - configurable: true, - writable: true, - value: function (key, value) { - return _super.prototype.set.call(this, "" + key, value); - } - }); - Object.defineProperty(MSTMap.prototype, "put", { - enumerable: false, - configurable: true, - writable: true, - value: function (value) { - if (!value) - throw fail$1("Map.put cannot be used to set empty values"); - if (isStateTreeNode(value)) { - var node = getStateTreeNode(value); - if (node.identifier === null) { - throw fail$1(needsIdentifierError); - } - this.set(node.identifier, value); - return value; - } - else if (!isMutable(value)) { - throw fail$1("Map.put can only be used to store complex values"); - } - else { - var mapNode = getStateTreeNode(this); - var mapType = mapNode.type; - if (mapType.identifierMode !== MapIdentifierMode.YES) { - throw fail$1(needsIdentifierError); - } - var idAttr = mapType.mapIdentifierAttribute; - var id = value[idAttr]; - if (!isValidIdentifier(id)) { - // try again but this time after creating a node for the value - // since it might be an optional identifier - var newNode = this.put(mapType.getChildType().create(value, mapNode.environment)); - return this.put(getSnapshot(newNode)); - } - var key = normalizeIdentifier(id); - this.set(key, value); - return this.get(key); - } - } - }); - return MSTMap; - }(ObservableMap)); - /** - * @internal - * @hidden - */ - var MapType = /** @class */ (function (_super) { - __extends$1(MapType, _super); - function MapType(name, _subType, hookInitializers) { - if (hookInitializers === void 0) { hookInitializers = []; } - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_subType", { - enumerable: true, - configurable: true, - writable: true, - value: _subType - }); - Object.defineProperty(_this, "identifierMode", { - enumerable: true, - configurable: true, - writable: true, - value: MapIdentifierMode.UNKNOWN - }); - Object.defineProperty(_this, "mapIdentifierAttribute", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Map - }); - Object.defineProperty(_this, "hookInitializers", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - _this._determineIdentifierMode(); - _this.hookInitializers = hookInitializers; - return _this; - } - Object.defineProperty(MapType.prototype, "hooks", { - enumerable: false, - configurable: true, - writable: true, - value: function (hooks) { - var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks]; - return new MapType(this.name, this._subType, hookInitializers); - } - }); - Object.defineProperty(MapType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - this._determineIdentifierMode(); - return createObjectNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(MapType.prototype, "_determineIdentifierMode", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - if (this.identifierMode !== MapIdentifierMode.UNKNOWN) { - return; - } - var modelTypes = []; - if (tryCollectModelTypes(this._subType, modelTypes)) { - var identifierAttribute_1 = undefined; - modelTypes.forEach(function (type) { - if (type.identifierAttribute) { - if (identifierAttribute_1 && identifierAttribute_1 !== type.identifierAttribute) { - throw fail$1("The objects in a map should all have the same identifier attribute, expected '" + identifierAttribute_1 + "', but child of type '" + type.name + "' declared attribute '" + type.identifierAttribute + "' as identifier"); - } - identifierAttribute_1 = type.identifierAttribute; - } - }); - if (identifierAttribute_1) { - this.identifierMode = MapIdentifierMode.YES; - this.mapIdentifierAttribute = identifierAttribute_1; - } - else { - this.identifierMode = MapIdentifierMode.NO; - } - } - } - }); - Object.defineProperty(MapType.prototype, "initializeChildNodes", { - enumerable: false, - configurable: true, - writable: true, - value: function (objNode, initialSnapshot) { - if (initialSnapshot === void 0) { initialSnapshot = {}; } - var subType = objNode.type._subType; - var result = {}; - Object.keys(initialSnapshot).forEach(function (name) { - result[name] = subType.instantiate(objNode, name, undefined, initialSnapshot[name]); - }); - return result; - } - }); - Object.defineProperty(MapType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - return new MSTMap(childNodes); - } - }); - Object.defineProperty(MapType.prototype, "finalizeNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, instance) { - interceptReads(instance, node.unbox); - var type = node.type; - type.hookInitializers.forEach(function (initializer) { - var hooks = initializer(instance); - Object.keys(hooks).forEach(function (name) { - var hook = hooks[name]; - var actionInvoker = createActionInvoker(instance, name, hook); - (addHiddenFinalProp )(instance, name, actionInvoker); - }); - }); - intercept(instance, this.willChange); - observe(instance, this.didChange); - } - }); - Object.defineProperty(MapType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "Map"; - } - }); - Object.defineProperty(MapType.prototype, "getChildren", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - // return (node.storedValue as ObservableMap).values() - return values(node.storedValue); - } - }); - Object.defineProperty(MapType.prototype, "getChildNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, key) { - var childNode = node.storedValue.get("" + key); - if (!childNode) - throw fail$1("Not a child " + key); - return childNode; - } - }); - Object.defineProperty(MapType.prototype, "willChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (change) { - var node = getStateTreeNode(change.object); - var key = change.name; - node.assertWritable({ subpath: key }); - var mapType = node.type; - var subType = mapType._subType; - switch (change.type) { - case "update": - { - var newValue = change.newValue; - var oldValue = change.object.get(key); - if (newValue === oldValue) - return null; - typecheckInternal(subType, newValue); - change.newValue = subType.reconcile(node.getChildNode(key), change.newValue, node, key); - mapType.processIdentifier(key, change.newValue); - } - break; - case "add": - { - typecheckInternal(subType, change.newValue); - change.newValue = subType.instantiate(node, key, undefined, change.newValue); - mapType.processIdentifier(key, change.newValue); - } - break; - } - return change; - } - }); - Object.defineProperty(MapType.prototype, "processIdentifier", { - enumerable: false, - configurable: true, - writable: true, - value: function (expected, node) { - if (this.identifierMode === MapIdentifierMode.YES && node instanceof ObjectNode) { - var identifier = node.identifier; - if (identifier !== expected) - throw fail$1("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '" + identifier + "', but expected: '" + expected + "'"); - } - } - }); - Object.defineProperty(MapType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var res = {}; - node.getChildren().forEach(function (childNode) { - res[childNode.subpath] = childNode.snapshot; - }); - return res; - } - }); - Object.defineProperty(MapType.prototype, "processInitialSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - var processed = {}; - Object.keys(childNodes).forEach(function (key) { - processed[key] = childNodes[key].getSnapshot(); - }); - return processed; - } - }); - Object.defineProperty(MapType.prototype, "didChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (change) { - var node = getStateTreeNode(change.object); - switch (change.type) { - case "update": - return void node.emitPatch({ - op: "replace", - path: escapeJsonPath(change.name), - value: change.newValue.snapshot, - oldValue: change.oldValue ? change.oldValue.snapshot : undefined - }, node); - case "add": - return void node.emitPatch({ - op: "add", - path: escapeJsonPath(change.name), - value: change.newValue.snapshot, - oldValue: undefined - }, node); - case "delete": - // a node got deleted, get the old snapshot and make the node die - var oldSnapshot = change.oldValue.snapshot; - change.oldValue.die(); - // emit the patch - return void node.emitPatch({ - op: "remove", - path: escapeJsonPath(change.name), - oldValue: oldSnapshot - }, node); - } - } - }); - Object.defineProperty(MapType.prototype, "applyPatchLocally", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath, patch) { - var target = node.storedValue; - switch (patch.op) { - case "add": - case "replace": - target.set(subpath, patch.value); - break; - case "remove": - target.delete(subpath); - break; - } - } - }); - Object.defineProperty(MapType.prototype, "applySnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, snapshot) { - typecheckInternal(this, snapshot); - var target = node.storedValue; - var currentKeys = {}; - Array.from(target.keys()).forEach(function (key) { - currentKeys[key] = false; - }); - if (snapshot) { - // Don't use target.replace, as it will throw away all existing items first - for (var key in snapshot) { - target.set(key, snapshot[key]); - currentKeys["" + key] = true; - } - } - Object.keys(currentKeys).forEach(function (key) { - if (currentKeys[key] === false) - target.delete(key); - }); - } - }); - Object.defineProperty(MapType.prototype, "getChildType", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subType; - } - }); - Object.defineProperty(MapType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var _this = this; - if (!isPlainObject(value)) { - return typeCheckFailure(context, value, "Value is not a plain object"); - } - return flattenTypeErrors(Object.keys(value).map(function (path) { - return _this._subType.validate(value[path], getContextForPath(context, path, _this._subType)); - })); - } - }); - Object.defineProperty(MapType.prototype, "getDefaultSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return EMPTY_OBJECT; - } - }); - Object.defineProperty(MapType.prototype, "removeChild", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath) { - node.storedValue.delete(subpath); - } - }); - return MapType; - }(ComplexType)); - MapType.prototype.applySnapshot = action(MapType.prototype.applySnapshot); - /** - * `types.map` - Creates a key based collection type who's children are all of a uniform declared type. - * If the type stored in a map has an identifier, it is mandatory to store the child under that identifier in the map. - * - * This type will always produce [observable maps](https://mobx.js.org/api.html#observablemap) - * - * Example: - * ```ts - * const Todo = types.model({ - * id: types.identifier, - * task: types.string - * }) - * - * const TodoStore = types.model({ - * todos: types.map(Todo) - * }) - * - * const s = TodoStore.create({ todos: {} }) - * unprotect(s) - * s.todos.set(17, { task: "Grab coffee", id: 17 }) - * s.todos.put({ task: "Grab cookie", id: 18 }) // put will infer key from the identifier - * console.log(s.todos.get(17).task) // prints: "Grab coffee" - * ``` - * - * @param subtype - * @returns - */ - function map$1(subtype) { - return new MapType("map", subtype); - } - - /** - * @internal - * @hidden - */ - var ArrayType = /** @class */ (function (_super) { - __extends$1(ArrayType, _super); - function ArrayType(name, _subType, hookInitializers) { - if (hookInitializers === void 0) { hookInitializers = []; } - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_subType", { - enumerable: true, - configurable: true, - writable: true, - value: _subType - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Array - }); - Object.defineProperty(_this, "hookInitializers", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - _this.hookInitializers = hookInitializers; - return _this; - } - Object.defineProperty(ArrayType.prototype, "hooks", { - enumerable: false, - configurable: true, - writable: true, - value: function (hooks) { - var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks]; - return new ArrayType(this.name, this._subType, hookInitializers); - } - }); - Object.defineProperty(ArrayType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - return createObjectNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(ArrayType.prototype, "initializeChildNodes", { - enumerable: false, - configurable: true, - writable: true, - value: function (objNode, snapshot) { - if (snapshot === void 0) { snapshot = []; } - var subType = objNode.type._subType; - var result = {}; - snapshot.forEach(function (item, index) { - var subpath = "" + index; - result[subpath] = subType.instantiate(objNode, subpath, undefined, item); - }); - return result; - } - }); - Object.defineProperty(ArrayType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - return observable$1.array(convertChildNodesToArray(childNodes), mobxShallow); - } - }); - Object.defineProperty(ArrayType.prototype, "finalizeNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, instance) { - getAdministration(instance).dehancer = node.unbox; - var type = node.type; - type.hookInitializers.forEach(function (initializer) { - var hooks = initializer(instance); - Object.keys(hooks).forEach(function (name) { - var hook = hooks[name]; - var actionInvoker = createActionInvoker(instance, name, hook); - (addHiddenFinalProp )(instance, name, actionInvoker); - }); - }); - intercept(instance, this.willChange); - observe(instance, this.didChange); - } - }); - Object.defineProperty(ArrayType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subType.describe() + "[]"; - } - }); - Object.defineProperty(ArrayType.prototype, "getChildren", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return node.storedValue.slice(); - } - }); - Object.defineProperty(ArrayType.prototype, "getChildNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, key) { - var index = Number(key); - if (index < node.storedValue.length) - return node.storedValue[index]; - throw fail$1("Not a child: " + key); - } - }); - Object.defineProperty(ArrayType.prototype, "willChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (change) { - var node = getStateTreeNode(change.object); - node.assertWritable({ subpath: "" + change.index }); - var subType = node.type._subType; - var childNodes = node.getChildren(); - switch (change.type) { - case "update": - { - if (change.newValue === change.object[change.index]) - return null; - var updatedNodes = reconcileArrayChildren(node, subType, [childNodes[change.index]], [change.newValue], [change.index]); - if (!updatedNodes) { - return null; - } - change.newValue = updatedNodes[0]; - } - break; - case "splice": - { - var index_1 = change.index, removedCount = change.removedCount, added = change.added; - var addedNodes = reconcileArrayChildren(node, subType, childNodes.slice(index_1, index_1 + removedCount), added, added.map(function (_, i) { return index_1 + i; })); - if (!addedNodes) { - return null; - } - change.added = addedNodes; - // update paths of remaining items - for (var i = index_1 + removedCount; i < childNodes.length; i++) { - childNodes[i].setParent(node, "" + (i + added.length - removedCount)); - } - } - break; - } - return change; - } - }); - Object.defineProperty(ArrayType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return node.getChildren().map(function (childNode) { return childNode.snapshot; }); - } - }); - Object.defineProperty(ArrayType.prototype, "processInitialSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - var processed = []; - Object.keys(childNodes).forEach(function (key) { - processed.push(childNodes[key].getSnapshot()); - }); - return processed; - } - }); - Object.defineProperty(ArrayType.prototype, "didChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (change) { - var node = getStateTreeNode(change.object); - switch (change.type) { - case "update": - return void node.emitPatch({ - op: "replace", - path: "" + change.index, - value: change.newValue.snapshot, - oldValue: change.oldValue ? change.oldValue.snapshot : undefined - }, node); - case "splice": - for (var i = change.removedCount - 1; i >= 0; i--) - node.emitPatch({ - op: "remove", - path: "" + (change.index + i), - oldValue: change.removed[i].snapshot - }, node); - for (var i = 0; i < change.addedCount; i++) - node.emitPatch({ - op: "add", - path: "" + (change.index + i), - value: node.getChildNode("" + (change.index + i)).snapshot, - oldValue: undefined - }, node); - return; - } - } - }); - Object.defineProperty(ArrayType.prototype, "applyPatchLocally", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath, patch) { - var target = node.storedValue; - var index = subpath === "-" ? target.length : Number(subpath); - switch (patch.op) { - case "replace": - target[index] = patch.value; - break; - case "add": - target.splice(index, 0, patch.value); - break; - case "remove": - target.splice(index, 1); - break; - } - } - }); - Object.defineProperty(ArrayType.prototype, "applySnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, snapshot) { - typecheckInternal(this, snapshot); - var target = node.storedValue; - target.replace(snapshot); - } - }); - Object.defineProperty(ArrayType.prototype, "getChildType", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subType; - } - }); - Object.defineProperty(ArrayType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var _this = this; - if (!isArray$2(value)) { - return typeCheckFailure(context, value, "Value is not an array"); - } - return flattenTypeErrors(value.map(function (item, index) { - return _this._subType.validate(item, getContextForPath(context, "" + index, _this._subType)); - })); - } - }); - Object.defineProperty(ArrayType.prototype, "getDefaultSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return EMPTY_ARRAY; - } - }); - Object.defineProperty(ArrayType.prototype, "removeChild", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath) { - node.storedValue.splice(Number(subpath), 1); - } - }); - return ArrayType; - }(ComplexType)); - ArrayType.prototype.applySnapshot = action(ArrayType.prototype.applySnapshot); - /** - * `types.array` - Creates an index based collection type who's children are all of a uniform declared type. - * - * This type will always produce [observable arrays](https://mobx.js.org/api.html#observablearray) - * - * Example: - * ```ts - * const Todo = types.model({ - * task: types.string - * }) - * - * const TodoStore = types.model({ - * todos: types.array(Todo) - * }) - * - * const s = TodoStore.create({ todos: [] }) - * unprotect(s) // needed to allow modifying outside of an action - * s.todos.push({ task: "Grab coffee" }) - * console.log(s.todos[0]) // prints: "Grab coffee" - * ``` - * - * @param subtype - * @returns - */ - function array(subtype) { - return new ArrayType(subtype.name + "[]", subtype); - } - function reconcileArrayChildren(parent, childType, oldNodes, newValues, newPaths) { - var nothingChanged = true; - for (var i = 0;; i++) { - var hasNewNode = i <= newValues.length - 1; - var oldNode = oldNodes[i]; - var newValue = hasNewNode ? newValues[i] : undefined; - var newPath = "" + newPaths[i]; - // for some reason, instead of newValue we got a node, fallback to the storedValue - // TODO: https://github.com/mobxjs/mobx-state-tree/issues/340#issuecomment-325581681 - if (isNode(newValue)) - newValue = newValue.storedValue; - if (!oldNode && !hasNewNode) { - // both are empty, end - break; - } - else if (!hasNewNode) { - // new one does not exists - nothingChanged = false; - oldNodes.splice(i, 1); - if (oldNode instanceof ObjectNode) { - // since it is going to be returned by pop/splice/shift better create it before killing it - // so it doesn't end up in an undead state - oldNode.createObservableInstanceIfNeeded(); - } - oldNode.die(); - i--; - } - else if (!oldNode) { - // there is no old node, create it - // check if already belongs to the same parent. if so, avoid pushing item in. only swapping can occur. - if (isStateTreeNode(newValue) && getStateTreeNode(newValue).parent === parent) { - // this node is owned by this parent, but not in the reconcilable set, so it must be double - throw fail$1("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 '" + parent.path + "/" + newPath + "', but it lives already at '" + getStateTreeNode(newValue).path + "'"); - } - nothingChanged = false; - var newNode = valueAsNode(childType, parent, newPath, newValue); - oldNodes.splice(i, 0, newNode); - } - else if (areSame(oldNode, newValue)) { - // both are the same, reconcile - oldNodes[i] = valueAsNode(childType, parent, newPath, newValue, oldNode); - } - else { - // nothing to do, try to reorder - var oldMatch = undefined; - // find a possible candidate to reuse - for (var j = i; j < oldNodes.length; j++) { - if (areSame(oldNodes[j], newValue)) { - oldMatch = oldNodes.splice(j, 1)[0]; - break; - } - } - nothingChanged = false; - var newNode = valueAsNode(childType, parent, newPath, newValue, oldMatch); - oldNodes.splice(i, 0, newNode); - } - } - return nothingChanged ? null : oldNodes; - } - /** - * Convert a value to a node at given parent and subpath. Attempts to reuse old node if possible and given. - */ - function valueAsNode(childType, parent, subpath, newValue, oldNode) { - // ensure the value is valid-ish - typecheckInternal(childType, newValue); - function getNewNode() { - // the new value has a MST node - if (isStateTreeNode(newValue)) { - var childNode = getStateTreeNode(newValue); - childNode.assertAlive(EMPTY_OBJECT); - // the node lives here - if (childNode.parent !== null && childNode.parent === parent) { - childNode.setParent(parent, subpath); - return childNode; - } - } - // there is old node and new one is a value/snapshot - if (oldNode) { - return childType.reconcile(oldNode, newValue, parent, subpath); - } - // nothing to do, create from scratch - return childType.instantiate(parent, subpath, undefined, newValue); - } - var newNode = getNewNode(); - if (oldNode && oldNode !== newNode) { - if (oldNode instanceof ObjectNode) { - // since it is going to be returned by pop/splice/shift better create it before killing it - // so it doesn't end up in an undead state - oldNode.createObservableInstanceIfNeeded(); - } - oldNode.die(); - } - return newNode; - } - /** - * Check if a node holds a value. - */ - function areSame(oldNode, newValue) { - // never consider dead old nodes for reconciliation - if (!oldNode.isAlive) { - return false; - } - // the new value has the same node - if (isStateTreeNode(newValue)) { - var newNode = getStateTreeNode(newValue); - return newNode.isAlive && newNode === oldNode; - } - // the provided value is the snapshot of the old node - if (oldNode.snapshot === newValue) { - return true; - } - // new value is a snapshot with the correct identifier - return (oldNode instanceof ObjectNode && - oldNode.identifier !== null && - oldNode.identifierAttribute && - isPlainObject(newValue) && - oldNode.identifier === normalizeIdentifier(newValue[oldNode.identifierAttribute]) && - oldNode.type.is(newValue)); - } - - var PRE_PROCESS_SNAPSHOT = "preProcessSnapshot"; - var POST_PROCESS_SNAPSHOT = "postProcessSnapshot"; - function objectTypeToString() { - return getStateTreeNode(this).toString(); - } - var defaultObjectOptions = { - name: "AnonymousModel", - properties: {}, - initializers: EMPTY_ARRAY - }; - function toPropertiesObject(declaredProps) { - // loop through properties and ensures that all items are types - return Object.keys(declaredProps).reduce(function (props, key) { - var _a, _b, _c; - // warn if user intended a HOOK - if (key in Hook) - throw fail$1("Hook '" + key + "' was defined as property. Hooks should be defined as part of the actions"); - // the user intended to use a view - var descriptor = Object.getOwnPropertyDescriptor(props, key); - if ("get" in descriptor) { - throw fail$1("Getters are not supported as properties. Please use views instead"); - } - // undefined and null are not valid - var value = descriptor.value; - if (value === null || value === undefined) { - throw fail$1("The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?"); - // its a primitive, convert to its type - } - else if (isPrimitive(value)) { - return Object.assign({}, props, (_a = {}, - _a[key] = optional(getPrimitiveFactoryFromValue(value), value), - _a)); - // map defaults to empty object automatically for models - } - else if (value instanceof MapType) { - return Object.assign({}, props, (_b = {}, - _b[key] = optional(value, {}), - _b)); - } - else if (value instanceof ArrayType) { - return Object.assign({}, props, (_c = {}, _c[key] = optional(value, []), _c)); - // its already a type - } - else if (isType(value)) { - return props; - // its a function, maybe the user wanted a view? - } - else { - throw fail$1("Invalid type definition for property '" + key + "', cannot infer a type from a value like '" + value + "' (" + typeof value + ")"); - } - }, declaredProps); - } - /** - * @internal - * @hidden - */ - var ModelType = /** @class */ (function (_super) { - __extends$1(ModelType, _super); - function ModelType(opts) { - var _this = _super.call(this, opts.name || defaultObjectOptions.name) || this; - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Object - }); - /* - * The original object definition - */ - Object.defineProperty(_this, "initializers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "properties", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "preProcessor", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "postProcessor", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "propertyNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "named", { - enumerable: true, - configurable: true, - writable: true, - value: function (name) { - return _this.cloneAndEnhance({ name: name }); - } - }); - Object.defineProperty(_this, "props", { - enumerable: true, - configurable: true, - writable: true, - value: function (properties) { - return _this.cloneAndEnhance({ properties: properties }); - } - }); - Object.defineProperty(_this, "preProcessSnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: function (preProcessor) { - var currentPreprocessor = _this.preProcessor; - if (!currentPreprocessor) - return _this.cloneAndEnhance({ preProcessor: preProcessor }); - else - return _this.cloneAndEnhance({ - preProcessor: function (snapshot) { return currentPreprocessor(preProcessor(snapshot)); } - }); - } - }); - Object.defineProperty(_this, "postProcessSnapshot", { - enumerable: true, - configurable: true, - writable: true, - value: function (postProcessor) { - var currentPostprocessor = _this.postProcessor; - if (!currentPostprocessor) - return _this.cloneAndEnhance({ postProcessor: postProcessor }); - else - return _this.cloneAndEnhance({ - postProcessor: function (snapshot) { return postProcessor(currentPostprocessor(snapshot)); } - }); - } - }); - Object.assign(_this, defaultObjectOptions, opts); - // ensures that any default value gets converted to its related type - _this.properties = toPropertiesObject(_this.properties); - freeze(_this.properties); // make sure nobody messes with it - _this.propertyNames = Object.keys(_this.properties); - _this.identifierAttribute = _this._getIdentifierAttribute(); - return _this; - } - Object.defineProperty(ModelType.prototype, "_getIdentifierAttribute", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var identifierAttribute = undefined; - this.forAllProps(function (propName, propType) { - if (propType.flags & TypeFlags.Identifier) { - if (identifierAttribute) - throw fail$1("Cannot define property '" + propName + "' as object identifier, property '" + identifierAttribute + "' is already defined as identifier property"); - identifierAttribute = propName; - } - }); - return identifierAttribute; - } - }); - Object.defineProperty(ModelType.prototype, "cloneAndEnhance", { - enumerable: false, - configurable: true, - writable: true, - value: function (opts) { - return new ModelType({ - name: opts.name || this.name, - properties: Object.assign({}, this.properties, opts.properties), - initializers: this.initializers.concat(opts.initializers || []), - preProcessor: opts.preProcessor || this.preProcessor, - postProcessor: opts.postProcessor || this.postProcessor - }); - } - }); - Object.defineProperty(ModelType.prototype, "actions", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - var actionInitializer = function (self) { - _this.instantiateActions(self, fn(self)); - return self; - }; - return this.cloneAndEnhance({ initializers: [actionInitializer] }); - } - }); - Object.defineProperty(ModelType.prototype, "instantiateActions", { - enumerable: false, - configurable: true, - writable: true, - value: function (self, actions) { - // check if return is correct - if (!isPlainObject(actions)) - throw fail$1("actions initializer should return a plain object containing actions"); - // bind actions to the object created - Object.keys(actions).forEach(function (name) { - // warn if preprocessor was given - if (name === PRE_PROCESS_SNAPSHOT) - throw fail$1("Cannot define action '" + PRE_PROCESS_SNAPSHOT + "', it should be defined using 'type.preProcessSnapshot(fn)' instead"); - // warn if postprocessor was given - if (name === POST_PROCESS_SNAPSHOT) - throw fail$1("Cannot define action '" + POST_PROCESS_SNAPSHOT + "', it should be defined using 'type.postProcessSnapshot(fn)' instead"); - var action2 = actions[name]; - // apply hook composition - var baseAction = self[name]; - if (name in Hook && baseAction) { - var specializedAction_1 = action2; - action2 = function () { - baseAction.apply(null, arguments); - specializedAction_1.apply(null, arguments); - }; - } - // the goal of this is to make sure actions using "this" can call themselves, - // while still allowing the middlewares to register them - var middlewares = action2.$mst_middleware; // make sure middlewares are not lost - var boundAction = action2.bind(actions); - boundAction.$mst_middleware = middlewares; - var actionInvoker = createActionInvoker(self, name, boundAction); - actions[name] = actionInvoker; - (addHiddenFinalProp )(self, name, actionInvoker); - }); - } - }); - Object.defineProperty(ModelType.prototype, "volatile", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - if (typeof fn !== "function") { - throw fail$1("You passed an " + typeof fn + " to volatile state as an argument, when function is expected"); - } - var stateInitializer = function (self) { - _this.instantiateVolatileState(self, fn(self)); - return self; - }; - return this.cloneAndEnhance({ initializers: [stateInitializer] }); - } - }); - Object.defineProperty(ModelType.prototype, "instantiateVolatileState", { - enumerable: false, - configurable: true, - writable: true, - value: function (self, state) { - // check views return - if (!isPlainObject(state)) - throw fail$1("volatile state initializer should return a plain object containing state"); - set(self, state); - } - }); - Object.defineProperty(ModelType.prototype, "extend", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - var initializer = function (self) { - var _a = fn(self), actions = _a.actions, views = _a.views, state = _a.state, rest = __rest(_a, ["actions", "views", "state"]); - for (var key in rest) - throw fail$1("The `extend` function should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '" + key + "'"); - if (state) - _this.instantiateVolatileState(self, state); - if (views) - _this.instantiateViews(self, views); - if (actions) - _this.instantiateActions(self, actions); - return self; - }; - return this.cloneAndEnhance({ initializers: [initializer] }); - } - }); - Object.defineProperty(ModelType.prototype, "views", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - var viewInitializer = function (self) { - _this.instantiateViews(self, fn(self)); - return self; - }; - return this.cloneAndEnhance({ initializers: [viewInitializer] }); - } - }); - Object.defineProperty(ModelType.prototype, "instantiateViews", { - enumerable: false, - configurable: true, - writable: true, - value: function (self, views) { - // check views return - if (!isPlainObject(views)) - throw fail$1("views initializer should return a plain object containing views"); - Object.keys(views).forEach(function (key) { - var _a; - // is this a computed property? - var descriptor = Object.getOwnPropertyDescriptor(views, key); - if ("get" in descriptor) { - apiDefineProperty(self, key, descriptor); - makeObservable(self, (_a = {}, _a[key] = computed, _a)); - } - else if (typeof descriptor.value === "function") { - (addHiddenFinalProp )(self, key, descriptor.value); - } - else { - throw fail$1("A view member should either be a function or getter based property"); - } - }); - } - }); - Object.defineProperty(ModelType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var value = isStateTreeNode(initialValue) - ? initialValue - : this.applySnapshotPreProcessor(initialValue); - return createObjectNode(this, parent, subpath, environment, value); - // Optimization: record all prop- view- and action names after first construction, and generate an optimal base class - // that pre-reserves all these fields for fast object-member lookups - } - }); - Object.defineProperty(ModelType.prototype, "initializeChildNodes", { - enumerable: false, - configurable: true, - writable: true, - value: function (objNode, initialSnapshot) { - if (initialSnapshot === void 0) { initialSnapshot = {}; } - var type = objNode.type; - var result = {}; - type.forAllProps(function (name, childType) { - result[name] = childType.instantiate(objNode, name, undefined, initialSnapshot[name]); - }); - return result; - } - }); - Object.defineProperty(ModelType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - return observable$1.object(childNodes, EMPTY_OBJECT, mobxShallow); - } - }); - Object.defineProperty(ModelType.prototype, "finalizeNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, instance) { - addHiddenFinalProp(instance, "toString", objectTypeToString); - this.forAllProps(function (name) { - interceptReads(instance, name, node.unbox); - }); - this.initializers.reduce(function (self, fn) { return fn(self); }, instance); - intercept(instance, this.willChange); - observe(instance, this.didChange); - } - }); - Object.defineProperty(ModelType.prototype, "willChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (chg) { - // TODO: mobx typings don't seem to take into account that newValue can be set even when removing a prop - var change = chg; - var node = getStateTreeNode(change.object); - var subpath = change.name; - node.assertWritable({ subpath: subpath }); - var childType = node.type.properties[subpath]; - // only properties are typed, state are stored as-is references - if (childType) { - typecheckInternal(childType, change.newValue); - change.newValue = childType.reconcile(node.getChildNode(subpath), change.newValue, node, subpath); - } - return change; - } - }); - Object.defineProperty(ModelType.prototype, "didChange", { - enumerable: false, - configurable: true, - writable: true, - value: function (chg) { - // TODO: mobx typings don't seem to take into account that newValue can be set even when removing a prop - var change = chg; - var childNode = getStateTreeNode(change.object); - var childType = childNode.type.properties[change.name]; - if (!childType) { - // don't emit patches for volatile state - return; - } - var oldChildValue = change.oldValue ? change.oldValue.snapshot : undefined; - childNode.emitPatch({ - op: "replace", - path: escapeJsonPath(change.name), - value: change.newValue.snapshot, - oldValue: oldChildValue - }, childNode); - } - }); - Object.defineProperty(ModelType.prototype, "getChildren", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var _this = this; - var res = []; - this.forAllProps(function (name) { - res.push(_this.getChildNode(node, name)); - }); - return res; - } - }); - Object.defineProperty(ModelType.prototype, "getChildNode", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, key) { - if (!(key in this.properties)) - throw fail$1("Not a value property: " + key); - var adm = getAdministration(node.storedValue, key); - var childNode = adm.raw(); - if (!childNode) - throw fail$1("Node not available for property " + key); - return childNode; - } - }); - Object.defineProperty(ModelType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, applyPostProcess) { - var _this = this; - if (applyPostProcess === void 0) { applyPostProcess = true; } - var res = {}; - this.forAllProps(function (name, type) { - getAtom(node.storedValue, name).reportObserved(); - res[name] = _this.getChildNode(node, name).snapshot; - }); - if (applyPostProcess) { - return this.applySnapshotPostProcessor(res); - } - return res; - } - }); - Object.defineProperty(ModelType.prototype, "processInitialSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (childNodes) { - var processed = {}; - Object.keys(childNodes).forEach(function (key) { - processed[key] = childNodes[key].getSnapshot(); - }); - return this.applySnapshotPostProcessor(processed); - } - }); - Object.defineProperty(ModelType.prototype, "applyPatchLocally", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath, patch) { - if (!(patch.op === "replace" || patch.op === "add")) { - throw fail$1("object does not support operation " + patch.op); - } - node.storedValue[subpath] = patch.value; - } - }); - Object.defineProperty(ModelType.prototype, "applySnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, snapshot) { - var preProcessedSnapshot = this.applySnapshotPreProcessor(snapshot); - typecheckInternal(this, preProcessedSnapshot); - this.forAllProps(function (name) { - node.storedValue[name] = preProcessedSnapshot[name]; - }); - } - }); - Object.defineProperty(ModelType.prototype, "applySnapshotPreProcessor", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - var processor = this.preProcessor; - return processor ? processor.call(null, snapshot) : snapshot; - } - }); - Object.defineProperty(ModelType.prototype, "applySnapshotPostProcessor", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - var postProcessor = this.postProcessor; - if (postProcessor) - return postProcessor.call(null, snapshot); - return snapshot; - } - }); - Object.defineProperty(ModelType.prototype, "getChildType", { - enumerable: false, - configurable: true, - writable: true, - value: function (propertyName) { - return this.properties[propertyName]; - } - }); - Object.defineProperty(ModelType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var _this = this; - var snapshot = this.applySnapshotPreProcessor(value); - if (!isPlainObject(snapshot)) { - return typeCheckFailure(context, snapshot, "Value is not a plain object"); - } - return flattenTypeErrors(this.propertyNames.map(function (key) { - return _this.properties[key].validate(snapshot[key], getContextForPath(context, key, _this.properties[key])); - })); - } - }); - Object.defineProperty(ModelType.prototype, "forAllProps", { - enumerable: false, - configurable: true, - writable: true, - value: function (fn) { - var _this = this; - this.propertyNames.forEach(function (key) { return fn(key, _this.properties[key]); }); - } - }); - Object.defineProperty(ModelType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var _this = this; - // optimization: cache - return ("{ " + - this.propertyNames - .map(function (key) { return key + ": " + _this.properties[key].describe(); }) - .join("; ") + - " }"); - } - }); - Object.defineProperty(ModelType.prototype, "getDefaultSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return EMPTY_OBJECT; - } - }); - Object.defineProperty(ModelType.prototype, "removeChild", { - enumerable: false, - configurable: true, - writable: true, - value: function (node, subpath) { - node.storedValue[subpath] = undefined; - } - }); - return ModelType; - }(ComplexType)); - ModelType.prototype.applySnapshot = action(ModelType.prototype.applySnapshot); - /** - * `types.model` - Creates a new model type by providing a name, properties, volatile state and actions. - * - * See the [model type](/concepts/trees#creating-models) description or the [getting started](intro/getting-started.md#getting-started-1) tutorial. - */ - function model() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var name = typeof args[0] === "string" ? args.shift() : "AnonymousModel"; - var properties = args.shift() || {}; - return new ModelType({ name: name, properties: properties }); - } - /** - * `types.compose` - Composes a new model from one or more existing model types. - * This method can be invoked in two forms: - * Given 2 or more model types, the types are composed into a new Type. - * Given first parameter as a string and 2 or more model types, - * the types are composed into a new Type with the given name - */ - function compose() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // TODO: just join the base type names if no name is provided - var hasTypename = typeof args[0] === "string"; - var typeName = hasTypename ? args[0] : "AnonymousModel"; - if (hasTypename) { - args.shift(); - } - return args - .reduce(function (prev, cur) { - return prev.cloneAndEnhance({ - name: prev.name + "_" + cur.name, - properties: cur.properties, - initializers: cur.initializers, - preProcessor: function (snapshot) { - return cur.applySnapshotPreProcessor(prev.applySnapshotPreProcessor(snapshot)); - }, - postProcessor: function (snapshot) { - return cur.applySnapshotPostProcessor(prev.applySnapshotPostProcessor(snapshot)); - } - }); - }) - .named(typeName); - } - /** - * Returns if a given value represents a model type. - * - * @param type - * @returns - */ - function isModelType(type) { - return isType(type) && (type.flags & TypeFlags.Object) > 0; - } - - // TODO: implement CoreType using types.custom ? - /** - * @internal - * @hidden - */ - var CoreType = /** @class */ (function (_super) { - __extends$1(CoreType, _super); - function CoreType(name, flags, checker, initializer) { - if (initializer === void 0) { initializer = identity$2; } - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: flags - }); - Object.defineProperty(_this, "checker", { - enumerable: true, - configurable: true, - writable: true, - value: checker - }); - Object.defineProperty(_this, "initializer", { - enumerable: true, - configurable: true, - writable: true, - value: initializer - }); - _this.flags = flags; - return _this; - } - Object.defineProperty(CoreType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.name; - } - }); - Object.defineProperty(CoreType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - return createScalarNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(CoreType.prototype, "createNewInstance", { - enumerable: false, - configurable: true, - writable: true, - value: function (snapshot) { - return this.initializer(snapshot); - } - }); - Object.defineProperty(CoreType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (isPrimitive(value) && this.checker(value)) { - return typeCheckSuccess(); - } - var typeName = this.name === "Date" ? "Date or a unix milliseconds timestamp" : this.name; - return typeCheckFailure(context, value, "Value is not a " + typeName); - } - }); - return CoreType; - }(SimpleType)); - /** - * `types.string` - Creates a type that can only contain a string value. - * This type is used for string values by default - * - * Example: - * ```ts - * const Person = types.model({ - * firstName: types.string, - * lastName: "Doe" - * }) - * ``` - */ - // tslint:disable-next-line:variable-name - var string = new CoreType("string", TypeFlags.String, function (v) { return typeof v === "string"; }); - /** - * `types.number` - Creates a type that can only contain a numeric value. - * This type is used for numeric values by default - * - * Example: - * ```ts - * const Vector = types.model({ - * x: types.number, - * y: 1.5 - * }) - * ``` - */ - // tslint:disable-next-line:variable-name - var number = new CoreType("number", TypeFlags.Number, function (v) { return typeof v === "number"; }); - /** - * `types.integer` - Creates a type that can only contain an integer value. - * This type is used for integer values by default - * - * Example: - * ```ts - * const Size = types.model({ - * width: types.integer, - * height: 10 - * }) - * ``` - */ - // tslint:disable-next-line:variable-name - var integer = new CoreType("integer", TypeFlags.Integer, function (v) { return isInteger(v); }); - /** - * `types.boolean` - Creates a type that can only contain a boolean value. - * This type is used for boolean values by default - * - * Example: - * ```ts - * const Thing = types.model({ - * isCool: types.boolean, - * isAwesome: false - * }) - * ``` - */ - // tslint:disable-next-line:variable-name - var boolean = new CoreType("boolean", TypeFlags.Boolean, function (v) { return typeof v === "boolean"; }); - /** - * `types.null` - The type of the value `null` - */ - var nullType = new CoreType("null", TypeFlags.Null, function (v) { return v === null; }); - /** - * `types.undefined` - The type of the value `undefined` - */ - var undefinedType = new CoreType("undefined", TypeFlags.Undefined, function (v) { return v === undefined; }); - var _DatePrimitive = new CoreType("Date", TypeFlags.Date, function (v) { return typeof v === "number" || v instanceof Date; }, function (v) { return (v instanceof Date ? v : new Date(v)); }); - _DatePrimitive.getSnapshot = function (node) { - return node.storedValue.getTime(); - }; - /** - * `types.Date` - Creates a type that can only contain a javascript Date value. - * - * Example: - * ```ts - * const LogLine = types.model({ - * timestamp: types.Date, - * }) - * - * LogLine.create({ timestamp: new Date() }) - * ``` - */ - var DatePrimitive = _DatePrimitive; - /** - * @internal - * @hidden - */ - function getPrimitiveFactoryFromValue(value) { - switch (typeof value) { - case "string": - return string; - case "number": - return number; // In the future, isInteger(value) ? integer : number would be interesting, but would be too breaking for now - case "boolean": - return boolean; - case "object": - if (value instanceof Date) - return DatePrimitive; - } - throw fail$1("Cannot determine primitive type from value " + value); - } - /** - * Returns if a given value represents a primitive type. - * - * @param type - * @returns - */ - function isPrimitiveType(type) { - return (isType(type) && - (type.flags & - (TypeFlags.String | - TypeFlags.Number | - TypeFlags.Integer | - TypeFlags.Boolean | - TypeFlags.Date)) > - 0); - } - - /** - * @internal - * @hidden - */ - var Literal = /** @class */ (function (_super) { - __extends$1(Literal, _super); - function Literal(value) { - var _this = _super.call(this, JSON.stringify(value)) || this; - Object.defineProperty(_this, "value", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Literal - }); - _this.value = value; - return _this; - } - Object.defineProperty(Literal.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - return createScalarNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(Literal.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return JSON.stringify(this.value); - } - }); - Object.defineProperty(Literal.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (isPrimitive(value) && value === this.value) { - return typeCheckSuccess(); - } - return typeCheckFailure(context, value, "Value is not a literal " + JSON.stringify(this.value)); - } - }); - return Literal; - }(SimpleType)); - /** - * `types.literal` - The literal type will return a type that will match only the exact given type. - * The given value must be a primitive, in order to be serialized to a snapshot correctly. - * You can use literal to match exact strings for example the exact male or female string. - * - * Example: - * ```ts - * const Person = types.model({ - * name: types.string, - * gender: types.union(types.literal('male'), types.literal('female')) - * }) - * ``` - * - * @param value The value to use in the strict equal check - * @returns - */ - function literal(value) { - return new Literal(value); - } - - var Refinement = /** @class */ (function (_super) { - __extends$1(Refinement, _super); - function Refinement(name, _subtype, _predicate, _message) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_subtype", { - enumerable: true, - configurable: true, - writable: true, - value: _subtype - }); - Object.defineProperty(_this, "_predicate", { - enumerable: true, - configurable: true, - writable: true, - value: _predicate - }); - Object.defineProperty(_this, "_message", { - enumerable: true, - configurable: true, - writable: true, - value: _message - }); - return _this; - } - Object.defineProperty(Refinement.prototype, "flags", { - get: function () { - return this._subtype.flags | TypeFlags.Refinement; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Refinement.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.name; - } - }); - Object.defineProperty(Refinement.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - // create the child type - return this._subtype.instantiate(parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(Refinement.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this._subtype.isAssignableFrom(type); - } - }); - Object.defineProperty(Refinement.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var subtypeErrors = this._subtype.validate(value, context); - if (subtypeErrors.length > 0) - return subtypeErrors; - var snapshot = isStateTreeNode(value) ? getStateTreeNode(value).snapshot : value; - if (!this._predicate(snapshot)) { - return typeCheckFailure(context, value, this._message(value)); - } - return typeCheckSuccess(); - } - }); - Object.defineProperty(Refinement.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - return this._subtype.reconcile(current, newValue, parent, subpath); - } - }); - Object.defineProperty(Refinement.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subtype; - } - }); - return Refinement; - }(BaseType)); - /** - * `types.refinement` - Creates a type that is more specific than the base type, e.g. `types.refinement(types.string, value => value.length > 5)` to create a type of strings that can only be longer then 5. - * - * @param name - * @param type - * @param predicate - * @returns - */ - function refinement() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var name = typeof args[0] === "string" ? args.shift() : isType(args[0]) ? args[0].name : null; - var type = args[0]; - var predicate = args[1]; - var message = args[2] - ? args[2] - : function (v) { return "Value does not respect the refinement predicate"; }; - return new Refinement(name, type, predicate, message); - } - - /** - * `types.enumeration` - Can be used to create an string based enumeration. - * (note: this methods is just sugar for a union of string literals) - * - * Example: - * ```ts - * const TrafficLight = types.model({ - * color: types.enumeration("Color", ["Red", "Orange", "Green"]) - * }) - * ``` - * - * @param name descriptive name of the enumeration (optional) - * @param options possible values this enumeration can have - * @returns - */ - function enumeration(name, options) { - var realOptions = typeof name === "string" ? options : name; - var type = union.apply(void 0, __spread(realOptions.map(function (option) { return literal("" + option); }))); - if (typeof name === "string") - type.name = name; - return type; - } - - /** - * @internal - * @hidden - */ - var Union = /** @class */ (function (_super) { - __extends$1(Union, _super); - function Union(name, _types, options) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_types", { - enumerable: true, - configurable: true, - writable: true, - value: _types - }); - Object.defineProperty(_this, "_dispatcher", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(_this, "_eager", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - options = __assign({ eager: true, dispatcher: undefined }, options); - _this._dispatcher = options.dispatcher; - if (!options.eager) - _this._eager = false; - return _this; - } - Object.defineProperty(Union.prototype, "flags", { - get: function () { - var result = TypeFlags.Union; - this._types.forEach(function (type) { - result |= type.flags; - }); - return result; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Union.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this._types.some(function (subType) { return subType.isAssignableFrom(type); }); - } - }); - Object.defineProperty(Union.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "(" + this._types.map(function (factory) { return factory.describe(); }).join(" | ") + ")"; - } - }); - Object.defineProperty(Union.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var type = this.determineType(initialValue, undefined); - if (!type) - throw fail$1("No matching type for union " + this.describe()); // can happen in prod builds - return type.instantiate(parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(Union.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - var type = this.determineType(newValue, current.type); - if (!type) - throw fail$1("No matching type for union " + this.describe()); // can happen in prod builds - return type.reconcile(current, newValue, parent, subpath); - } - }); - Object.defineProperty(Union.prototype, "determineType", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, reconcileCurrentType) { - // try the dispatcher, if defined - if (this._dispatcher) { - return this._dispatcher(value); - } - // find the most accomodating type - // if we are using reconciliation try the current node type first (fix for #1045) - if (reconcileCurrentType) { - if (reconcileCurrentType.is(value)) { - return reconcileCurrentType; - } - return this._types - .filter(function (t) { return t !== reconcileCurrentType; }) - .find(function (type) { return type.is(value); }); - } - else { - return this._types.find(function (type) { return type.is(value); }); - } - } - }); - Object.defineProperty(Union.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (this._dispatcher) { - return this._dispatcher(value).validate(value, context); - } - var allErrors = []; - var applicableTypes = 0; - for (var i = 0; i < this._types.length; i++) { - var type = this._types[i]; - var errors = type.validate(value, context); - if (errors.length === 0) { - if (this._eager) - return typeCheckSuccess(); - else - applicableTypes++; - } - else { - allErrors.push(errors); - } - } - if (applicableTypes === 1) - return typeCheckSuccess(); - return typeCheckFailure(context, value, "No type is applicable for the union").concat(flattenTypeErrors(allErrors)); - } - }); - Object.defineProperty(Union.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._types; - } - }); - return Union; - }(BaseType)); - /** - * `types.union` - Create a union of multiple types. If the correct type cannot be inferred unambiguously from a snapshot, provide a dispatcher function of the form `(snapshot) => Type`. - * - * @param optionsOrType - * @param otherTypes - * @returns - */ - function union(optionsOrType) { - var otherTypes = []; - for (var _i = 1; _i < arguments.length; _i++) { - otherTypes[_i - 1] = arguments[_i]; - } - var options = isType(optionsOrType) ? undefined : optionsOrType; - var types = isType(optionsOrType) ? __spread([optionsOrType], otherTypes) : otherTypes; - var name = "(" + types.map(function (type) { return type.name; }).join(" | ") + ")"; - return new Union(name, types, options); - } - - /** - * @hidden - * @internal - */ - var OptionalValue = /** @class */ (function (_super) { - __extends$1(OptionalValue, _super); - function OptionalValue(_subtype, _defaultValue, optionalValues) { - var _this = _super.call(this, _subtype.name) || this; - Object.defineProperty(_this, "_subtype", { - enumerable: true, - configurable: true, - writable: true, - value: _subtype - }); - Object.defineProperty(_this, "_defaultValue", { - enumerable: true, - configurable: true, - writable: true, - value: _defaultValue - }); - Object.defineProperty(_this, "optionalValues", { - enumerable: true, - configurable: true, - writable: true, - value: optionalValues - }); - return _this; - } - Object.defineProperty(OptionalValue.prototype, "flags", { - get: function () { - return this._subtype.flags | TypeFlags.Optional; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(OptionalValue.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subtype.describe() + "?"; - } - }); - Object.defineProperty(OptionalValue.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - if (this.optionalValues.indexOf(initialValue) >= 0) { - var defaultInstanceOrSnapshot = this.getDefaultInstanceOrSnapshot(); - return this._subtype.instantiate(parent, subpath, environment, defaultInstanceOrSnapshot); - } - return this._subtype.instantiate(parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(OptionalValue.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - return this._subtype.reconcile(current, this.optionalValues.indexOf(newValue) < 0 && this._subtype.is(newValue) - ? newValue - : this.getDefaultInstanceOrSnapshot(), parent, subpath); - } - }); - Object.defineProperty(OptionalValue.prototype, "getDefaultInstanceOrSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var defaultInstanceOrSnapshot = typeof this._defaultValue === "function" - ? this._defaultValue() - : this._defaultValue; - // while static values are already snapshots and checked on types.optional - // generator functions must always be rechecked just in case - if (typeof this._defaultValue === "function") { - typecheckInternal(this, defaultInstanceOrSnapshot); - } - return defaultInstanceOrSnapshot; - } - }); - Object.defineProperty(OptionalValue.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - // defaulted values can be skipped - if (this.optionalValues.indexOf(value) >= 0) { - return typeCheckSuccess(); - } - // bounce validation to the sub-type - return this._subtype.validate(value, context); - } - }); - Object.defineProperty(OptionalValue.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this._subtype.isAssignableFrom(type); - } - }); - Object.defineProperty(OptionalValue.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this._subtype; - } - }); - return OptionalValue; - }(BaseType)); - function checkOptionalPreconditions(type, defaultValueOrFunction) { - // make sure we never pass direct instances - if (typeof defaultValueOrFunction !== "function" && isStateTreeNode(defaultValueOrFunction)) { - throw fail$1("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead"); - } - } - /** - * `types.optional` - Can be used to create a property with a default value. - * - * Depending on the third argument (`optionalValues`) there are two ways of operation: - * - If the argument is not provided, then if a value is not provided in the snapshot (`undefined` or missing), - * it will default to the provided `defaultValue` - * - If the argument is provided, then if the value in the snapshot matches one of the optional values inside the array then it will - * default to the provided `defaultValue`. Additionally, if one of the optional values inside the array is `undefined` then a missing - * property is also valid. - * - * Note that it is also possible to include values of the same type as the intended subtype as optional values, - * in this case the optional value will be transformed into the `defaultValue` (e.g. `types.optional(types.string, "unnamed", [undefined, ""])` - * will transform the snapshot values `undefined` (and therefore missing) and empty strings into the string `"unnamed"` when it gets - * instantiated). - * - * If `defaultValue` is a function, the function will be invoked for every new instance. - * Applying a snapshot in which the optional value is one of the optional values (or `undefined`/_not_ present if none are provided) causes the - * value to be reset. - * - * Example: - * ```ts - * const Todo = types.model({ - * title: types.string, - * subtitle1: types.optional(types.string, "", [null]), - * subtitle2: types.optional(types.string, "", [null, undefined]), - * done: types.optional(types.boolean, false), - * created: types.optional(types.Date, () => new Date()), - * }) - * - * // if done is missing / undefined it will become false - * // if created is missing / undefined it will get a freshly generated timestamp - * // if subtitle1 is null it will default to "", but it cannot be missing or undefined - * // if subtitle2 is null or undefined it will default to ""; since it can be undefined it can also be missing - * const todo = Todo.create({ title: "Get coffee", subtitle1: null }) - * ``` - * - * @param type - * @param defaultValueOrFunction - * @param optionalValues an optional array with zero or more primitive values (string, number, boolean, null or undefined) - * that will be converted into the default. `[ undefined ]` is assumed when none is provided - * @returns - */ - function optional(type, defaultValueOrFunction, optionalValues) { - checkOptionalPreconditions(type, defaultValueOrFunction); - return new OptionalValue(type, defaultValueOrFunction, optionalValues ? optionalValues : undefinedAsOptionalValues); - } - var undefinedAsOptionalValues = [undefined]; - - var optionalUndefinedType = optional(undefinedType, undefined); - var optionalNullType = optional(nullType, null); - /** - * `types.maybe` - Maybe will make a type nullable, and also optional. - * The value `undefined` will be used to represent nullability. - * - * @param type - * @returns - */ - function maybe(type) { - return union(type, optionalUndefinedType); - } - /** - * `types.maybeNull` - Maybe will make a type nullable, and also optional. - * The value `null` will be used to represent no value. - * - * @param type - * @returns - */ - function maybeNull(type) { - return union(type, optionalNullType); - } - - var Late = /** @class */ (function (_super) { - __extends$1(Late, _super); - function Late(name, _definition) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "_definition", { - enumerable: true, - configurable: true, - writable: true, - value: _definition - }); - Object.defineProperty(_this, "_subType", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - return _this; - } - Object.defineProperty(Late.prototype, "flags", { - get: function () { - return (this._subType ? this._subType.flags : 0) | TypeFlags.Late; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Late.prototype, "getSubType", { - enumerable: false, - configurable: true, - writable: true, - value: function (mustSucceed) { - if (!this._subType) { - var t = undefined; - try { - t = this._definition(); - } - catch (e) { - if (e instanceof ReferenceError) - // can happen in strict ES5 code when a definition is self refering - t = undefined; - else - throw e; - } - if (mustSucceed && t === undefined) - throw fail$1("Late type seems to be used too early, the definition (still) returns undefined"); - if (t) { - this._subType = t; - } - } - return this._subType; - } - }); - Object.defineProperty(Late.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - return this.getSubType(true).instantiate(parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(Late.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - return this.getSubType(true).reconcile(current, newValue, parent, subpath); - } - }); - Object.defineProperty(Late.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var t = this.getSubType(false); - return t ? t.name : ""; - } - }); - Object.defineProperty(Late.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - var t = this.getSubType(false); - if (!t) { - // See #916; the variable the definition closure is pointing to wasn't defined yet, so can't be evaluted yet here - return typeCheckSuccess(); - } - return t.validate(value, context); - } - }); - Object.defineProperty(Late.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - var t = this.getSubType(false); - return t ? t.isAssignableFrom(type) : false; - } - }); - Object.defineProperty(Late.prototype, "getSubTypes", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - var subtype = this.getSubType(false); - return subtype ? subtype : cannotDetermineSubtype; - } - }); - return Late; - }(BaseType)); - /** - * `types.late` - Defines a type that gets implemented later. This is useful when you have to deal with circular dependencies. - * Please notice that when defining circular dependencies TypeScript isn't smart enough to inference them. - * - * Example: - * ```ts - * // TypeScript isn't smart enough to infer self referencing types. - * const Node = types.model({ - * children: types.array(types.late((): IAnyModelType => Node)) // then typecast each array element to Instance - * }) - * ``` - * - * @param name The name to use for the type that will be returned. - * @param type A function that returns the type that will be defined. - * @returns - */ - function late(nameOrType, maybeType) { - var name = typeof nameOrType === "string" ? nameOrType : "late(" + nameOrType.toString() + ")"; - var type = typeof nameOrType === "string" ? maybeType : nameOrType; - return new Late(name, type); - } - - /** - * @internal - * @hidden - */ - var Frozen = /** @class */ (function (_super) { - __extends$1(Frozen, _super); - function Frozen(subType) { - var _this = _super.call(this, subType ? "frozen(" + subType.name + ")" : "frozen") || this; - Object.defineProperty(_this, "subType", { - enumerable: true, - configurable: true, - writable: true, - value: subType - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Frozen - }); - return _this; - } - Object.defineProperty(Frozen.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return ""; - } - }); - Object.defineProperty(Frozen.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, value) { - // create the node - return createScalarNode(this, parent, subpath, environment, deepFreeze(value)); - } - }); - Object.defineProperty(Frozen.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (!isSerializable(value)) { - return typeCheckFailure(context, value, "Value is not serializable and cannot be frozen"); - } - if (this.subType) - return this.subType.validate(value, context); - return typeCheckSuccess(); - } - }); - return Frozen; - }(SimpleType)); - var untypedFrozenInstance = new Frozen(); - /** - * `types.frozen` - Frozen can be used to store any value that is serializable in itself (that is valid JSON). - * Frozen values need to be immutable or treated as if immutable. They need be serializable as well. - * Values stored in frozen will snapshotted as-is by MST, and internal changes will not be tracked. - * - * This is useful to store complex, but immutable values like vectors etc. It can form a powerful bridge to parts of your application that should be immutable, or that assume data to be immutable. - * - * Note: if you want to store free-form state that is mutable, or not serializeable, consider using volatile state instead. - * - * Frozen properties can be defined in three different ways - * 1. `types.frozen(SubType)` - provide a valid MST type and frozen will check if the provided data conforms the snapshot for that type - * 2. `types.frozen({ someDefaultValue: true})` - provide a primitive value, object or array, and MST will infer the type from that object, and also make it the default value for the field - * 3. `types.frozen()` - provide a typescript type, to help in strongly typing the field (design time only) - * - * Example: - * ```ts - * const GameCharacter = types.model({ - * name: string, - * location: types.frozen({ x: 0, y: 0}) - * }) - * - * const hero = GameCharacter.create({ - * name: "Mario", - * location: { x: 7, y: 4 } - * }) - * - * hero.location = { x: 10, y: 2 } // OK - * hero.location.x = 7 // Not ok! - * ``` - * - * ```ts - * type Point = { x: number, y: number } - * const Mouse = types.model({ - * loc: types.frozen() - * }) - * ``` - * - * @param defaultValueOrType - * @returns - */ - function frozen(arg) { - if (arguments.length === 0) - return untypedFrozenInstance; - else if (isType(arg)) - return new Frozen(arg); - else - return optional(untypedFrozenInstance, arg); - } - - function getInvalidationCause(hook) { - switch (hook) { - case Hook.beforeDestroy: - return "destroy"; - case Hook.beforeDetach: - return "detach"; - default: - return undefined; - } - } - var StoredReference = /** @class */ (function () { - function StoredReference(value, targetType) { - Object.defineProperty(this, "targetType", { - enumerable: true, - configurable: true, - writable: true, - value: targetType - }); - Object.defineProperty(this, "identifier", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "node", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "resolvedReference", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (isValidIdentifier(value)) { - this.identifier = value; - } - else if (isStateTreeNode(value)) { - var targetNode = getStateTreeNode(value); - if (!targetNode.identifierAttribute) - throw fail$1("Can only store references with a defined identifier attribute."); - var id = targetNode.unnormalizedIdentifier; - if (id === null || id === undefined) { - throw fail$1("Can only store references to tree nodes with a defined identifier."); - } - this.identifier = id; - } - else { - throw fail$1("Can only store references to tree nodes or identifiers, got: '" + value + "'"); - } - } - Object.defineProperty(StoredReference.prototype, "updateResolvedReference", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - var normalizedId = normalizeIdentifier(this.identifier); - var root = node.root; - var lastCacheModification = root.identifierCache.getLastCacheModificationPerId(normalizedId); - if (!this.resolvedReference || - this.resolvedReference.lastCacheModification !== lastCacheModification) { - var targetType = this.targetType; - // reference was initialized with the identifier of the target - var target = root.identifierCache.resolve(targetType, normalizedId); - if (!target) { - throw new InvalidReferenceError("[mobx-state-tree] Failed to resolve reference '" + this.identifier + "' to type '" + this.targetType.name + "' (from node: " + node.path + ")"); - } - this.resolvedReference = { - node: target, - lastCacheModification: lastCacheModification - }; - } - } - }); - Object.defineProperty(StoredReference.prototype, "resolvedValue", { - get: function () { - this.updateResolvedReference(this.node); - return this.resolvedReference.node.value; - }, - enumerable: false, - configurable: true - }); - return StoredReference; - }()); - /** - * @internal - * @hidden - */ - var InvalidReferenceError = /** @class */ (function (_super) { - __extends$1(InvalidReferenceError, _super); - function InvalidReferenceError(m) { - var _this = _super.call(this, m) || this; - Object.setPrototypeOf(_this, InvalidReferenceError.prototype); - return _this; - } - return InvalidReferenceError; - }(Error)); - /** - * @internal - * @hidden - */ - var BaseReferenceType = /** @class */ (function (_super) { - __extends$1(BaseReferenceType, _super); - function BaseReferenceType(targetType, onInvalidated) { - var _this = _super.call(this, "reference(" + targetType.name + ")") || this; - Object.defineProperty(_this, "targetType", { - enumerable: true, - configurable: true, - writable: true, - value: targetType - }); - Object.defineProperty(_this, "onInvalidated", { - enumerable: true, - configurable: true, - writable: true, - value: onInvalidated - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Reference - }); - return _this; - } - Object.defineProperty(BaseReferenceType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.name; - } - }); - Object.defineProperty(BaseReferenceType.prototype, "isAssignableFrom", { - enumerable: false, - configurable: true, - writable: true, - value: function (type) { - return this.targetType.isAssignableFrom(type); - } - }); - Object.defineProperty(BaseReferenceType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - return isValidIdentifier(value) - ? typeCheckSuccess() - : typeCheckFailure(context, value, "Value is not a valid identifier, which is a string or a number"); - } - }); - Object.defineProperty(BaseReferenceType.prototype, "fireInvalidated", { - enumerable: false, - configurable: true, - writable: true, - value: function (cause, storedRefNode, referenceId, refTargetNode) { - // to actually invalidate a reference we need an alive parent, - // since it is a scalar value (immutable-ish) and we need to change it - // from the parent - var storedRefParentNode = storedRefNode.parent; - if (!storedRefParentNode || !storedRefParentNode.isAlive) { - return; - } - var storedRefParentValue = storedRefParentNode.storedValue; - if (!storedRefParentValue) { - return; - } - this.onInvalidated({ - cause: cause, - parent: storedRefParentValue, - invalidTarget: refTargetNode ? refTargetNode.storedValue : undefined, - invalidId: referenceId, - replaceRef: function (newRef) { - applyPatch(storedRefNode.root.storedValue, { - op: "replace", - value: newRef, - path: storedRefNode.path - }); - }, - removeRef: function () { - if (isModelType(storedRefParentNode.type)) { - this.replaceRef(undefined); - } - else { - applyPatch(storedRefNode.root.storedValue, { - op: "remove", - path: storedRefNode.path - }); - } - } - }); - } - }); - Object.defineProperty(BaseReferenceType.prototype, "addTargetNodeWatcher", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode, referenceId) { - var _this = this; - // this will make sure the target node becomes created - var refTargetValue = this.getValue(storedRefNode); - if (!refTargetValue) { - return undefined; - } - var refTargetNode = getStateTreeNode(refTargetValue); - var hookHandler = function (_, refTargetNodeHook) { - var cause = getInvalidationCause(refTargetNodeHook); - if (!cause) { - return; - } - _this.fireInvalidated(cause, storedRefNode, referenceId, refTargetNode); - }; - var refTargetDetachHookDisposer = refTargetNode.registerHook(Hook.beforeDetach, hookHandler); - var refTargetDestroyHookDisposer = refTargetNode.registerHook(Hook.beforeDestroy, hookHandler); - return function () { - refTargetDetachHookDisposer(); - refTargetDestroyHookDisposer(); - }; - } - }); - Object.defineProperty(BaseReferenceType.prototype, "watchTargetNodeForInvalidations", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode, identifier, customGetSet) { - var _this = this; - if (!this.onInvalidated) { - return; - } - var onRefTargetDestroyedHookDisposer; - // get rid of the watcher hook when the stored ref node is destroyed - // detached is ignored since scalar nodes (where the reference resides) cannot be detached - storedRefNode.registerHook(Hook.beforeDestroy, function () { - if (onRefTargetDestroyedHookDisposer) { - onRefTargetDestroyedHookDisposer(); - } - }); - var startWatching = function (sync) { - // re-create hook in case the stored ref gets reattached - if (onRefTargetDestroyedHookDisposer) { - onRefTargetDestroyedHookDisposer(); - } - // make sure the target node is actually there and initialized - var storedRefParentNode = storedRefNode.parent; - var storedRefParentValue = storedRefParentNode && storedRefParentNode.storedValue; - if (storedRefParentNode && storedRefParentNode.isAlive && storedRefParentValue) { - var refTargetNodeExists = void 0; - if (customGetSet) { - refTargetNodeExists = !!customGetSet.get(identifier, storedRefParentValue); - } - else { - refTargetNodeExists = storedRefNode.root.identifierCache.has(_this.targetType, normalizeIdentifier(identifier)); - } - if (!refTargetNodeExists) { - // we cannot change the reference in sync mode - // since we are in the middle of a reconciliation/instantiation and the change would be overwritten - // for those cases just let the wrong reference be assigned and fail upon usage - // (like current references do) - // this means that effectively this code will only run when it is created from a snapshot - if (!sync) { - _this.fireInvalidated("invalidSnapshotReference", storedRefNode, identifier, null); - } - } - else { - onRefTargetDestroyedHookDisposer = _this.addTargetNodeWatcher(storedRefNode, identifier); - } - } - }; - if (storedRefNode.state === NodeLifeCycle.FINALIZED) { - // already attached, so the whole tree is ready - startWatching(true); - } - else { - if (!storedRefNode.isRoot) { - // start watching once the whole tree is ready - storedRefNode.root.registerHook(Hook.afterCreationFinalization, function () { - // make sure to attach it so it can start listening - if (storedRefNode.parent) { - storedRefNode.parent.createObservableInstanceIfNeeded(); - } - }); - } - // start watching once the node is attached somewhere / parent changes - storedRefNode.registerHook(Hook.afterAttach, function () { - startWatching(false); - }); - } - } - }); - return BaseReferenceType; - }(SimpleType)); - /** - * @internal - * @hidden - */ - var IdentifierReferenceType = /** @class */ (function (_super) { - __extends$1(IdentifierReferenceType, _super); - function IdentifierReferenceType(targetType, onInvalidated) { - return _super.call(this, targetType, onInvalidated) || this; - } - Object.defineProperty(IdentifierReferenceType.prototype, "getValue", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode) { - if (!storedRefNode.isAlive) - return undefined; - var storedRef = storedRefNode.storedValue; - return storedRef.resolvedValue; - } - }); - Object.defineProperty(IdentifierReferenceType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode) { - var ref = storedRefNode.storedValue; - return ref.identifier; - } - }); - Object.defineProperty(IdentifierReferenceType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var identifier = isStateTreeNode(initialValue) - ? getIdentifier(initialValue) - : initialValue; - var storedRef = new StoredReference(initialValue, this.targetType); - var storedRefNode = createScalarNode(this, parent, subpath, environment, storedRef); - storedRef.node = storedRefNode; - this.watchTargetNodeForInvalidations(storedRefNode, identifier, undefined); - return storedRefNode; - } - }); - Object.defineProperty(IdentifierReferenceType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - if (!current.isDetaching && current.type === this) { - var compareByValue = isStateTreeNode(newValue); - var ref = current.storedValue; - if ((!compareByValue && ref.identifier === newValue) || - (compareByValue && ref.resolvedValue === newValue)) { - current.setParent(parent, subpath); - return current; - } - } - var newNode = this.instantiate(parent, subpath, undefined, newValue); - current.die(); // noop if detaching - return newNode; - } - }); - return IdentifierReferenceType; - }(BaseReferenceType)); - /** - * @internal - * @hidden - */ - var CustomReferenceType = /** @class */ (function (_super) { - __extends$1(CustomReferenceType, _super); - function CustomReferenceType(targetType, options, onInvalidated) { - var _this = _super.call(this, targetType, onInvalidated) || this; - Object.defineProperty(_this, "options", { - enumerable: true, - configurable: true, - writable: true, - value: options - }); - return _this; - } - Object.defineProperty(CustomReferenceType.prototype, "getValue", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode) { - if (!storedRefNode.isAlive) - return undefined; - var referencedNode = this.options.get(storedRefNode.storedValue, storedRefNode.parent ? storedRefNode.parent.storedValue : null); - return referencedNode; - } - }); - Object.defineProperty(CustomReferenceType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (storedRefNode) { - return storedRefNode.storedValue; - } - }); - Object.defineProperty(CustomReferenceType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, newValue) { - var identifier = isStateTreeNode(newValue) - ? this.options.set(newValue, parent ? parent.storedValue : null) - : newValue; - var storedRefNode = createScalarNode(this, parent, subpath, environment, identifier); - this.watchTargetNodeForInvalidations(storedRefNode, identifier, this.options); - return storedRefNode; - } - }); - Object.defineProperty(CustomReferenceType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - var newIdentifier = isStateTreeNode(newValue) - ? this.options.set(newValue, current ? current.storedValue : null) - : newValue; - if (!current.isDetaching && - current.type === this && - current.storedValue === newIdentifier) { - current.setParent(parent, subpath); - return current; - } - var newNode = this.instantiate(parent, subpath, undefined, newIdentifier); - current.die(); // noop if detaching - return newNode; - } - }); - return CustomReferenceType; - }(BaseReferenceType)); - /** - * `types.reference` - Creates a reference to another type, which should have defined an identifier. - * See also the [reference and identifiers](https://github.com/mobxjs/mobx-state-tree#references-and-identifiers) section. - */ - function reference(subType, options) { - var getSetOptions = options ? options : undefined; - var onInvalidated = options - ? options.onInvalidated - : undefined; - if (getSetOptions && (getSetOptions.get || getSetOptions.set)) { - return new CustomReferenceType(subType, { - get: getSetOptions.get, - set: getSetOptions.set - }, onInvalidated); - } - else { - return new IdentifierReferenceType(subType, onInvalidated); - } - } - /** - * `types.safeReference` - A safe reference is like a standard reference, except that it accepts the undefined value by default - * and automatically sets itself to undefined (when the parent is a model) / removes itself from arrays and maps - * when the reference it is pointing to gets detached/destroyed. - * - * The optional options parameter object accepts a parameter named `acceptsUndefined`, which is set to true by default, so it is suitable - * for model properties. - * When used inside collections (arrays/maps), it is recommended to set this option to false so it can't take undefined as value, - * which is usually the desired in those cases. - * Additionally, the optional options parameter object accepts a parameter named `onInvalidated`, which will be called when the reference target node that the reference is pointing to is about to be detached/destroyed - * - * Strictly speaking it is a `types.maybe(types.reference(X))` (when `acceptsUndefined` is set to true, the default) and - * `types.reference(X)` (when `acceptsUndefined` is set to false), both of them with a customized `onInvalidated` option. - * - * @param subType - * @param options - * @returns - */ - function safeReference(subType, options) { - var refType = reference(subType, __assign(__assign({}, options), { onInvalidated: function (ev) { - if (options && options.onInvalidated) { - options.onInvalidated(ev); - } - ev.removeRef(); - } })); - if (options && options.acceptsUndefined === false) { - return refType; - } - else { - return maybe(refType); - } - } - - var BaseIdentifierType = /** @class */ (function (_super) { - __extends$1(BaseIdentifierType, _super); - function BaseIdentifierType(name, validType) { - var _this = _super.call(this, name) || this; - Object.defineProperty(_this, "validType", { - enumerable: true, - configurable: true, - writable: true, - value: validType - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Identifier - }); - return _this; - } - Object.defineProperty(BaseIdentifierType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - if (!parent || !(parent.type instanceof ModelType)) - throw fail$1("Identifier types can only be instantiated as direct child of a model type"); - return createScalarNode(this, parent, subpath, environment, initialValue); - } - }); - Object.defineProperty(BaseIdentifierType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, newValue, parent, subpath) { - // we don't consider detaching here since identifier are scalar nodes, and scalar nodes cannot be detached - if (current.storedValue !== newValue) - throw fail$1("Tried to change identifier from '" + current.storedValue + "' to '" + newValue + "'. Changing identifiers is not allowed."); - current.setParent(parent, subpath); - return current; - } - }); - Object.defineProperty(BaseIdentifierType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (typeof value !== this.validType) { - return typeCheckFailure(context, value, "Value is not a valid " + this.describe() + ", expected a " + this.validType); - } - return typeCheckSuccess(); - } - }); - return BaseIdentifierType; - }(SimpleType)); - /** - * @internal - * @hidden - */ - var IdentifierType = /** @class */ (function (_super) { - __extends$1(IdentifierType, _super); - function IdentifierType() { - var _this = _super.call(this, "identifier", "string") || this; - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Identifier - }); - return _this; - } - Object.defineProperty(IdentifierType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "identifier"; - } - }); - return IdentifierType; - }(BaseIdentifierType)); - /** - * @internal - * @hidden - */ - var IdentifierNumberType = /** @class */ (function (_super) { - __extends$1(IdentifierNumberType, _super); - function IdentifierNumberType() { - return _super.call(this, "identifierNumber", "number") || this; - } - Object.defineProperty(IdentifierNumberType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return node.storedValue; - } - }); - Object.defineProperty(IdentifierNumberType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return "identifierNumber"; - } - }); - return IdentifierNumberType; - }(BaseIdentifierType)); - /** - * `types.identifier` - Identifiers are used to make references, lifecycle events and reconciling works. - * Inside a state tree, for each type can exist only one instance for each given identifier. - * For example there couldn't be 2 instances of user with id 1. If you need more, consider using references. - * Identifier can be used only as type property of a model. - * This type accepts as parameter the value type of the identifier field that can be either string or number. - * - * Example: - * ```ts - * const Todo = types.model("Todo", { - * id: types.identifier, - * title: types.string - * }) - * ``` - * - * @returns - */ - var identifier = new IdentifierType(); - /** - * `types.identifierNumber` - Similar to `types.identifier`. This one will serialize from / to a number when applying snapshots - * - * Example: - * ```ts - * const Todo = types.model("Todo", { - * id: types.identifierNumber, - * title: types.string - * }) - * ``` - * - * @returns - */ - var identifierNumber = new IdentifierNumberType(); - /** - * @internal - * @hidden - */ - function normalizeIdentifier(id) { - return "" + id; - } - /** - * @internal - * @hidden - */ - function isValidIdentifier(id) { - return typeof id === "string" || typeof id === "number"; - } - - /** - * `types.custom` - Creates a custom type. Custom types can be used for arbitrary immutable values, that have a serializable representation. For example, to create your own Date representation, Decimal type etc. - * - * The signature of the options is: - * ```ts - * export interface CustomTypeOptions { - * // Friendly name - * name: string - * // given a serialized value and environment, how to turn it into the target type - * fromSnapshot(snapshot: S, env: any): T - * // return the serialization of the current value - * toSnapshot(value: T): S - * // if true, this is a converted value, if false, it's a snapshot - * isTargetType(value: T | S): value is T - * // a non empty string is assumed to be a validation error - * getValidationMessage?(snapshot: S): string - * } - * ``` - * - * Example: - * ```ts - * const DecimalPrimitive = types.custom({ - * name: "Decimal", - * fromSnapshot(value: string) { - * return new Decimal(value) - * }, - * toSnapshot(value: Decimal) { - * return value.toString() - * }, - * isTargetType(value: string | Decimal): boolean { - * return value instanceof Decimal - * }, - * getValidationMessage(value: string): string { - * if (/^-?\d+\.\d+$/.test(value)) return "" // OK - * return `'${value}' doesn't look like a valid decimal number` - * } - * }) - * - * const Wallet = types.model({ - * balance: DecimalPrimitive - * }) - * ``` - * - * @param options - * @returns - */ - function custom(options) { - return new CustomType(options); - } - /** - * @internal - * @hidden - */ - var CustomType = /** @class */ (function (_super) { - __extends$1(CustomType, _super); - function CustomType(options) { - var _this = _super.call(this, options.name) || this; - Object.defineProperty(_this, "options", { - enumerable: true, - configurable: true, - writable: true, - value: options - }); - Object.defineProperty(_this, "flags", { - enumerable: true, - configurable: true, - writable: true, - value: TypeFlags.Custom - }); - return _this; - } - Object.defineProperty(CustomType.prototype, "describe", { - enumerable: false, - configurable: true, - writable: true, - value: function () { - return this.name; - } - }); - Object.defineProperty(CustomType.prototype, "isValidSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (value, context) { - if (this.options.isTargetType(value)) - return typeCheckSuccess(); - var typeError = this.options.getValidationMessage(value); - if (typeError) { - return typeCheckFailure(context, value, "Invalid value for type '" + this.name + "': " + typeError); - } - return typeCheckSuccess(); - } - }); - Object.defineProperty(CustomType.prototype, "getSnapshot", { - enumerable: false, - configurable: true, - writable: true, - value: function (node) { - return this.options.toSnapshot(node.storedValue); - } - }); - Object.defineProperty(CustomType.prototype, "instantiate", { - enumerable: false, - configurable: true, - writable: true, - value: function (parent, subpath, environment, initialValue) { - var valueToStore = this.options.isTargetType(initialValue) - ? initialValue - : this.options.fromSnapshot(initialValue, parent && parent.root.environment); - return createScalarNode(this, parent, subpath, environment, valueToStore); - } - }); - Object.defineProperty(CustomType.prototype, "reconcile", { - enumerable: false, - configurable: true, - writable: true, - value: function (current, value, parent, subpath) { - var isSnapshot = !this.options.isTargetType(value); - // in theory customs use scalar nodes which cannot be detached, but still... - if (!current.isDetaching) { - var unchanged = current.type === this && - (isSnapshot ? value === current.snapshot : value === current.storedValue); - if (unchanged) { - current.setParent(parent, subpath); - return current; - } - } - var valueToStore = isSnapshot - ? this.options.fromSnapshot(value, parent.root.environment) - : value; - var newNode = this.instantiate(parent, subpath, undefined, valueToStore); - current.die(); // noop if detaching - return newNode; - } - }); - return CustomType; - }(SimpleType)); - - // we import the types to re-export them inside types. - var types = { - enumeration: enumeration, - model: model, - compose: compose, - custom: custom, - reference: reference, - safeReference: safeReference, - union: union, - optional: optional, - literal: literal, - maybe: maybe, - maybeNull: maybeNull, - refinement: refinement, - string: string, - boolean: boolean, - number: number, - integer: integer, - Date: DatePrimitive, - map: map$1, - array: array, - frozen: frozen, - identifier: identifier, - identifierNumber: identifierNumber, - late: late, - undefined: undefinedType, - null: nullType, - snapshotProcessor: snapshotProcessor - }; - - // Unique ID creation requires a high quality random # generator. In the browser we therefore - // require the crypto API and do not support built-in fallback to lower quality random number - // generators (like Math.random()). - var getRandomValues; - var rnds8 = new Uint8Array(16); - function rng() { - // lazy load so that environments that need to polyfill have a chance to do so - if (!getRandomValues) { - // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, - // find the complete implementation of crypto (msCrypto) on IE11. - getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); - - if (!getRandomValues) { - throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); - } - } - - return getRandomValues(rnds8); - } - - var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; - - function validate(uuid) { - return typeof uuid === 'string' && REGEX.test(uuid); - } - - /** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ - - var byteToHex = []; - - for (var i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); - } - - function stringify(arr) { - var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!validate(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; - } - - function parse(uuid) { - if (!validate(uuid)) { - throw TypeError('Invalid UUID'); - } - - var v; - var arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; - } - - function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - var bytes = []; - - for (var i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - - return bytes; - } - - var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; - var URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; - function v35 (name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } - - if (typeof namespace === 'string') { - namespace = parse(namespace); - } - - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - - - var bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - - return buf; - } - - return stringify(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL$1; - return generateUUID; - } - - function v4(options, buf, offset) { - options = options || {}; - var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - - return buf; - } - - return stringify(rnds); - } - - // Adapted from Chris Veness' SHA1 code at - // http://www.movable-type.co.uk/scripts/sha1.html - function f(s, x, y, z) { - switch (s) { - case 0: - return x & y ^ ~x & z; - - case 1: - return x ^ y ^ z; - - case 2: - return x & y ^ x & z ^ y & z; - - case 3: - return x ^ y ^ z; - } - } - - function ROTL(x, n) { - return x << n | x >>> 32 - n; - } - - function sha1(bytes) { - var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; - var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; - - if (typeof bytes === 'string') { - var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - - bytes = []; - - for (var i = 0; i < msg.length; ++i) { - bytes.push(msg.charCodeAt(i)); - } - } else if (!Array.isArray(bytes)) { - // Convert Array-like to Array - bytes = Array.prototype.slice.call(bytes); - } - - bytes.push(0x80); - var l = bytes.length / 4 + 2; - var N = Math.ceil(l / 16); - var M = new Array(N); - - for (var _i = 0; _i < N; ++_i) { - var arr = new Uint32Array(16); - - for (var j = 0; j < 16; ++j) { - arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; - } - - M[_i] = arr; - } - - M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); - M[N - 1][14] = Math.floor(M[N - 1][14]); - M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; - - for (var _i2 = 0; _i2 < N; ++_i2) { - var W = new Uint32Array(80); - - for (var t = 0; t < 16; ++t) { - W[t] = M[_i2][t]; - } - - for (var _t = 16; _t < 80; ++_t) { - W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); - } - - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - - for (var _t2 = 0; _t2 < 80; ++_t2) { - var s = Math.floor(_t2 / 20); - var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0; - e = d; - d = c; - c = ROTL(b, 30) >>> 0; - b = a; - a = T; - } - - H[0] = H[0] + a >>> 0; - H[1] = H[1] + b >>> 0; - H[2] = H[2] + c >>> 0; - H[3] = H[3] + d >>> 0; - H[4] = H[4] + e >>> 0; - } - - return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; - } - - var v5 = v35('v5', 0x50, sha1); - - /** - * @license - * Copyright 2021 KonghaYao 江夏尧 - * SPDX-License-Identifier: Apache-2.0 - */ - function createProps({ spiderUUID, originData }) { - // 创建初始化的参数 - return { - uuid: v4(), - spiderUUID, // JSpider 的实例的 UUID - createdAt: new Date(), - errorMessage: '', - status: 'free', // 这个位置是为了让 Plugin 能识别的一个标识 - updatedAt: new Date(), - dataSlideUUID: spiderUUID, - dataSlide: [], - originData, - output: null, // 每个中间件传出的数据 - }; - } - - /** - * @license - * Copyright 2021 KonghaYao 江夏尧 - * SPDX-License-Identifier: Apache-2.0 - */ - const TaskState = types.enumeration('TaskState', ['free', 'pending', 'complete', 'error', 'destroyed']); - - const AutoType = { - anyType: types.custom({ - name: 'any', - fromSnapshot(value) { - return value; - }, - toSnapshot(value) { - return value; - }, - isTargetType() { - return true; - }, - getValidationMessage() { - return ''; - }, - }), - }; - - /** - * @license - * Copyright 2021 KonghaYao 江夏尧 - * SPDX-License-Identifier: Apache-2.0 - */ - - const TaskStore = types - .model({ - uuid: types.string, - spiderUUID: types.string, // JSpider 的实例的 UUID - dataSlide: types.array(types.string), // 更改为存储 UUID - dataSlideUUID: types.string, // 上一次完成的 UUID - createdAt: types.Date, - errorMessage: types.optional(types.string, ''), - status: TaskState, // 这个位置是为了让 Plugin 能识别的一个标识 - updatedAt: types.Date, - // 记录完成过的 uuid 的信息,只有在 StaticEvent.js 中才能更改 - originData: types.maybe(AutoType.anyType), - - // 每个中间件传出的数据 - output: types.maybe(AutoType.anyType), - }) - .actions((self) => { - return { - $backup() { - return getSnapshot(self); - }, - $import(backup) { - return applySnapshot(backup); - }, - - start() { - if (self.status === 'pending') throw new Error('Task 处在 pending 状态'); - self.dataSlide = []; - self.dataSlideUUID = ''; - self.status = 'pending'; - return self.output || self.originData; - }, - success(output, uuid) { - self.status = 'free'; - self.output = output; - this._addUUIDToDataSlide(uuid); - }, - complete(uuid) { - self.status = 'complete'; - this._addUUIDToDataSlide(uuid); - }, - error(err = '', uuid) { - self.status = 'error'; - self.errorMessage = err; - this._addUUIDToDataSlide(uuid); - }, - destroy() { - destroy(self); - }, - _addUUIDToDataSlide(uuid) { - if (uuid) { - self.dataSlide.push(uuid); - self.dataSlideUUID = uuid; - } - }, - }; - }); - function createTaskStore(model) { - return TaskStore.create(createProps(model)); - } - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - - function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function isFunction$1(x) { - return typeof x === 'function'; - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var _enable_super_gross_mode_that_will_cause_bad_things = false; - var config = { - Promise: undefined, - set useDeprecatedSynchronousErrorHandling(value) { - if (value) { - var error = /*@__PURE__*/ new Error(); - /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); - } - _enable_super_gross_mode_that_will_cause_bad_things = value; - }, - get useDeprecatedSynchronousErrorHandling() { - return _enable_super_gross_mode_that_will_cause_bad_things; - }, - }; - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function hostReportError(err) { - setTimeout(function () { throw err; }, 0); - } - - /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ - var empty = { - closed: true, - next: function (value) { }, - error: function (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - }, - complete: function () { } - }; - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var isArray$1 = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function isObject$1(x) { - return x !== null && typeof x === 'object'; - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { - function UnsubscriptionErrorImpl(errors) { - Error.call(this); - this.message = errors ? - errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; - this.name = 'UnsubscriptionError'; - this.errors = errors; - return this; - } - UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return UnsubscriptionErrorImpl; - })(); - var UnsubscriptionError = UnsubscriptionErrorImpl; - - /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ - var Subscription = /*@__PURE__*/ (function () { - function Subscription(unsubscribe) { - this.closed = false; - this._parentOrParents = null; - this._subscriptions = null; - if (unsubscribe) { - this._ctorUnsubscribe = true; - this._unsubscribe = unsubscribe; - } - } - Subscription.prototype.unsubscribe = function () { - var errors; - if (this.closed) { - return; - } - var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; - this.closed = true; - this._parentOrParents = null; - this._subscriptions = null; - if (_parentOrParents instanceof Subscription) { - _parentOrParents.remove(this); - } - else if (_parentOrParents !== null) { - for (var index = 0; index < _parentOrParents.length; ++index) { - var parent_1 = _parentOrParents[index]; - parent_1.remove(this); - } - } - if (isFunction$1(_unsubscribe)) { - if (_ctorUnsubscribe) { - this._unsubscribe = undefined; - } - try { - _unsubscribe.call(this); - } - catch (e) { - errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; - } - } - if (isArray$1(_subscriptions)) { - var index = -1; - var len = _subscriptions.length; - while (++index < len) { - var sub = _subscriptions[index]; - if (isObject$1(sub)) { - try { - sub.unsubscribe(); - } - catch (e) { - errors = errors || []; - if (e instanceof UnsubscriptionError) { - errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); - } - else { - errors.push(e); - } - } - } - } - } - if (errors) { - throw new UnsubscriptionError(errors); - } - }; - Subscription.prototype.add = function (teardown) { - var subscription = teardown; - if (!teardown) { - return Subscription.EMPTY; - } - switch (typeof teardown) { - case 'function': - subscription = new Subscription(teardown); - case 'object': - if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { - return subscription; - } - else if (this.closed) { - subscription.unsubscribe(); - return subscription; - } - else if (!(subscription instanceof Subscription)) { - var tmp = subscription; - subscription = new Subscription(); - subscription._subscriptions = [tmp]; - } - break; - default: { - throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); - } - } - var _parentOrParents = subscription._parentOrParents; - if (_parentOrParents === null) { - subscription._parentOrParents = this; - } - else if (_parentOrParents instanceof Subscription) { - if (_parentOrParents === this) { - return subscription; - } - subscription._parentOrParents = [_parentOrParents, this]; - } - else if (_parentOrParents.indexOf(this) === -1) { - _parentOrParents.push(this); - } - else { - return subscription; - } - var subscriptions = this._subscriptions; - if (subscriptions === null) { - this._subscriptions = [subscription]; - } - else { - subscriptions.push(subscription); - } - return subscription; - }; - Subscription.prototype.remove = function (subscription) { - var subscriptions = this._subscriptions; - if (subscriptions) { - var subscriptionIndex = subscriptions.indexOf(subscription); - if (subscriptionIndex !== -1) { - subscriptions.splice(subscriptionIndex, 1); - } - } - }; - Subscription.EMPTY = (function (empty) { - empty.closed = true; - return empty; - }(new Subscription())); - return Subscription; - }()); - function flattenUnsubscriptionErrors(errors) { - return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var rxSubscriber = /*@__PURE__*/ (function () { - return typeof Symbol === 'function' - ? /*@__PURE__*/ Symbol('rxSubscriber') - : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); - })(); - - /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ - var Subscriber = /*@__PURE__*/ (function (_super) { - __extends(Subscriber, _super); - function Subscriber(destinationOrNext, error, complete) { - var _this = _super.call(this) || this; - _this.syncErrorValue = null; - _this.syncErrorThrown = false; - _this.syncErrorThrowable = false; - _this.isStopped = false; - switch (arguments.length) { - case 0: - _this.destination = empty; - break; - case 1: - if (!destinationOrNext) { - _this.destination = empty; - break; - } - if (typeof destinationOrNext === 'object') { - if (destinationOrNext instanceof Subscriber) { - _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; - _this.destination = destinationOrNext; - destinationOrNext.add(_this); - } - else { - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext); - } - break; - } - default: - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); - break; - } - return _this; - } - Subscriber.prototype[rxSubscriber] = function () { return this; }; - Subscriber.create = function (next, error, complete) { - var subscriber = new Subscriber(next, error, complete); - subscriber.syncErrorThrowable = false; - return subscriber; - }; - Subscriber.prototype.next = function (value) { - if (!this.isStopped) { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (!this.isStopped) { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (!this.isStopped) { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - this.destination.error(err); - this.unsubscribe(); - }; - Subscriber.prototype._complete = function () { - this.destination.complete(); - this.unsubscribe(); - }; - Subscriber.prototype._unsubscribeAndRecycle = function () { - var _parentOrParents = this._parentOrParents; - this._parentOrParents = null; - this.unsubscribe(); - this.closed = false; - this.isStopped = false; - this._parentOrParents = _parentOrParents; - return this; - }; - return Subscriber; - }(Subscription)); - var SafeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SafeSubscriber, _super); - function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { - var _this = _super.call(this) || this; - _this._parentSubscriber = _parentSubscriber; - var next; - var context = _this; - if (isFunction$1(observerOrNext)) { - next = observerOrNext; - } - else if (observerOrNext) { - next = observerOrNext.next; - error = observerOrNext.error; - complete = observerOrNext.complete; - if (observerOrNext !== empty) { - context = Object.create(observerOrNext); - if (isFunction$1(context.unsubscribe)) { - _this.add(context.unsubscribe.bind(context)); - } - context.unsubscribe = _this.unsubscribe.bind(_this); - } - } - _this._context = context; - _this._next = next; - _this._error = error; - _this._complete = complete; - return _this; - } - SafeSubscriber.prototype.next = function (value) { - if (!this.isStopped && this._next) { - var _parentSubscriber = this._parentSubscriber; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._next, value); - } - else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; - if (this._error) { - if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._error, err); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, this._error, err); - this.unsubscribe(); - } - } - else if (!_parentSubscriber.syncErrorThrowable) { - this.unsubscribe(); - if (useDeprecatedSynchronousErrorHandling) { - throw err; - } - hostReportError(err); - } - else { - if (useDeprecatedSynchronousErrorHandling) { - _parentSubscriber.syncErrorValue = err; - _parentSubscriber.syncErrorThrown = true; - } - else { - hostReportError(err); - } - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.complete = function () { - var _this = this; - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - if (this._complete) { - var wrappedComplete = function () { return _this._complete.call(_this._context); }; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(wrappedComplete); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, wrappedComplete); - this.unsubscribe(); - } - } - else { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { - try { - fn.call(this._context, value); - } - catch (err) { - this.unsubscribe(); - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - } - }; - SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { - if (!config.useDeprecatedSynchronousErrorHandling) { - throw new Error('bad call'); - } - try { - fn.call(this._context, value); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - parent.syncErrorValue = err; - parent.syncErrorThrown = true; - return true; - } - else { - hostReportError(err); - return true; - } - } - return false; - }; - SafeSubscriber.prototype._unsubscribe = function () { - var _parentSubscriber = this._parentSubscriber; - this._context = null; - this._parentSubscriber = null; - _parentSubscriber.unsubscribe(); - }; - return SafeSubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ - function canReportError(observer) { - while (observer) { - var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; - if (closed_1 || isStopped) { - return false; - } - else if (destination && destination instanceof Subscriber) { - observer = destination; - } - else { - observer = null; - } - } - return true; - } - - /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ - function toSubscriber(nextOrObserver, error, complete) { - if (nextOrObserver) { - if (nextOrObserver instanceof Subscriber) { - return nextOrObserver; - } - if (nextOrObserver[rxSubscriber]) { - return nextOrObserver[rxSubscriber](); - } - } - if (!nextOrObserver && !error && !complete) { - return new Subscriber(empty); - } - return new Subscriber(nextOrObserver, error, complete); - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function identity$1(x) { - return x; - } - - /** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ - function pipe() { - var fns = []; - for (var _i = 0; _i < arguments.length; _i++) { - fns[_i] = arguments[_i]; - } - return pipeFromArray(fns); - } - function pipeFromArray(fns) { - if (fns.length === 0) { - return identity$1; - } - if (fns.length === 1) { - return fns[0]; - } - return function piped(input) { - return fns.reduce(function (prev, fn) { return fn(prev); }, input); - }; - } - - /** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ - var Observable = /*@__PURE__*/ (function () { - function Observable(subscribe) { - this._isScalar = false; - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; - }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var operator = this.operator; - var sink = toSubscriber(observerOrNext, error, complete); - if (operator) { - sink.add(operator.call(sink, this.source)); - } - else { - sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? - this._subscribe(sink) : - this._trySubscribe(sink)); - } - if (config.useDeprecatedSynchronousErrorHandling) { - if (sink.syncErrorThrowable) { - sink.syncErrorThrowable = false; - if (sink.syncErrorThrown) { - throw sink.syncErrorValue; - } - } - } - return sink; - }; - Observable.prototype._trySubscribe = function (sink) { - try { - return this._subscribe(sink); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - sink.syncErrorThrown = true; - sink.syncErrorValue = err; - } - if (canReportError(sink)) { - sink.error(err); - } - else { - console.warn(err); - } - } - }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscription; - subscription = _this.subscribe(function (value) { - try { - next(value); - } - catch (err) { - reject(err); - if (subscription) { - subscription.unsubscribe(); - } - } - }, reject, resolve); - }); - }; - Observable.prototype._subscribe = function (subscriber) { - var source = this.source; - return source && source.subscribe(subscriber); - }; - Observable.prototype[observable] = function () { - return this; - }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - if (operations.length === 0) { - return this; - } - return pipeFromArray(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); - }; - return Observable; - }()); - function getPromiseCtor(promiseCtor) { - if (!promiseCtor) { - promiseCtor = Promise; - } - if (!promiseCtor) { - throw new Error('no Promise impl found'); - } - return promiseCtor; - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { - function ObjectUnsubscribedErrorImpl() { - Error.call(this); - this.message = 'object unsubscribed'; - this.name = 'ObjectUnsubscribedError'; - return this; - } - ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return ObjectUnsubscribedErrorImpl; - })(); - var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; - - /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ - var SubjectSubscription = /*@__PURE__*/ (function (_super) { - __extends(SubjectSubscription, _super); - function SubjectSubscription(subject, subscriber) { - var _this = _super.call(this) || this; - _this.subject = subject; - _this.subscriber = subscriber; - _this.closed = false; - return _this; - } - SubjectSubscription.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.closed = true; - var subject = this.subject; - var observers = subject.observers; - this.subject = null; - if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { - return; - } - var subscriberIndex = observers.indexOf(this.subscriber); - if (subscriberIndex !== -1) { - observers.splice(subscriberIndex, 1); - } - }; - return SubjectSubscription; - }(Subscription)); - - /** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ - var SubjectSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SubjectSubscriber, _super); - function SubjectSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - return _this; - } - return SubjectSubscriber; - }(Subscriber)); - var Subject = /*@__PURE__*/ (function (_super) { - __extends(Subject, _super); - function Subject() { - var _this = _super.call(this) || this; - _this.observers = []; - _this.closed = false; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; - } - Subject.prototype[rxSubscriber] = function () { - return new SubjectSubscriber(this); - }; - Subject.prototype.lift = function (operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject.prototype.next = function (value) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - if (!this.isStopped) { - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].next(value); - } - } - }; - Subject.prototype.error = function (err) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.hasError = true; - this.thrownError = err; - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].error(err); - } - this.observers.length = 0; - }; - Subject.prototype.complete = function () { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].complete(); - } - this.observers.length = 0; - }; - Subject.prototype.unsubscribe = function () { - this.isStopped = true; - this.closed = true; - this.observers = null; - }; - Subject.prototype._trySubscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else { - return _super.prototype._trySubscribe.call(this, subscriber); - } - }; - Subject.prototype._subscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else if (this.hasError) { - subscriber.error(this.thrownError); - return Subscription.EMPTY; - } - else if (this.isStopped) { - subscriber.complete(); - return Subscription.EMPTY; - } - else { - this.observers.push(subscriber); - return new SubjectSubscription(this, subscriber); - } - }; - Subject.prototype.asObservable = function () { - var observable = new Observable(); - observable.source = this; - return observable; - }; - Subject.create = function (destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject; - }(Observable)); - var AnonymousSubject = /*@__PURE__*/ (function (_super) { - __extends(AnonymousSubject, _super); - function AnonymousSubject(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; - } - AnonymousSubject.prototype.next = function (value) { - var destination = this.destination; - if (destination && destination.next) { - destination.next(value); - } - }; - AnonymousSubject.prototype.error = function (err) { - var destination = this.destination; - if (destination && destination.error) { - this.destination.error(err); - } - }; - AnonymousSubject.prototype.complete = function () { - var destination = this.destination; - if (destination && destination.complete) { - this.destination.complete(); - } - }; - AnonymousSubject.prototype._subscribe = function (subscriber) { - var source = this.source; - if (source) { - return this.source.subscribe(subscriber); - } - else { - return Subscription.EMPTY; - } - }; - return AnonymousSubject; - }(Subject)); - - /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - function refCount() { - return function refCountOperatorFunction(source) { - return source.lift(new RefCountOperator(source)); - }; - } - var RefCountOperator = /*@__PURE__*/ (function () { - function RefCountOperator(connectable) { - this.connectable = connectable; - } - RefCountOperator.prototype.call = function (subscriber, source) { - var connectable = this.connectable; - connectable._refCount++; - var refCounter = new RefCountSubscriber(subscriber, connectable); - var subscription = source.subscribe(refCounter); - if (!refCounter.closed) { - refCounter.connection = connectable.connect(); - } - return subscription; - }; - return RefCountOperator; - }()); - var RefCountSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RefCountSubscriber, _super); - function RefCountSubscriber(destination, connectable) { - var _this = _super.call(this, destination) || this; - _this.connectable = connectable; - return _this; - } - RefCountSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (!connectable) { - this.connection = null; - return; - } - this.connectable = null; - var refCount = connectable._refCount; - if (refCount <= 0) { - this.connection = null; - return; - } - connectable._refCount = refCount - 1; - if (refCount > 1) { - this.connection = null; - return; - } - var connection = this.connection; - var sharedConnection = connectable._connection; - this.connection = null; - if (sharedConnection && (!connection || sharedConnection === connection)) { - sharedConnection.unsubscribe(); - } - }; - return RefCountSubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */ - var ConnectableObservable = /*@__PURE__*/ (function (_super) { - __extends(ConnectableObservable, _super); - function ConnectableObservable(source, subjectFactory) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subjectFactory = subjectFactory; - _this._refCount = 0; - _this._isComplete = false; - return _this; - } - ConnectableObservable.prototype._subscribe = function (subscriber) { - return this.getSubject().subscribe(subscriber); - }; - ConnectableObservable.prototype.getSubject = function () { - var subject = this._subject; - if (!subject || subject.isStopped) { - this._subject = this.subjectFactory(); - } - return this._subject; - }; - ConnectableObservable.prototype.connect = function () { - var connection = this._connection; - if (!connection) { - this._isComplete = false; - connection = this._connection = new Subscription(); - connection.add(this.source - .subscribe(new ConnectableSubscriber(this.getSubject(), this))); - if (connection.closed) { - this._connection = null; - connection = Subscription.EMPTY; - } - } - return connection; - }; - ConnectableObservable.prototype.refCount = function () { - return refCount()(this); - }; - return ConnectableObservable; - }(Observable)); - var connectableObservableDescriptor = /*@__PURE__*/ (function () { - var connectableProto = ConnectableObservable.prototype; - return { - operator: { value: null }, - _refCount: { value: 0, writable: true }, - _subject: { value: null, writable: true }, - _connection: { value: null, writable: true }, - _subscribe: { value: connectableProto._subscribe }, - _isComplete: { value: connectableProto._isComplete, writable: true }, - getSubject: { value: connectableProto.getSubject }, - connect: { value: connectableProto.connect }, - refCount: { value: connectableProto.refCount } - }; - })(); - var ConnectableSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ConnectableSubscriber, _super); - function ConnectableSubscriber(destination, connectable) { - var _this = _super.call(this, destination) || this; - _this.connectable = connectable; - return _this; - } - ConnectableSubscriber.prototype._error = function (err) { - this._unsubscribe(); - _super.prototype._error.call(this, err); - }; - ConnectableSubscriber.prototype._complete = function () { - this.connectable._isComplete = true; - this._unsubscribe(); - _super.prototype._complete.call(this); - }; - ConnectableSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (connectable) { - this.connectable = null; - var connection = connectable._connection; - connectable._refCount = 0; - connectable._subject = null; - connectable._connection = null; - if (connection) { - connection.unsubscribe(); - } - } - }; - return ConnectableSubscriber; - }(SubjectSubscriber)); - - /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ - var Action = /*@__PURE__*/ (function (_super) { - __extends(Action, _super); - function Action(scheduler, work) { - return _super.call(this) || this; - } - Action.prototype.schedule = function (state, delay) { - return this; - }; - return Action; - }(Subscription)); - - /** PURE_IMPORTS_START tslib,_Action PURE_IMPORTS_END */ - var AsyncAction = /*@__PURE__*/ (function (_super) { - __extends(AsyncAction, _super); - function AsyncAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.pending = false; - return _this; - } - AsyncAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - if (this.closed) { - return this; - } - this.state = state; - var id = this.id; - var scheduler = this.scheduler; - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay); - } - this.pending = true; - this.delay = delay; - this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); - return this; - }; - AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - return setInterval(scheduler.flush.bind(scheduler, this), delay); - }; - AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay !== null && this.delay === delay && this.pending === false) { - return id; - } - clearInterval(id); - return undefined; - }; - AsyncAction.prototype.execute = function (state, delay) { - if (this.closed) { - return new Error('executing a cancelled action'); - } - this.pending = false; - var error = this._execute(state, delay); - if (error) { - return error; - } - else if (this.pending === false && this.id != null) { - this.id = this.recycleAsyncId(this.scheduler, this.id, null); - } - }; - AsyncAction.prototype._execute = function (state, delay) { - var errored = false; - var errorValue = undefined; - try { - this.work(state); - } - catch (e) { - errored = true; - errorValue = !!e && e || new Error(e); - } - if (errored) { - this.unsubscribe(); - return errorValue; - } - }; - AsyncAction.prototype._unsubscribe = function () { - var id = this.id; - var scheduler = this.scheduler; - var actions = scheduler.actions; - var index = actions.indexOf(this); - this.work = null; - this.state = null; - this.pending = false; - this.scheduler = null; - if (index !== -1) { - actions.splice(index, 1); - } - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); - } - this.delay = null; - }; - return AsyncAction; - }(Action)); - - var Scheduler = /*@__PURE__*/ (function () { - function Scheduler(SchedulerAction, now) { - if (now === void 0) { - now = Scheduler.now; - } - this.SchedulerAction = SchedulerAction; - this.now = now; - } - Scheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { - delay = 0; - } - return new this.SchedulerAction(this, work).schedule(state, delay); - }; - Scheduler.now = function () { return Date.now(); }; - return Scheduler; - }()); - - /** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */ - var AsyncScheduler = /*@__PURE__*/ (function (_super) { - __extends(AsyncScheduler, _super); - function AsyncScheduler(SchedulerAction, now) { - if (now === void 0) { - now = Scheduler.now; - } - var _this = _super.call(this, SchedulerAction, function () { - if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) { - return AsyncScheduler.delegate.now(); - } - else { - return now(); - } - }) || this; - _this.actions = []; - _this.active = false; - _this.scheduled = undefined; - return _this; - } - AsyncScheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { - delay = 0; - } - if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) { - return AsyncScheduler.delegate.schedule(work, delay, state); - } - else { - return _super.prototype.schedule.call(this, work, delay, state); - } - }; - AsyncScheduler.prototype.flush = function (action) { - var actions = this.actions; - if (this.active) { - actions.push(action); - return; - } - var error; - this.active = true; - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (action = actions.shift()); - this.active = false; - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - return AsyncScheduler; - }(Scheduler)); - - /** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ - var EMPTY = /*@__PURE__*/ new Observable(function (subscriber) { return subscriber.complete(); }); - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function isScheduler(value) { - return value && typeof value.schedule === 'function'; - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var subscribeToArray = function (array) { - return function (subscriber) { - for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { - subscriber.next(array[i]); - } - subscriber.complete(); - }; - }; - - /** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ - function scheduleArray(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - var i = 0; - sub.add(scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - return; - } - subscriber.next(input[i++]); - if (!subscriber.closed) { - sub.add(this.schedule()); - } - })); - return sub; - }); - } - - /** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */ - function fromArray(input, scheduler) { - if (!scheduler) { - return new Observable(subscribeToArray(input)); - } - else { - return scheduleArray(input, scheduler); - } - } - - /** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */ - function of() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = args[args.length - 1]; - if (isScheduler(scheduler)) { - args.pop(); - return scheduleArray(args, scheduler); - } - else { - return fromArray(args); - } - } - - /** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ - var asyncScheduler = /*@__PURE__*/ new AsyncScheduler(AsyncAction); - var async = asyncScheduler; - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function noop() { } - - /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - function map(project, thisArg) { - return function mapOperation(source) { - if (typeof project !== 'function') { - throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); - } - return source.lift(new MapOperator(project, thisArg)); - }; - } - var MapOperator = /*@__PURE__*/ (function () { - function MapOperator(project, thisArg) { - this.project = project; - this.thisArg = thisArg; - } - MapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); - }; - return MapOperator; - }()); - var MapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MapSubscriber, _super); - function MapSubscriber(destination, project, thisArg) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.count = 0; - _this.thisArg = thisArg || _this; - return _this; - } - MapSubscriber.prototype._next = function (value) { - var result; - try { - result = this.project.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return MapSubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - var OuterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(OuterSubscriber, _super); - function OuterSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); - }; - OuterSubscriber.prototype.notifyError = function (error, innerSub) { - this.destination.error(error); - }; - OuterSubscriber.prototype.notifyComplete = function (innerSub) { - this.destination.complete(); - }; - return OuterSubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - var InnerSubscriber = /*@__PURE__*/ (function (_super) { - __extends(InnerSubscriber, _super); - function InnerSubscriber(parent, outerValue, outerIndex) { - var _this = _super.call(this) || this; - _this.parent = parent; - _this.outerValue = outerValue; - _this.outerIndex = outerIndex; - _this.index = 0; - return _this; - } - InnerSubscriber.prototype._next = function (value) { - this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this); - }; - InnerSubscriber.prototype._error = function (error) { - this.parent.notifyError(error, this); - this.unsubscribe(); - }; - InnerSubscriber.prototype._complete = function () { - this.parent.notifyComplete(this); - this.unsubscribe(); - }; - return InnerSubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ - var subscribeToPromise = function (promise) { - return function (subscriber) { - promise.then(function (value) { - if (!subscriber.closed) { - subscriber.next(value); - subscriber.complete(); - } - }, function (err) { return subscriber.error(err); }) - .then(null, hostReportError); - return subscriber; - }; - }; - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function getSymbolIterator() { - if (typeof Symbol !== 'function' || !Symbol.iterator) { - return '@@iterator'; - } - return Symbol.iterator; - } - var iterator = /*@__PURE__*/ getSymbolIterator(); - - /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ - var subscribeToIterable = function (iterable) { - return function (subscriber) { - var iterator$1 = iterable[iterator](); - do { - var item = void 0; - try { - item = iterator$1.next(); - } - catch (err) { - subscriber.error(err); - return subscriber; - } - if (item.done) { - subscriber.complete(); - break; - } - subscriber.next(item.value); - if (subscriber.closed) { - break; - } - } while (true); - if (typeof iterator$1.return === 'function') { - subscriber.add(function () { - if (iterator$1.return) { - iterator$1.return(); - } - }); - } - return subscriber; - }; - }; - - /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ - var subscribeToObservable = function (obj) { - return function (subscriber) { - var obs = obj[observable](); - if (typeof obs.subscribe !== 'function') { - throw new TypeError('Provided object does not correctly implement Symbol.observable'); - } - else { - return obs.subscribe(subscriber); - } - }; - }; - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var isArrayLike$1 = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function isPromise(value) { - return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; - } - - /** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ - var subscribeTo = function (result) { - if (!!result && typeof result[observable] === 'function') { - return subscribeToObservable(result); - } - else if (isArrayLike$1(result)) { - return subscribeToArray(result); - } - else if (isPromise(result)) { - return subscribeToPromise(result); - } - else if (!!result && typeof result[iterator] === 'function') { - return subscribeToIterable(result); - } - else { - var value = isObject$1(result) ? 'an invalid object' : "'" + result + "'"; - var msg = "You provided " + value + " where a stream was expected." - + ' You can provide an Observable, Promise, Array, or Iterable.'; - throw new TypeError(msg); - } - }; - - /** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */ - function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber) { - if (innerSubscriber === void 0) { - innerSubscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex); - } - if (innerSubscriber.closed) { - return undefined; - } - if (result instanceof Observable) { - return result.subscribe(innerSubscriber); - } - return subscribeTo(result)(innerSubscriber); - } - - /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ - function scheduleObservable(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - var observable$1 = input[observable](); - sub.add(observable$1.subscribe({ - next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, - error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, - complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, - })); - })); - return sub; - }); - } - - /** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ - function schedulePromise(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - return input.then(function (value) { - sub.add(scheduler.schedule(function () { - subscriber.next(value); - sub.add(scheduler.schedule(function () { return subscriber.complete(); })); - })); - }, function (err) { - sub.add(scheduler.schedule(function () { return subscriber.error(err); })); - }); - })); - return sub; - }); - } - - /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ - function scheduleIterable(input, scheduler) { - if (!input) { - throw new Error('Iterable cannot be null'); - } - return new Observable(function (subscriber) { - var sub = new Subscription(); - var iterator$1; - sub.add(function () { - if (iterator$1 && typeof iterator$1.return === 'function') { - iterator$1.return(); - } - }); - sub.add(scheduler.schedule(function () { - iterator$1 = input[iterator](); - sub.add(scheduler.schedule(function () { - if (subscriber.closed) { - return; - } - var value; - var done; - try { - var result = iterator$1.next(); - value = result.value; - done = result.done; - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - this.schedule(); - } - })); - })); - return sub; - }); - } - - /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ - function isInteropObservable(input) { - return input && typeof input[observable] === 'function'; - } - - /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ - function isIterable(input) { - return input && typeof input[iterator] === 'function'; - } - - /** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ - function scheduled(input, scheduler) { - if (input != null) { - if (isInteropObservable(input)) { - return scheduleObservable(input, scheduler); - } - else if (isPromise(input)) { - return schedulePromise(input, scheduler); - } - else if (isArrayLike$1(input)) { - return scheduleArray(input, scheduler); - } - else if (isIterable(input) || typeof input === 'string') { - return scheduleIterable(input, scheduler); - } - } - throw new TypeError((input !== null && typeof input || input) + ' is not observable'); - } - - /** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ - function from$1(input, scheduler) { - if (!scheduler) { - if (input instanceof Observable) { - return input; - } - return new Observable(subscribeTo(input)); - } - else { - return scheduled(input, scheduler); - } - } - - /** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_util_subscribeTo PURE_IMPORTS_END */ - var SimpleInnerSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SimpleInnerSubscriber, _super); - function SimpleInnerSubscriber(parent) { - var _this = _super.call(this) || this; - _this.parent = parent; - return _this; - } - SimpleInnerSubscriber.prototype._next = function (value) { - this.parent.notifyNext(value); - }; - SimpleInnerSubscriber.prototype._error = function (error) { - this.parent.notifyError(error); - this.unsubscribe(); - }; - SimpleInnerSubscriber.prototype._complete = function () { - this.parent.notifyComplete(); - this.unsubscribe(); - }; - return SimpleInnerSubscriber; - }(Subscriber)); - var SimpleOuterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SimpleOuterSubscriber, _super); - function SimpleOuterSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - SimpleOuterSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - SimpleOuterSubscriber.prototype.notifyError = function (err) { - this.destination.error(err); - }; - SimpleOuterSubscriber.prototype.notifyComplete = function () { - this.destination.complete(); - }; - return SimpleOuterSubscriber; - }(Subscriber)); - function innerSubscribe(result, innerSubscriber) { - if (innerSubscriber.closed) { - return undefined; - } - if (result instanceof Observable) { - return result.subscribe(innerSubscriber); - } - return subscribeTo(result)(innerSubscriber); - } - - /** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ - function mergeMap(project, resultSelector, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(mergeMap(function (a, i) { return from$1(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); }; - } - else if (typeof resultSelector === 'number') { - concurrent = resultSelector; - } - return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); }; - } - var MergeMapOperator = /*@__PURE__*/ (function () { - function MergeMapOperator(project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - this.project = project; - this.concurrent = concurrent; - } - MergeMapOperator.prototype.call = function (observer, source) { - return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent)); - }; - return MergeMapOperator; - }()); - var MergeMapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MergeMapSubscriber, _super); - function MergeMapSubscriber(destination, project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.concurrent = concurrent; - _this.hasCompleted = false; - _this.buffer = []; - _this.active = 0; - _this.index = 0; - return _this; - } - MergeMapSubscriber.prototype._next = function (value) { - if (this.active < this.concurrent) { - this._tryNext(value); - } - else { - this.buffer.push(value); - } - }; - MergeMapSubscriber.prototype._tryNext = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this.active++; - this._innerSub(result); - }; - MergeMapSubscriber.prototype._innerSub = function (ish) { - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - var innerSubscription = innerSubscribe(ish, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - destination.add(innerSubscription); - } - }; - MergeMapSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - this.destination.complete(); - } - this.unsubscribe(); - }; - MergeMapSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - MergeMapSubscriber.prototype.notifyComplete = function () { - var buffer = this.buffer; - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); - } - else if (this.active === 0 && this.hasCompleted) { - this.destination.complete(); - } - }; - return MergeMapSubscriber; - }(SimpleOuterSubscriber)); - - /** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ - function fromEventPattern(addHandler, removeHandler, resultSelector) { - if (resultSelector) { - return fromEventPattern(addHandler, removeHandler).pipe(map(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - } - return new Observable(function (subscriber) { - var handler = function () { - var e = []; - for (var _i = 0; _i < arguments.length; _i++) { - e[_i] = arguments[_i]; - } - return subscriber.next(e.length === 1 ? e[0] : e); - }; - var retValue; - try { - retValue = addHandler(handler); - } - catch (err) { - subscriber.error(err); - return undefined; - } - if (!isFunction$1(removeHandler)) { - return undefined; - } - return function () { return removeHandler(handler, retValue); }; - }); - } - - /** PURE_IMPORTS_START _isArray PURE_IMPORTS_END */ - function isNumeric(val) { - return !isArray$1(val) && (val - parseFloat(val) + 1) >= 0; - } - - /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - function filter(predicate, thisArg) { - return function filterOperatorFunction(source) { - return source.lift(new FilterOperator(predicate, thisArg)); - }; - } - var FilterOperator = /*@__PURE__*/ (function () { - function FilterOperator(predicate, thisArg) { - this.predicate = predicate; - this.thisArg = thisArg; - } - FilterOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); - }; - return FilterOperator; - }()); - var FilterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(FilterSubscriber, _super); - function FilterSubscriber(destination, predicate, thisArg) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.thisArg = thisArg; - _this.count = 0; - return _this; - } - FilterSubscriber.prototype._next = function (value) { - var result; - try { - result = this.predicate.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - this.destination.next(value); - } - }; - return FilterSubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ - function timer(dueTime, periodOrScheduler, scheduler) { - if (dueTime === void 0) { - dueTime = 0; - } - var period = -1; - if (isNumeric(periodOrScheduler)) { - period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler); - } - else if (isScheduler(periodOrScheduler)) { - scheduler = periodOrScheduler; - } - if (!isScheduler(scheduler)) { - scheduler = async; - } - return new Observable(function (subscriber) { - var due = isNumeric(dueTime) - ? dueTime - : (+dueTime - scheduler.now()); - return scheduler.schedule(dispatch, due, { - index: 0, period: period, subscriber: subscriber - }); - }); - } - function dispatch(state) { - var index = state.index, period = state.period, subscriber = state.subscriber; - subscriber.next(index); - if (subscriber.closed) { - return; - } - else if (period === -1) { - return subscriber.complete(); - } - state.index = index + 1; - this.schedule(state, period); - } - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Built-in value references. */ - var Symbol$1 = root.Symbol; - - /** Used for built-in method references. */ - var objectProto$6 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$5 = objectProto$6.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString$1 = objectProto$6.toString; - - /** Built-in value references. */ - var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty$5.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; - - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString$1.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$5 = Object.prototype; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto$5.toString; - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString.call(value); - } - - /** `Object#toString` result references. */ - var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - - /** Built-in value references. */ - var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** `Object#toString` result references. */ - var symbolTag = '[object Symbol]'; - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); - } - - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** Used as references for various `Number` constants. */ - var INFINITY$1 = 1 / 0; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity(value) { - return value; - } - - /** `Object#toString` result references. */ - var asyncTag = '[object AsyncFunction]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** Used for built-in method references. */ - var funcProto$1 = Function.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$1 = funcProto$1.toString; - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString$1.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used for built-in method references. */ - var funcProto = Function.prototype, - objectProto$4 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$4 = objectProto$4.hasOwnProperty; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty$4).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeNow = Date.now; - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ - function constant(value) { - return function() { - return value; - }; - } - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } - - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } - - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$1 = 9007199254740991; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$1 : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** Used for built-in method references. */ - var objectProto$3 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$3 = objectProto$3.hasOwnProperty; - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$3.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeMax = Math.max; - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]'; - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** Used for built-in method references. */ - var objectProto$2 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$2 = objectProto$2.hasOwnProperty; - - /** Built-in value references. */ - var propertyIsEnumerable = objectProto$2.propertyIsEnumerable; - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /* Built-in method references that are verified to be native. */ - var nativeCreate = getNative(Object, 'create'); - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - - /** Used for built-in method references. */ - var objectProto$1 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$1 = objectProto$1.hasOwnProperty; - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED$2 ? undefined : result; - } - return hasOwnProperty$1.call(data, key) ? data[key] : undefined; - } - - /** Used for built-in method references. */ - var objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; - } - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype; - - /** Built-in value references. */ - var splice = arrayProto.splice; - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /* Built-in method references that are verified to be native. */ - var Map$1 = getNative(root, 'Map'); - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** Error message constants. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** Used to match property names within property paths. */ - var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0; - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** Built-in value references. */ - var spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : undefined; - - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); - } - - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } - - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } - - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; - } - - /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - - /** `Object#toString` result references. */ - var stringTag = '[object String]'; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); - } - - /** `Object#toString` result references. */ - var regexpTag = '[object RegExp]'; - - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } - - /* Node.js helper references. */ - var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; - - /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } - - /** - * Creates an object composed of the picked `object` properties. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); - - /** PURE_IMPORTS_START tslib,_scheduler_async,_Subscriber,_util_isScheduler PURE_IMPORTS_END */ - function bufferTime(bufferTimeSpan) { - var length = arguments.length; - var scheduler = async; - if (isScheduler(arguments[arguments.length - 1])) { - scheduler = arguments[arguments.length - 1]; - length--; - } - var bufferCreationInterval = null; - if (length >= 2) { - bufferCreationInterval = arguments[1]; - } - var maxBufferSize = Number.POSITIVE_INFINITY; - if (length >= 3) { - maxBufferSize = arguments[2]; - } - return function bufferTimeOperatorFunction(source) { - return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler)); - }; - } - var BufferTimeOperator = /*@__PURE__*/ (function () { - function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { - this.bufferTimeSpan = bufferTimeSpan; - this.bufferCreationInterval = bufferCreationInterval; - this.maxBufferSize = maxBufferSize; - this.scheduler = scheduler; - } - BufferTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler)); - }; - return BufferTimeOperator; - }()); - var Context = /*@__PURE__*/ (function () { - function Context() { - this.buffer = []; - } - return Context; - }()); - var BufferTimeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(BufferTimeSubscriber, _super); - function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { - var _this = _super.call(this, destination) || this; - _this.bufferTimeSpan = bufferTimeSpan; - _this.bufferCreationInterval = bufferCreationInterval; - _this.maxBufferSize = maxBufferSize; - _this.scheduler = scheduler; - _this.contexts = []; - var context = _this.openContext(); - _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0; - if (_this.timespanOnly) { - var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan }; - _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); - } - else { - var closeState = { subscriber: _this, context: context }; - var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler }; - _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState)); - _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState)); - } - return _this; - } - BufferTimeSubscriber.prototype._next = function (value) { - var contexts = this.contexts; - var len = contexts.length; - var filledBufferContext; - for (var i = 0; i < len; i++) { - var context_1 = contexts[i]; - var buffer = context_1.buffer; - buffer.push(value); - if (buffer.length == this.maxBufferSize) { - filledBufferContext = context_1; - } - } - if (filledBufferContext) { - this.onBufferFull(filledBufferContext); - } - }; - BufferTimeSubscriber.prototype._error = function (err) { - this.contexts.length = 0; - _super.prototype._error.call(this, err); - }; - BufferTimeSubscriber.prototype._complete = function () { - var _a = this, contexts = _a.contexts, destination = _a.destination; - while (contexts.length > 0) { - var context_2 = contexts.shift(); - destination.next(context_2.buffer); - } - _super.prototype._complete.call(this); - }; - BufferTimeSubscriber.prototype._unsubscribe = function () { - this.contexts = null; - }; - BufferTimeSubscriber.prototype.onBufferFull = function (context) { - this.closeContext(context); - var closeAction = context.closeAction; - closeAction.unsubscribe(); - this.remove(closeAction); - if (!this.closed && this.timespanOnly) { - context = this.openContext(); - var bufferTimeSpan = this.bufferTimeSpan; - var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan }; - this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); - } - }; - BufferTimeSubscriber.prototype.openContext = function () { - var context = new Context(); - this.contexts.push(context); - return context; - }; - BufferTimeSubscriber.prototype.closeContext = function (context) { - this.destination.next(context.buffer); - var contexts = this.contexts; - var spliceIndex = contexts ? contexts.indexOf(context) : -1; - if (spliceIndex >= 0) { - contexts.splice(contexts.indexOf(context), 1); - } - }; - return BufferTimeSubscriber; - }(Subscriber)); - function dispatchBufferTimeSpanOnly(state) { - var subscriber = state.subscriber; - var prevContext = state.context; - if (prevContext) { - subscriber.closeContext(prevContext); - } - if (!subscriber.closed) { - state.context = subscriber.openContext(); - state.context.closeAction = this.schedule(state, state.bufferTimeSpan); - } - } - function dispatchBufferCreation(state) { - var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler; - var context = subscriber.openContext(); - var action = this; - if (!subscriber.closed) { - subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context })); - action.schedule(state, bufferCreationInterval); - } - } - function dispatchBufferClose(arg) { - var subscriber = arg.subscriber, context = arg.context; - subscriber.closeContext(context); - } - - /** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ - function catchError(selector) { - return function catchErrorOperatorFunction(source) { - var operator = new CatchOperator(selector); - var caught = source.lift(operator); - return (operator.caught = caught); - }; - } - var CatchOperator = /*@__PURE__*/ (function () { - function CatchOperator(selector) { - this.selector = selector; - } - CatchOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught)); - }; - return CatchOperator; - }()); - var CatchSubscriber = /*@__PURE__*/ (function (_super) { - __extends(CatchSubscriber, _super); - function CatchSubscriber(destination, selector, caught) { - var _this = _super.call(this, destination) || this; - _this.selector = selector; - _this.caught = caught; - return _this; - } - CatchSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var result = void 0; - try { - result = this.selector(err, this.caught); - } - catch (err2) { - _super.prototype.error.call(this, err2); - return; - } - this._unsubscribeAndRecycle(); - var innerSubscriber = new SimpleInnerSubscriber(this); - this.add(innerSubscriber); - var innerSubscription = innerSubscribe(result, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - this.add(innerSubscription); - } - } - }; - return CatchSubscriber; - }(SimpleOuterSubscriber)); - - /** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ - function concatMap(project, resultSelector) { - return mergeMap(project, resultSelector, 1); - } - - /** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ - function delayWhen(delayDurationSelector, subscriptionDelay) { - if (subscriptionDelay) { - return function (source) { - return new SubscriptionDelayObservable(source, subscriptionDelay) - .lift(new DelayWhenOperator(delayDurationSelector)); - }; - } - return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); }; - } - var DelayWhenOperator = /*@__PURE__*/ (function () { - function DelayWhenOperator(delayDurationSelector) { - this.delayDurationSelector = delayDurationSelector; - } - DelayWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector)); - }; - return DelayWhenOperator; - }()); - var DelayWhenSubscriber = /*@__PURE__*/ (function (_super) { - __extends(DelayWhenSubscriber, _super); - function DelayWhenSubscriber(destination, delayDurationSelector) { - var _this = _super.call(this, destination) || this; - _this.delayDurationSelector = delayDurationSelector; - _this.completed = false; - _this.delayNotifierSubscriptions = []; - _this.index = 0; - return _this; - } - DelayWhenSubscriber.prototype.notifyNext = function (outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) { - this.destination.next(outerValue); - this.removeSubscription(innerSub); - this.tryComplete(); - }; - DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) { - this._error(error); - }; - DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) { - var value = this.removeSubscription(innerSub); - if (value) { - this.destination.next(value); - } - this.tryComplete(); - }; - DelayWhenSubscriber.prototype._next = function (value) { - var index = this.index++; - try { - var delayNotifier = this.delayDurationSelector(value, index); - if (delayNotifier) { - this.tryDelay(delayNotifier, value); - } - } - catch (err) { - this.destination.error(err); - } - }; - DelayWhenSubscriber.prototype._complete = function () { - this.completed = true; - this.tryComplete(); - this.unsubscribe(); - }; - DelayWhenSubscriber.prototype.removeSubscription = function (subscription) { - subscription.unsubscribe(); - var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription); - if (subscriptionIdx !== -1) { - this.delayNotifierSubscriptions.splice(subscriptionIdx, 1); - } - return subscription.outerValue; - }; - DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) { - var notifierSubscription = subscribeToResult(this, delayNotifier, value); - if (notifierSubscription && !notifierSubscription.closed) { - var destination = this.destination; - destination.add(notifierSubscription); - this.delayNotifierSubscriptions.push(notifierSubscription); - } - }; - DelayWhenSubscriber.prototype.tryComplete = function () { - if (this.completed && this.delayNotifierSubscriptions.length === 0) { - this.destination.complete(); - } - }; - return DelayWhenSubscriber; - }(OuterSubscriber)); - var SubscriptionDelayObservable = /*@__PURE__*/ (function (_super) { - __extends(SubscriptionDelayObservable, _super); - function SubscriptionDelayObservable(source, subscriptionDelay) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subscriptionDelay = subscriptionDelay; - return _this; - } - SubscriptionDelayObservable.prototype._subscribe = function (subscriber) { - this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source)); - }; - return SubscriptionDelayObservable; - }(Observable)); - var SubscriptionDelaySubscriber = /*@__PURE__*/ (function (_super) { - __extends(SubscriptionDelaySubscriber, _super); - function SubscriptionDelaySubscriber(parent, source) { - var _this = _super.call(this) || this; - _this.parent = parent; - _this.source = source; - _this.sourceSubscribed = false; - return _this; - } - SubscriptionDelaySubscriber.prototype._next = function (unused) { - this.subscribeToSource(); - }; - SubscriptionDelaySubscriber.prototype._error = function (err) { - this.unsubscribe(); - this.parent.error(err); - }; - SubscriptionDelaySubscriber.prototype._complete = function () { - this.unsubscribe(); - this.subscribeToSource(); - }; - SubscriptionDelaySubscriber.prototype.subscribeToSource = function () { - if (!this.sourceSubscribed) { - this.sourceSubscribed = true; - this.unsubscribe(); - this.source.subscribe(this.parent); - } - }; - return SubscriptionDelaySubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - function scan(accumulator, seed) { - var hasSeed = false; - if (arguments.length >= 2) { - hasSeed = true; - } - return function scanOperatorFunction(source) { - return source.lift(new ScanOperator(accumulator, seed, hasSeed)); - }; - } - var ScanOperator = /*@__PURE__*/ (function () { - function ScanOperator(accumulator, seed, hasSeed) { - if (hasSeed === void 0) { - hasSeed = false; - } - this.accumulator = accumulator; - this.seed = seed; - this.hasSeed = hasSeed; - } - ScanOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); - }; - return ScanOperator; - }()); - var ScanSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ScanSubscriber, _super); - function ScanSubscriber(destination, accumulator, _seed, hasSeed) { - var _this = _super.call(this, destination) || this; - _this.accumulator = accumulator; - _this._seed = _seed; - _this.hasSeed = hasSeed; - _this.index = 0; - return _this; - } - Object.defineProperty(ScanSubscriber.prototype, "seed", { - get: function () { - return this._seed; - }, - set: function (value) { - this.hasSeed = true; - this._seed = value; - }, - enumerable: true, - configurable: true - }); - ScanSubscriber.prototype._next = function (value) { - if (!this.hasSeed) { - this.seed = value; - this.destination.next(value); - } - else { - return this._tryNext(value); - } - }; - ScanSubscriber.prototype._tryNext = function (value) { - var index = this.index++; - var result; - try { - result = this.accumulator(this.seed, value, index); - } - catch (err) { - this.destination.error(err); - } - this.seed = result; - this.destination.next(result); - }; - return ScanSubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */ - function multicast(subjectOrSubjectFactory, selector) { - return function multicastOperatorFunction(source) { - var subjectFactory; - if (typeof subjectOrSubjectFactory === 'function') { - subjectFactory = subjectOrSubjectFactory; - } - else { - subjectFactory = function subjectFactory() { - return subjectOrSubjectFactory; - }; - } - if (typeof selector === 'function') { - return source.lift(new MulticastOperator(subjectFactory, selector)); - } - var connectable = Object.create(source, connectableObservableDescriptor); - connectable.source = source; - connectable.subjectFactory = subjectFactory; - return connectable; - }; - } - var MulticastOperator = /*@__PURE__*/ (function () { - function MulticastOperator(subjectFactory, selector) { - this.subjectFactory = subjectFactory; - this.selector = selector; - } - MulticastOperator.prototype.call = function (subscriber, source) { - var selector = this.selector; - var subject = this.subjectFactory(); - var subscription = selector(subject).subscribe(subscriber); - subscription.add(source.subscribe(subject)); - return subscription; - }; - return MulticastOperator; - }()); - - /** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */ - function retryWhen(notifier) { - return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); }; - } - var RetryWhenOperator = /*@__PURE__*/ (function () { - function RetryWhenOperator(notifier, source) { - this.notifier = notifier; - this.source = source; - } - RetryWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source)); - }; - return RetryWhenOperator; - }()); - var RetryWhenSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RetryWhenSubscriber, _super); - function RetryWhenSubscriber(destination, notifier, source) { - var _this = _super.call(this, destination) || this; - _this.notifier = notifier; - _this.source = source; - return _this; - } - RetryWhenSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var errors = this.errors; - var retries = this.retries; - var retriesSubscription = this.retriesSubscription; - if (!retries) { - errors = new Subject(); - try { - var notifier = this.notifier; - retries = notifier(errors); - } - catch (e) { - return _super.prototype.error.call(this, e); - } - retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this)); - } - else { - this.errors = undefined; - this.retriesSubscription = undefined; - } - this._unsubscribeAndRecycle(); - this.errors = errors; - this.retries = retries; - this.retriesSubscription = retriesSubscription; - errors.next(err); - } - }; - RetryWhenSubscriber.prototype._unsubscribe = function () { - var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription; - if (errors) { - errors.unsubscribe(); - this.errors = undefined; - } - if (retriesSubscription) { - retriesSubscription.unsubscribe(); - this.retriesSubscription = undefined; - } - this.retries = undefined; - }; - RetryWhenSubscriber.prototype.notifyNext = function () { - var _unsubscribe = this._unsubscribe; - this._unsubscribe = null; - this._unsubscribeAndRecycle(); - this._unsubscribe = _unsubscribe; - this.source.subscribe(this); - }; - return RetryWhenSubscriber; - }(SimpleOuterSubscriber)); - - /** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */ - function shareSubjectFactory() { - return new Subject(); - } - function share() { - return function (source) { return refCount()(multicast(shareSubjectFactory)(source)); }; - } - - /** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ - function switchMap(project, resultSelector) { - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(switchMap(function (a, i) { return from$1(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; - } - return function (source) { return source.lift(new SwitchMapOperator(project)); }; - } - var SwitchMapOperator = /*@__PURE__*/ (function () { - function SwitchMapOperator(project) { - this.project = project; - } - SwitchMapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SwitchMapSubscriber(subscriber, this.project)); - }; - return SwitchMapOperator; - }()); - var SwitchMapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SwitchMapSubscriber, _super); - function SwitchMapSubscriber(destination, project) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.index = 0; - return _this; - } - SwitchMapSubscriber.prototype._next = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (error) { - this.destination.error(error); - return; - } - this._innerSub(result); - }; - SwitchMapSubscriber.prototype._innerSub = function (result) { - var innerSubscription = this.innerSubscription; - if (innerSubscription) { - innerSubscription.unsubscribe(); - } - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - this.innerSubscription = innerSubscribe(result, innerSubscriber); - if (this.innerSubscription !== innerSubscriber) { - destination.add(this.innerSubscription); - } - }; - SwitchMapSubscriber.prototype._complete = function () { - var innerSubscription = this.innerSubscription; - if (!innerSubscription || innerSubscription.closed) { - _super.prototype._complete.call(this); - } - this.unsubscribe(); - }; - SwitchMapSubscriber.prototype._unsubscribe = function () { - this.innerSubscription = undefined; - }; - SwitchMapSubscriber.prototype.notifyComplete = function () { - this.innerSubscription = undefined; - if (this.isStopped) { - _super.prototype._complete.call(this); - } - }; - SwitchMapSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - return SwitchMapSubscriber; - }(SimpleOuterSubscriber)); - - /** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */ - function tap(nextOrObserver, error, complete) { - return function tapOperatorFunction(source) { - return source.lift(new DoOperator(nextOrObserver, error, complete)); - }; - } - var DoOperator = /*@__PURE__*/ (function () { - function DoOperator(nextOrObserver, error, complete) { - this.nextOrObserver = nextOrObserver; - this.error = error; - this.complete = complete; - } - DoOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); - }; - return DoOperator; - }()); - var TapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(TapSubscriber, _super); - function TapSubscriber(destination, observerOrNext, error, complete) { - var _this = _super.call(this, destination) || this; - _this._tapNext = noop; - _this._tapError = noop; - _this._tapComplete = noop; - _this._tapError = error || noop; - _this._tapComplete = complete || noop; - if (isFunction$1(observerOrNext)) { - _this._context = _this; - _this._tapNext = observerOrNext; - } - else if (observerOrNext) { - _this._context = observerOrNext; - _this._tapNext = observerOrNext.next || noop; - _this._tapError = observerOrNext.error || noop; - _this._tapComplete = observerOrNext.complete || noop; - } - return _this; - } - TapSubscriber.prototype._next = function (value) { - try { - this._tapNext.call(this._context, value); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(value); - }; - TapSubscriber.prototype._error = function (err) { - try { - this._tapError.call(this._context, err); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.error(err); - }; - TapSubscriber.prototype._complete = function () { - try { - this._tapComplete.call(this._context); - } - catch (err) { - this.destination.error(err); - return; - } - return this.destination.complete(); - }; - return TapSubscriber; - }(Subscriber)); + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - /** + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ +var en=function(e,t){return(en=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function tn(e,t){function r(){this.constructor=e}en(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var rn=function(){return(rn=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function on(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function an(){for(var e=[],t=0;t";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==Mn.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeCreation()}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseAboutToDie()}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.fireInternalHook(e)}}),t}(fn);pn.prototype.die=Ot(pn.prototype.die);var hn,bn,dn=1,vn={onError:function(e){throw e}},yn=function(e){function t(t,r,n,i,o){var a=e.call(this,t,r,n,i)||this;if(Object.defineProperty(a,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:++dn}),Object.defineProperty(a,"identifierAttribute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"unnormalizedIdentifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifierCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"isProtectionEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applyPatches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applySnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_autoUnbox",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"_isRunningAction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_hasSnapshotReaction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_observableInstanceState",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(a,"_childNodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_initialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshotCreated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_snapshotComputed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_snapshotUponDeath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_internalEvents",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),a._snapshotComputed=Ae((function(){return a.getSnapshot()})),a.unbox=a.unbox.bind(a),a._initialSnapshot=o,a.identifierAttribute=t.identifierAttribute,r||(a.identifierCache=new Fn),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 u=a._childNodes[a.identifierAttribute];u&&(s=u.value)}if("string"!=typeof s&&"number"!=typeof s)throw Jn("Instance identifier '"+a.identifierAttribute+"' for type '"+a.type.name+"' must be a string or a number");a.identifier=ho(s),a.unnormalizedIdentifier=s}return r?r.root.identifierCache.addNodeToCache(a):a.identifierCache.addNodeToCache(a),a}return tn(t,e),Object.defineProperty(t.prototype,"applyPatches",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)}}),Object.defineProperty(t.prototype,"createObservableInstanceIfNeeded",{enumerable:!1,configurable:!0,writable:!0,value:function(){0===this._observableInstanceState&&this.createObservableInstance()}}),Object.defineProperty(t.prototype,"createObservableInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e,t;this._observableInstanceState=1;for(var r=[],n=this.parent;n&&0===n._observableInstanceState;)r.unshift(n),n=n.parent;try{for(var i=nn(r),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=Mn.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,this._snapshotComputed.trackAndCompute(),this.isRoot&&this._addSnapshotReaction(),this._childNodes=Xn,this.state=Mn.CREATED,this.fireHook(Jr.afterCreate),this.finalizeCreation()}}),Object.defineProperty(t.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearParent",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.parent){this.fireHook(Jr.beforeDetach);var e=this.state;this.state=Mn.DETACHING;var t=this.root,r=t.environment,n=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=r,this.identifierCache=n}finally{this.state=e}}}}),Object.defineProperty(t.prototype,"setParent",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e!==this.parent,n=t!==this.subpath;(r||n)&&(r?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(Jr.afterAttach)):n&&this.baseSetParent(this.parent,t))}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;this.fireInternalHook(e);var r=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof r&&(Pt?Pt((function(){r.apply(t.storedValue)})):r.apply(this.storedValue))}}),Object.defineProperty(t.prototype,"snapshot",{get:function(){return this._snapshotComputed.get()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath}}),Object.defineProperty(t.prototype,"_getActualSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.type.getSnapshot(this)}}),Object.defineProperty(t.prototype,"_getCachedInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this._cachedInitialSnapshotCreated){var e=this.type,t=this._childNodes,r=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,r),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot}}),Object.defineProperty(t.prototype,"isRunningAction",{enumerable:!1,configurable:!0,writable:!0,value:function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()}}),Object.defineProperty(t.prototype,"assertAlive",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t;if(!this.isAlive){var r=this._getAssertAliveError(e);t=r,console.warn(new Error("[mobx-state-tree] "+t))}}}),Object.defineProperty(t.prototype,"_getAssertAliveError",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",r=e.subpath&&bi(e.subpath)||"",n=e.actionContext||Pn;n&&"action"!==n.type&&n.parentActionEvent&&(n=n.parentActionEvent);var i="";n&&null!=n.name&&(i=(n&&n.context&&Bn(n.context).path||t)+"."+n.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: '"+r+"', Action: '"+i+"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value: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}}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.assertAlive(Xn),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):Wn(this._childNodes)}finally{this._autoUnbox=!0}}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.type.getChildType(e)}}),Object.defineProperty(t.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"assertWritable",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw Jn("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.type.removeChild(this,e)}}),Object.defineProperty(t.prototype,"unbox",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e}}),Object.defineProperty(t.prototype,"toString",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this.baseFinalizeCreation((function(){var t,r;try{for(var n=nn(e.getChildren()),i=n.next();!i.done;i=n.next()){i.value.finalizeCreation()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}e.fireInternalHook(Jr.afterCreationFinalization)}))}}),Object.defineProperty(t.prototype,"detach",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this.isAlive)throw Jn("Error while detaching, node is not alive.");this.clearParent()}}),Object.defineProperty(t.prototype,"preboot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this._applyPatches=Tn(this.storedValue,"@APPLY_PATCHES",(function(t){t.forEach((function(t){if(t.path){var r=function(e){var t=e.split("/").map(di);if(!(""===e||"."===e||".."===e||fi(e,"/")||fi(e,"./")||fi(e,"../")))throw Jn("a json path must be either rooted, empty or relative, but got '"+e+"'");""===t[0]&&t.shift();return t}(t.path);qn(e,r.slice(0,-1)).applyPatchLocally(r[r.length-1],t)}else e.type.applySnapshot(e,t.value)}))})),this._applySnapshot=Tn(this.storedValue,"@APPLY_SNAPSHOT",(function(t){if(t!==e.snapshot)return e.type.applySnapshot(e,t)})),si(this.storedValue,"$treenode",this),si(this.storedValue,"toJSON",Kn)}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==Mn.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){0!==this._observableInstanceState&&(this.getChildren().forEach((function(e){e.aboutToDie()})),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.getChildren().forEach((function(e){e.finalizeDeath()})),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"onSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)}}),Object.defineProperty(t.prototype,"emitSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this._internalEventsEmit("snapshot",e)}}),Object.defineProperty(t.prototype,"onPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._internalEventsRegister("patch",e)}}),Object.defineProperty(t.prototype,"emitPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._internalEventsHasSubscribers("patch")){var r=on(function(e){if(!("oldValue"in e))throw Jn("Patches without `oldValue` field cannot be inversed");return[pi(e),hi(e)]}(function(e){for(var t=[],r=1;r=0&&this.middlewares.splice(t,1)}}}),Object.defineProperty(t.prototype,"addMiddleWare",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;void 0===t&&(t=!0);var n={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(n):this.middlewares=[n],function(){r.removeMiddleware(n)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)}}),Object.defineProperty(t.prototype,"_addSnapshotReaction",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;if(!this._hasSnapshotReaction){var t=Et((function(){return e.snapshot}),(function(t){return e.emitSnapshot(t)}),vn);this.addDisposer(t),this._hasSnapshotReaction=!0}}}),Object.defineProperty(t.prototype,"_internalEventsHasSubscribers",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)}}),Object.defineProperty(t.prototype,"_internalEventsRegister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){return void 0===r&&(r=!1),this._internalEvents||(this._internalEvents=new ci),this._internalEvents.register(e,t,r)}}),Object.defineProperty(t.prototype,"_internalEventsHas",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsUnregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsEmit",{enumerable:!1,configurable:!0,writable:!0,value:function(e){for(var t,r=[],n=1;n0},enumerable:!1,configurable:!0})}();var Pn,Sn=1;function An(){return Sn++}function xn(e,t){var r=Bn(e.context);"action"===e.type&&r.assertAlive({actionContext:e});var n=r._isRunningAction;r._isRunningAction=!0;var i=Pn;Pn=e;try{return function(e,t,r){var n=new In(e,r);if(n.isEmpty)return Ot(r).apply(null,t.args);var i=null;function o(e){var t=n.getNextMiddleware(),a=t&&t.handler;if(!a)return Ot(r).apply(null,e.args);if(!t.includeHooks&&Jr[e.name])return o(e);function s(e,t){i=o(e),t&&(i=t(i))}function u(e){i=e}return a(e,s,u),i}return o(t)}(r,e,t)}finally{Pn=i,r._isRunningAction=n}}function En(e){if(e)return"action"===e.type?e:e.parentActionEvent}function Tn(e,t,r){var n=function(){var n=An(),i=Pn,o=En(i);return xn({type:"action",name:t,id:n,args:li(arguments),context:e,tree:ln(e),rootId:i?i.rootId:n,parentId:i?i.id:0,allParentIds:i?an(i.allParentIds,[i.id]):[],parentEvent:i,parentActionEvent:o},r)};return n._isMSTAction=!0,n}var In=function(){function e(e,t){Object.defineProperty(this,"arrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"inArrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:[]}),t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);for(var r=e;r;)r.middlewares&&this.middlewares.push(r.middlewares),r=r.parent}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return this.middlewares.length<=0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"getNextMiddleware",{enumerable:!1,configurable:!0,writable:!0,value: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 Cn(e){return"function"==typeof e?"":Hn(e)?"<"+e+">":"`"+function(e){try{return JSON.stringify(e)}catch(e){return""}}(e)+"`"}function kn(e){var t=e.value,r=e.context[e.context.length-1].type,n=e.context.map((function(e){return e.path})).filter((function(e){return e.length>0})).join("/"),i=n.length>0?'at path "/'+n+'" ':"",o=Hn(t)?"value of type "+Bn(t).type.name+":":ai(t)?"value":"snapshot",a=r&&Hn(t)&&r.is(Bn(t).snapshot);return""+i+o+" "+Cn(t)+" is not assignable "+(r?"to type: `"+r.name+"`":"")+(e.message?" ("+e.message+")":"")+(r?function(e){return jn(e)&&(e.flags&(bn.String|bn.Number|bn.Integer|bn.Boolean|bn.Date))>0}(r)||ai(t)?".":", expected an instance of `"+r.name+"` or a snapshot like `"+r.describe()+"` instead."+(a?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".")}function Dn(e,t,r){return e.concat([{path:t,type:r}])}function Nn(){return Qn}function Vn(e,t,r){return[{context:e,value:t,message:r}]}function Rn(e){return e.reduce((function(e,t){return e.concat(t)}),[])}function Un(e,t){"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK&&function(e,t){var r=e.validate(t,[{path:"",type:e}]);if(r.length>0)throw Jn(function(e,t,r){if(0===r.length)return;return"Error while converting "+(n=Cn(t),(n.length<280?n:n.substring(0,272)+"......"+n.substring(n.length-8))+" to `")+e.name+"`:\n\n "+r.map(kn).join("\n ");var n}(e,t,r))}(e,t)}var Mn,zn=0,Fn=function(){function t(){Object.defineProperty(this,"cacheId",{enumerable:!0,configurable:!0,writable:!0,value:zn++}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:Oe.map()}),Object.defineProperty(this,"lastCacheModificationPerId",{enumerable:!0,configurable:!0,writable:!0,value:Oe.map()})}return Object.defineProperty(t.prototype,"updateLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)}}),Object.defineProperty(t.prototype,"getLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t}}),Object.defineProperty(t.prototype,"addNodeToCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var r=e.identifier;this.cache.has(r)||this.cache.set(r,Oe.array([],Zn));var n=this.cache.get(r);if(-1!==n.indexOf(e))throw Jn("Already registered");n.push(e),t&&this.updateLastCacheModificationPerId(r)}}}),Object.defineProperty(t.prototype,"mergeCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;Ht(e.identifierCache.cache).forEach((function(e){return e.forEach((function(e){t.addNodeToCache(e)}))}))}}),Object.defineProperty(t.prototype,"notifyDied",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.identifierAttribute){var t=e.identifier,r=this.cache.get(t);r&&(r.remove(e),r.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}}}),Object.defineProperty(t.prototype,"splitCache",{enumerable:!1,configurable:!0,writable:!0,value:function(r){var n,i=this,o=new t,a=r.path;return(n=this.cache,Nr(n)?$t(n).map((function(e){return[e,n[e]]})):Pr(n)?$t(n).map((function(e){return[e,n.get(e)]})):xr(n)?Array.from(n.entries()):yr(n)?n.map((function(e,t){return[t,e]})):void e(7)).forEach((function(e){for(var t=on(e,2),r=t[0],n=t[1],s=!1,u=n.length-1;u>=0;u--)0===n[u].path.indexOf(a)&&(o.addNodeToCache(n[u],!1),n.splice(u,1),s=!0);s&&i.updateLastCacheModificationPerId(r)})),o}}),Object.defineProperty(t.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);return!!r&&r.some((function(t){return e.isAssignableFrom(t.type)}))}}),Object.defineProperty(t.prototype,"resolve",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);if(!r)return null;var n=r.filter((function(t){return e.isAssignableFrom(t.type)}));switch(n.length){case 0:return null;case 1:return n[0];default:throw Jn("Cannot resolve a reference to type '"+e.name+"' with id: '"+t+"' unambigously, there are multiple candidates: "+n.map((function(e){return e.path})).join(", "))}}}),t}();function Ln(e,t,r,n,i){var o=Gn(i);if(o){if(o.parent)throw Jn("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:"")+"/"+r+"', but it lives already at '"+o.path+"'");return t&&o.setParent(t,r),o}return new yn(e,t,r,n,i)}function $n(e,t,r,n,i){return new pn(e,t,r,n,i)}function Hn(e){return!(!e||!e.$treenode)}function Bn(e){if(!Hn(e))throw Jn("Value "+e+" is no MST Node");return e.$treenode}function Gn(e){return e&&e.$treenode||null}function Kn(){return Bn(this).snapshot}function qn(e,t,r){void 0===r&&(r=!0);for(var n=e,i=0;i0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"register",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return void 0===t&&(t=!1),t?this.handlers.unshift(e):this.handlers.push(e),function(){r.unregister(e)}}}),Object.defineProperty(e.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.handlers.indexOf(e)>=0}}),Object.defineProperty(e.prototype,"unregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}),Object.defineProperty(e.prototype,"clear",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.handlers.length=0}}),Object.defineProperty(e.prototype,"emit",{enumerable:!1,configurable:!0,writable:!0,value:function(){for(var e=[],t=0;t0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._determineIdentifierMode(),Ln(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"_determineIdentifierMode",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.identifierMode===gi.UNKNOWN){var e=[];if(_i(this._subType,e)){var t=void 0;e.forEach((function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw Jn("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=gi.YES,this.mapIdentifierAttribute=t):this.identifierMode=gi.NO}}}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t={});var r=e.type._subType,n={};return Object.keys(t).forEach((function(i){n[i]=r.instantiate(e,i,void 0,t[i])})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return new wi(e)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){zt(t,e.unbox),e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=Tn(t,e,n);si(t,e,i)}))})),Ft(t,this.willChange),Kt(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"Map"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Ht(e.storedValue)}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e.storedValue.get(""+t);if(!r)throw Jn("Not a child "+t);return r}}),Object.defineProperty(t.prototype,"willChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Bn(e.object),r=e.name;t.assertWritable({subpath:r});var n=t.type,i=n._subType;switch(e.type){case"update":var o=e.newValue;if(o===e.object.get(r))return null;Un(i,o),e.newValue=i.reconcile(t.getChildNode(r),e.newValue,t,r),n.processIdentifier(r,e.newValue);break;case"add":Un(i,e.newValue),e.newValue=i.instantiate(t,r,void 0,e.newValue),n.processIdentifier(r,e.newValue)}return e}}),Object.defineProperty(t.prototype,"processIdentifier",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.identifierMode===gi.YES&&t instanceof yn){var r=t.identifier;if(r!==e)throw Jn("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '"+r+"', but expected: '"+e+"'")}}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return e.getChildren().forEach((function(e){t[e.subpath]=e.snapshot})),t}}),Object.defineProperty(t.prototype,"processInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return Object.keys(e).forEach((function(r){t[r]=e[r].getSnapshot()})),t}}),Object.defineProperty(t.prototype,"didChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Bn(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:bi(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:bi(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":var r=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:bi(e.name),oldValue:r},t)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=e.storedValue;switch(r.op){case"add":case"replace":n.set(t,r.value);break;case"remove":n.delete(t)}}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Un(this,t);var r=e.storedValue,n={};if(Array.from(r.keys()).forEach((function(e){n[e]=!1})),t)for(var i in t)r.set(i,t[i]),n[""+i]=!0;Object.keys(n).forEach((function(e){!1===n[e]&&r.delete(e)}))}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return ii(e)?Rn(Object.keys(e).map((function(n){return r._subType.validate(e[n],Dn(t,n,r._subType))}))):Vn(t,e,"Value is not a plain object")}}),Object.defineProperty(t.prototype,"getDefaultSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return Xn}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){e.storedValue.delete(t)}}),t}(wn);Oi.prototype.applySnapshot=Ot(Oi.prototype.applySnapshot);var ji=function(e){function t(t,r,n){void 0===n&&(n=[]);var i=e.call(this,t)||this;return Object.defineProperty(i,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Array}),Object.defineProperty(i,"hookInitializers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),i.hookInitializers=n,i}return tn(t,e),Object.defineProperty(t.prototype,"hooks",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var r=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return Ln(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t=[]);var r=e.type._subType,n={};return t.forEach((function(t,i){var o=""+i;n[o]=r.instantiate(e,o,void 0,t)})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Oe.array(Wn(e),Zn)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Gr(t).dehancer=e.unbox,e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=Tn(t,e,n);si(t,e,i)}))})),Ft(t,this.willChange),Kt(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType.describe()+"[]"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.slice()}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=Number(t);if(r=0;r--)t.emitPatch({op:"remove",path:""+(e.index+r),oldValue:e.removed[r].snapshot},t);for(r=0;r0)return r;var n=Hn(e)?Bn(e).snapshot:e;return this._predicate(n)?Nn():Vn(t,e,this._message(e))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(_n);var Gi=function(e){function t(t,r,n){var i=e.call(this,t)||this;return Object.defineProperty(i,"_types",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"_dispatcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"_eager",{enumerable:!0,configurable:!0,writable:!0,value:!0}),n=rn({eager:!0,dispatcher:void 0},n),i._dispatcher=n.dispatcher,n.eager||(i._eager=!1),i}return tn(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){var e=bn.Union;return this._types.forEach((function(t){e|=t.flags})),e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._types.some((function(t){return t.isAssignableFrom(e)}))}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"("+this._types.map((function(e){return e.describe()})).join(" | ")+")"}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(n,void 0);if(!i)throw Jn("No matching type for union "+this.describe());return i.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(t,e.type);if(!i)throw Jn("No matching type for union "+this.describe());return i.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"determineType",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter((function(e){return e!==t})).find((function(t){return t.is(e)})):this._types.find((function(t){return t.is(e)}))}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);for(var r=[],n=0,i=0;i=0){var i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,r,i)}return this._subtype.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),r,n)}}),Object.defineProperty(t.prototype,"getDefaultInstanceOrSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&Un(this,e),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this.optionalValues.indexOf(e)>=0?Nn():this._subtype.validate(e,t)}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._subtype.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(_n);function Wi(e,t,r){return function(e,t){if("function"!=typeof t&&Hn(t))throw Jn("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}(0,t),new qi(e,t,r||Yi)}var Yi=[void 0],Qi=Wi(zi,void 0),Xi=Wi(Mi,null);function Zi(e){return Ki(e,Qi)}var Ji=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"_definition",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n}return tn(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return(this._subType?this._subType.flags:0)|bn.Late},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSubType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(!this._subType){var t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw Jn("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e?e.name:""}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.getSubType(!1);return r?r.validate(e,t):Nn()}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e||gn}}),t}(_n);var eo=function(e){function t(t){var r=e.call(this,t?"frozen("+t.name+")":"frozen")||this;return Object.defineProperty(r,"subType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Frozen}),r}return tn(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return""}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return $n(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return function(e){return"function"!=typeof e}(e)?this.subType?this.subType.validate(e,t):Nn():Vn(t,e,"Value is not serializable and cannot be frozen")}}),t}(On),to=new eo;var ro=function(){function e(e,t){if(Object.defineProperty(this,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolvedReference",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),bo(e))this.identifier=e;else{if(!Hn(e))throw Jn("Can only store references to tree nodes or identifiers, got: '"+e+"'");var r=Bn(e);if(!r.identifierAttribute)throw Jn("Can only store references with a defined identifier attribute.");var n=r.unnormalizedIdentifier;if(null==n)throw Jn("Can only store references to tree nodes with a defined identifier.");this.identifier=n}}return Object.defineProperty(e.prototype,"updateResolvedReference",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=ho(this.identifier),r=e.root,n=r.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==n){var i=this.targetType,o=r.identifierCache.resolve(i,t);if(!o)throw new no("[mobx-state-tree] Failed to resolve reference '"+this.identifier+"' to type '"+this.targetType.name+"' (from node: "+e.path+")");this.resolvedReference={node:o,lastCacheModification:n}}}}),Object.defineProperty(e.prototype,"resolvedValue",{get:function(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value},enumerable:!1,configurable:!0}),e}(),no=function(e){function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return tn(t,e),t}(Error),io=function(e){function t(t,r){var n=e.call(this,"reference("+t.name+")")||this;return Object.defineProperty(n,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"onInvalidated",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Reference}),n}return tn(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.targetType.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return bo(e)?Nn():Vn(t,e,"Value is not a valid identifier, which is a string or a number")}}),Object.defineProperty(t.prototype,"fireInvalidated",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=t.parent;if(i&&i.isAlive){var o=i.storedValue;o&&this.onInvalidated({cause:e,parent:o,invalidTarget:n?n.storedValue:void 0,invalidId:r,replaceRef:function(e){un(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef:function(){!function(e){return jn(e)&&(e.flags&bn.Object)>0}(i.type)?un(t.root.storedValue,{op:"remove",path:t.path}):this.replaceRef(void 0)}})}}}),Object.defineProperty(t.prototype,"addTargetNodeWatcher",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this,n=this.getValue(e);if(n){var i=Bn(n),o=function(n,o){var a=function(e){switch(e){case Jr.beforeDestroy:return"destroy";case Jr.beforeDetach:return"detach";default:return}}(o);a&&r.fireInvalidated(a,e,t,i)},a=i.registerHook(Jr.beforeDetach,o),s=i.registerHook(Jr.beforeDestroy,o);return function(){a(),s()}}}}),Object.defineProperty(t.prototype,"watchTargetNodeForInvalidations",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=this;if(this.onInvalidated){var i;e.registerHook(Jr.beforeDestroy,(function(){i&&i()}));var o=function(o){i&&i();var a=e.parent,s=a&&a.storedValue;if(a&&a.isAlive&&s){(r?!!r.get(t,s):e.root.identifierCache.has(n.targetType,ho(t)))?i=n.addTargetNodeWatcher(e,t):o||n.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===Mn.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(Jr.afterCreationFinalization,(function(){e.parent&&e.parent.createObservableInstanceIfNeeded()})),e.registerHook(Jr.afterAttach,(function(){o(!1)})))}}}),t}(On),oo=function(e){function t(t,r){return e.call(this,t,r)||this}return tn(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return e.storedValue.resolvedValue}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.identifier}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Hn(n)?Bn(n).identifier:n,o=new ro(n,this.targetType),a=$n(this,e,t,r,o);return o.node=a,this.watchTargetNodeForInvalidations(a,i,void 0),a}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!e.isDetaching&&e.type===this){var i=Hn(t),o=e.storedValue;if(!i&&o.identifier===t||i&&o.resolvedValue===t)return e.setParent(r,n),e}var a=this.instantiate(r,n,void 0,t);return e.die(),a}}),t}(io),ao=function(e){function t(t,r,n){var i=e.call(this,t,n)||this;return Object.defineProperty(i,"options",{enumerable:!0,configurable:!0,writable:!0,value:r}),i}return tn(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Hn(n)?this.options.set(n,e?e.storedValue:null):n,o=$n(this,e,t,r,i);return this.watchTargetNodeForInvalidations(o,i,this.options),o}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Hn(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===i)return e.setParent(r,n),e;var o=this.instantiate(r,n,void 0,i);return e.die(),o}}),t}(io);function so(e,t){var r=t||void 0,n=t?t.onInvalidated:void 0;return r&&(r.get||r.set)?new ao(e,{get:r.get,set:r.set},n):new oo(e,n)}var uo=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"validType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Identifier}),n}return tn(t,e),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!(e&&e.type instanceof ki))throw Jn("Identifier types can only be instantiated as direct child of a model type");return $n(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(e.storedValue!==t)throw Jn("Tried to change identifier from '"+e.storedValue+"' to '"+t+"'. Changing identifiers is not allowed.");return e.setParent(r,n),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return typeof e!==this.validType?Vn(t,e,"Value is not a valid "+this.describe()+", expected a "+this.validType):Nn()}}),t}(On),co=function(e){function t(){var t=e.call(this,"identifier","string")||this;return Object.defineProperty(t,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Identifier}),t}return tn(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifier"}}),t}(uo),lo=function(e){function t(){return e.call(this,"identifierNumber","number")||this}return tn(t,e),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifierNumber"}}),t}(uo),fo=new co,po=new lo;function ho(e){return""+e}function bo(e){return"string"==typeof e||"number"==typeof e}var vo,yo=function(e){function t(t){var r=e.call(this,t.name)||this;return Object.defineProperty(r,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Custom}),r}return tn(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.options.isTargetType(e))return Nn();var r=this.options.getValidationMessage(e);return r?Vn(t,e,"Invalid value for type '"+this.name+"': "+r):Nn()}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.options.toSnapshot(e.storedValue)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return $n(this,e,t,r,this.options.isTargetType(n)?n:this.options.fromSnapshot(n,e&&e.root.environment))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=!this.options.isTargetType(t);if(!e.isDetaching&&(e.type===this&&(i?t===e.snapshot:t===e.storedValue)))return e.setParent(r,n),e;var o=i?this.options.fromSnapshot(t,r.root.environment):t,a=this.instantiate(r,n,void 0,o);return e.die(),a}}),t}(On),go={enumeration:function(e,t){var r="string"==typeof e?t:e,n=Ki.apply(void 0,an(r.map((function(e){return Hi(""+e)}))));return"string"==typeof e&&(n.name=e),n},model:function(){for(var e=[],t=0;t",e)},array:function(e){return new ji(e.name+"[]",e)},frozen:function(e){return 0===arguments.length?to:jn(e)?new eo(e):Wi(to,e)},identifier:fo,identifierNumber:po,late:function(e,t){var r="string"==typeof e?e:"late("+e.toString()+")";return new Ji(r,"string"==typeof e?t:e)},undefined:zi,null:Mi,snapshotProcessor:function(e,t,r){return new yi(e,t,r)}},mo=new Uint8Array(16);function _o(){if(!vo&&!(vo="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vo(mo)}var wo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Oo(e){return"string"==typeof e&&wo.test(e)}for(var jo=[],Po=0;Po<256;++Po)jo.push((Po+256).toString(16).substr(1));function So(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(jo[e[t+0]]+jo[e[t+1]]+jo[e[t+2]]+jo[e[t+3]]+"-"+jo[e[t+4]]+jo[e[t+5]]+"-"+jo[e[t+6]]+jo[e[t+7]]+"-"+jo[e[t+8]]+jo[e[t+9]]+"-"+jo[e[t+10]]+jo[e[t+11]]+jo[e[t+12]]+jo[e[t+13]]+jo[e[t+14]]+jo[e[t+15]]).toLowerCase();if(!Oo(r))throw TypeError("Stringified UUID is invalid");return r}function Ao(e,t,r){var n=(e=e||{}).random||(e.rng||_o)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return So(n)}function xo(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function Eo(e,t){return e<>>32-t}var To=function(e,t,r){function n(e,n,i,o){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}(n)),16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var a=new Uint8Array(16+e.length);if(a.set(n),a.set(e,n.length),(a=r(a))[6]=15&a[6]|t,a[8]=63&a[8]|128,i){o=o||0;for(var s=0;s<16;++s)i[o+s]=a[s];return i}return So(a)}try{n.name=e}catch(e){}return n.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",n.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",n}("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i>>0;m=g,g=y,y=Eo(v,30)>>>0,v=d,d=O}r[0]=r[0]+d>>>0,r[1]=r[1]+v>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+g>>>0,r[4]=r[4]+m>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]})); +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - /** - * EventHub 是一个事件处理中心,用于事件的接收与派发 - */ - - class EventHub { - all = new Map(); - constructor(eventMap = {}, bindThis = null) { - this.bindThis = bindThis || globalThis; - this.on(eventMap); - - // createSource$ 创建一个 rxjs 流的源头监听相应的事件 - this.createSource$ = memoize((eventName) => { - return fromEventPattern( - (handle) => this.on(eventName, handle), - (handle) => this.off(eventName, handle), - ).pipe(share()); - }); - } - - /** - * #on 是单个事件绑定函数,type 与 handle 函数一一对应 - */ - #on(type, handler) { - const handlers = this.all.get(type); - // ! 注意,栈的结构,这里要使用 unshift 将元素插入到头部,这样触发的时候才会最后执行最先声明的函数作为默认函数 - // 栈的结构可以保证 在 destroy 事件的时候,首先定义的 destroy 可以最后执行,保证后面绑定 destroy 事件的函数可以先触发,而在 destroy 的定义函数中可以最后 off('*') 解除事件 - handlers ? handlers.unshift(handler) : this.all.set(type, [handler]); - } - - /** - * on 函数重载,第一个参数可以为一个事件绑定对象, - * on({eventName: callback }) - * on({eventName: [callback] }) - * on(type,handle) - */ - on(type, handler) { - // 函数重载 - if (typeof type === 'string') { - this.#on(type, handler); - } else if (type instanceof Object) { - // 在直接赋值为一个 - Object.entries(type).forEach(([key, value]) => { - if (value instanceof Array) { - value.forEach((item) => this.#on(key, item)); - } else if (value instanceof Function) { - this.#on(key, value); - } - }); - } - } - - /** - * off 函数 type 设置为 '*' 时删除所有函数 - */ - off(type, handler) { - if (type === '*') { - return this.all.clear(); - } else { - const handlers = this.all.get(type); - if (handlers) { - return handler ? handlers.splice(handlers.indexOf(handler) >>> 0, 1) : this.all.set(type, []); - } - return false; - } - } - emit(type, ...eventParams) { - const handlers = this.all.get(type); - return handlers - ? handlers.map((handler) => { - return handler.apply(this.bindThis, eventParams); - }) - : []; - } - } - - class Task { - _belongTo = null; // 当有 TaskGroup 时,指向 Group - constructor(originData, spiderUUID) { - this.$EventHub = new EventHub({}, this); - // 由 store 验证相关的正确性 - this.$store = createTaskStore({ spiderUUID, originData }); - } - - // Plugin 的汇报口 - $commit(type, ...payload) { - // 遵循内先外后的函数触发 - - const result = this.$store[type](...payload); - this.$EventHub.emit(type, ...payload); - return result; - } - - // 外部系统的监控口 - $on(...args) { - return this.$EventHub.on(...args); - } - $off(...args) { - return this.$EventHub.off(...args); - } - $isSameTask(task) { - return task.$store.spiderUUID === this.$store.spiderUUID && task.$store.uuid === this.$store.uuid; - } - - $destroy() { - this._belongTo = null; - this.$commit('destroy'); // 先通知外部,该 Task 被销毁 - this.$EventHub.off('*'); // 后进行自身销毁 - } - get [Symbol.toStringTag]() { - return 'Task'; - } - } - - /** +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - class TaskGroup extends Task { - constructor(TaskArray, spiderUUID = '00000') { - super({}, TaskArray?.[0]?.spiderUUID || spiderUUID); - this.member = new Set(TaskArray); - this.#linkTask(); - } - #linkTask() { - this.member.forEach((task) => { - task._belongTo = this; - task.$on('destroy', () => this.$removeLink(task)); - }); - } - - // 当第一次 start 的时候,返回的是完全不一样的 Task 的信息 - // 经过第一个 start 之后,所有 Task 中的数据被统一,这个标识改为 true - consume = false; - // Plugin 的汇报口 - $commit(type, ...payload) { - // 扩散事件 Set 类型不能 map - const result = []; - this.member.forEach((task) => result.push(task.$commit(type, ...payload))); - this.$EventHub.emit(type, ...payload); - - if (this.consume) return result[0]; - if (type === 'start') this.consume = true; - return result; - } - // 删除所有的 link - $destroy() { - this.$EventHub.emit('destroy'); // 不进行事件的扩散, 只是自身的报销的消息被传开 - this.$store.destroy(); - const tasks = this.member; - this.member = null; +const Io=go.enumeration("TaskState",["free","pending","complete","error","destroyed"]),Co={anyType:go.custom({name:"any",fromSnapshot:e=>e,toSnapshot:e=>e,isTargetType:()=>!0,getValidationMessage:()=>""})},ko=go.model({uuid:go.string,spiderUUID:go.string,dataSlide:go.array(go.string),dataSlideUUID:go.string,createdAt:go.Date,errorMessage:go.optional(go.string,""),status:Io,updatedAt:go.Date,originData:go.maybe(Co.anyType),output:go.maybe(Co.anyType)}).actions((e=>({$backup:()=>cn(e),$import(e){return Bn(e).applySnapshot(t);var t},start(){if("pending"===e.status)throw new Error("Task 处在 pending 状态");return e.dataSlide=[],e.dataSlideUUID="",e.status="pending",e.output||e.originData},success(t,r){e.status="free",e.output=t,this._addUUIDToDataSlide(r)},complete(t){e.status="complete",this._addUUIDToDataSlide(t)},error(t="",r){e.status="error",e.errorMessage=t,this._addUUIDToDataSlide(r)},destroy(){var t;(t=Bn(e)).isRoot?t.die():t.parent.removeChild(t.subpath)},_addUUIDToDataSlide(t){t&&(e.dataSlide.push(t),e.dataSlideUUID=t)}})));function Do(e){return ko.create(function({spiderUUID:e,originData:t}){return{uuid:Ao(),spiderUUID:e,createdAt:new Date,errorMessage:"",status:"free",updatedAt:new Date,dataSlideUUID:e,dataSlide:[],originData:t,output:null}}(e))} +/*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - return tasks; - } - // 单独删除一个连接 - $removeLink(task) { - this.member.delete(task); - } - get [Symbol.toStringTag]() { - return 'TaskGroup'; - } - } + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - /** + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */var No=function(e,t){return(No=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function Vo(e,t){function r(){this.constructor=e}No(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Ro(e){return"function"==typeof e}var Uo=!1,Mo={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;Uo=e},get useDeprecatedSynchronousErrorHandling(){return Uo}};function zo(e){setTimeout((function(){throw e}),0)}var Fo={closed:!0,next:function(e){},error:function(e){if(Mo.useDeprecatedSynchronousErrorHandling)throw e;zo(e)},complete:function(){}},Lo=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function $o(e){return null!==e&&"object"==typeof e}var Ho=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),Bo=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var r=this,n=r._parentOrParents,i=r._ctorUnsubscribe,o=r._unsubscribe,a=r._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,n instanceof e)n.remove(this);else if(null!==n)for(var s=0;s1)this.connection=null;else{var r=this.connection,n=e._connection;this.connection=null,!n||r&&n!==r||n.unsubscribe()}}else this.connection=null},t}(qo),ca=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subjectFactory=r,n._refCount=0,n._isComplete=!1,n}return Vo(t,e),t.prototype._subscribe=function(e){return this.getSubject().subscribe(e)},t.prototype.getSubject=function(){var e=this._subject;return e&&!e.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype.connect=function(){var e=this._connection;return e||(this._isComplete=!1,(e=this._connection=new Bo).add(this.source.subscribe(new fa(this.getSubject(),this))),e.closed&&(this._connection=null,e=Bo.EMPTY)),e},t.prototype.refCount=function(){return aa()(this)},t}(Jo),la=function(){var e=ca.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:e._subscribe},_isComplete:{value:e._isComplete,writable:!0},getSubject:{value:e.getSubject},connect:{value:e.connect},refCount:{value:e.refCount}}}(),fa=function(e){function t(t,r){var n=e.call(this,t)||this;return n.connectable=r,n}return Vo(t,e),t.prototype._error=function(t){this._unsubscribe(),e.prototype._error.call(this,t)},t.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){var e=this.connectable;if(e){this.connectable=null;var t=e._connection;e._refCount=0,e._subject=null,e._connection=null,t&&t.unsubscribe()}},t}(na),pa=function(e){function t(t,r){var n=e.call(this,t,r)||this;return n.scheduler=t,n.work=r,n.pending=!1,n}return Vo(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var r=this.id,n=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(n,r,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(n,this.id,t),this},t.prototype.requestAsyncId=function(e,t,r){return void 0===r&&(r=0),setInterval(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,t,r){if(void 0===r&&(r=0),null!==r&&this.delay===r&&!1===this.pending)return t;clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,t);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var r=!1,n=void 0;try{this.work(e)}catch(e){r=!0,n=!!e&&e||new Error(e)}if(r)return this.unsubscribe(),n},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,r=t.actions,n=r.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==n&&r.splice(n,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,r){return e.call(this)||this}return Vo(t,e),t.prototype.schedule=function(e,t){return this},t}(Bo)),ha=function(){function e(t,r){void 0===r&&(r=e.now),this.SchedulerAction=t,this.now=r}return e.prototype.schedule=function(e,t,r){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(r,t)},e.now=function(){return Date.now()},e}(),ba=function(e){function t(r,n){void 0===n&&(n=ha.now);var i=e.call(this,r,(function(){return t.delegate&&t.delegate!==i?t.delegate.now():n()}))||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return Vo(t,e),t.prototype.schedule=function(r,n,i){return void 0===n&&(n=0),t.delegate&&t.delegate!==this?t.delegate.schedule(r,n,i):e.prototype.schedule.call(this,r,n,i)},t.prototype.flush=function(e){var t=this.actions;if(this.active)t.push(e);else{var r;this.active=!0;do{if(r=e.execute(e.state,e.delay))break}while(e=t.shift());if(this.active=!1,r){for(;e=t.shift();)e.unsubscribe();throw r}}},t}(ha),da=new Jo((function(e){return e.complete()}));function va(e){return e&&"function"==typeof e.schedule}var ya=function(e){return function(t){for(var r=0,n=e.length;r0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(Ra);function La(e,t,r){return r?La(e,t).pipe(ja((function(e){return Lo(e)?r.apply(void 0,e):r(e)}))):new Jo((function(r){var n,i=function(){for(var e=[],t=0;t=0}function Ha(e,t){return function(r){return r.lift(new Ba(e,t))}}var Ba=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Ga(e,this.predicate,this.thisArg))},e}(),Ga=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.predicate=r,i.thisArg=n,i.count=0,i}return Vo(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(qo);function Ka(e,t,r){void 0===e&&(e=0);var n=-1;return $a(t)?n=Number(t)<1?1:Number(t):va(t)&&(r=t),va(r)||(r=wa),new Jo((function(t){var i=$a(e)?e:+e-r.now();return r.schedule(qa,i,{index:0,period:n,subscriber:t})}))}function qa(e){var t=e.index,r=e.period,n=e.subscriber;if(n.next(t),!n.closed){if(-1===r)return n.complete();e.index=t+1,this.schedule(e,r)}}var Wa="object"==typeof global&&global&&global.Object===Object&&global,Ya="object"==typeof self&&self&&self.Object===Object&&self,Qa=Wa||Ya||Function("return this")(),Xa=Qa.Symbol,Za=Object.prototype,Ja=Za.hasOwnProperty,es=Za.toString,ts=Xa?Xa.toStringTag:void 0;var rs=Object.prototype.toString;var ns=Xa?Xa.toStringTag:void 0;function is(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ns&&ns in Object(e)?function(e){var t=Ja.call(e,ts),r=e[ts];try{e[ts]=void 0;var n=!0}catch(e){}var i=es.call(e);return n&&(t?e[ts]=r:delete e[ts]),i}(e):function(e){return rs.call(e)}(e)}function os(e){return null!=e&&"object"==typeof e}function as(e){return"symbol"==typeof e||os(e)&&"[object Symbol]"==is(e)}function ss(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r0){if(++Is>=800)return arguments[0]}else Is=0;return Ts.apply(void 0,arguments)});function Ns(e){return e!=e}function Vs(e,t){return!!(null==e?0:e.length)&&function(e,t,r){return t==t?function(e,t,r){for(var n=r-1,i=e.length;++n-1}var Rs=/^(?:0|[1-9]\d*)$/;function Us(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&Rs.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}function Bs(e){return os(e)&&"[object Arguments]"==is(e)}var Gs=Object.prototype,Ks=Gs.hasOwnProperty,qs=Gs.propertyIsEnumerable,Ws=Bs(function(){return arguments}())?Bs:function(e){return os(e)&&Ks.call(e,"callee")&&!qs.call(e,"callee")};function Ys(e){return function(t){return e(t)}}var Qs="object"==typeof exports&&exports&&!exports.nodeType&&exports,Xs=Qs&&"object"==typeof module&&module&&!module.nodeType&&module,Zs=Xs&&Xs.exports===Qs&&Wa.process,Js=function(){try{var e=Xs&&Xs.require&&Xs.require("util").types;return e||Zs&&Zs.binding&&Zs.binding("util")}catch(e){}}(),eu=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,tu=/^\w*$/;var ru=As(Object,"create");var nu=Object.prototype.hasOwnProperty;var iu=Object.prototype.hasOwnProperty;function ou(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1},uu.prototype.set=function(e,t){var r=this.__data__,n=au(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};var cu=As(Qa,"Map");function lu(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function fu(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t0&&r(s)?t>1?Ou(s,t-1,r,n,i):mu(i,s):n||(i[i.length]=s)}return i}function ju(e){return(null==e?0:e.length)?Ou(e,1):[]}function Pu(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new fu;++t=200&&(o=Su,a=!1,t=new Pu(t));e:for(;++i0;){var n=t.shift();r.next(n.buffer)}e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){this.contexts=null},t.prototype.onBufferFull=function(e){this.closeContext(e);var t=e.closeAction;if(t.unsubscribe(),this.remove(t),!this.closed&&this.timespanOnly){e=this.openContext();var r=this.bufferTimeSpan,n={subscriber:this,context:e,bufferTimeSpan:r};this.add(e.closeAction=this.scheduler.schedule(zu,r,n))}},t.prototype.openContext=function(){var e=new Uu;return this.contexts.push(e),e},t.prototype.closeContext=function(e){this.destination.next(e.buffer);var t=this.contexts;(t?t.indexOf(e):-1)>=0&&t.splice(t.indexOf(e),1)},t}(qo);function zu(e){var t=e.subscriber,r=e.context;r&&t.closeContext(r),t.closed||(e.context=t.openContext(),e.context.closeAction=this.schedule(e,e.bufferTimeSpan))}function Fu(e){var t=e.bufferCreationInterval,r=e.bufferTimeSpan,n=e.subscriber,i=e.scheduler,o=n.openContext();n.closed||(n.add(o.closeAction=i.schedule(Lu,r,{subscriber:n,context:o})),this.schedule(e,t))}function Lu(e){var t=e.subscriber,r=e.context;t.closeContext(r)}function $u(e){return function(t){var r=new Hu(e),n=t.lift(r);return r.caught=n}}var Hu=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new Bu(e,this.selector,this.caught))},e}(),Bu=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.selector=r,i.caught=n,i}return Vo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=void 0;try{r=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var n=new Va(this);this.add(n);var i=Ua(r,n);i!==n&&this.add(i)}},t}(Ra);function Gu(e,t){return Ma(e,t,1)}function Ku(e,t){return t?function(r){return new Yu(r,t).lift(new qu(e))}:function(t){return t.lift(new qu(e))}}var qu=function(){function e(e){this.delayDurationSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new Wu(e,this.delayDurationSelector))},e}(),Wu=function(e){function t(t,r){var n=e.call(this,t)||this;return n.delayDurationSelector=r,n.completed=!1,n.delayNotifierSubscriptions=[],n.index=0,n}return Vo(t,e),t.prototype.notifyNext=function(e,t,r,n,i){this.destination.next(e),this.removeSubscription(i),this.tryComplete()},t.prototype.notifyError=function(e,t){this._error(e)},t.prototype.notifyComplete=function(e){var t=this.removeSubscription(e);t&&this.destination.next(t),this.tryComplete()},t.prototype._next=function(e){var t=this.index++;try{var r=this.delayDurationSelector(e,t);r&&this.tryDelay(r,e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){this.completed=!0,this.tryComplete(),this.unsubscribe()},t.prototype.removeSubscription=function(e){e.unsubscribe();var t=this.delayNotifierSubscriptions.indexOf(e);return-1!==t&&this.delayNotifierSubscriptions.splice(t,1),e.outerValue},t.prototype.tryDelay=function(e,t){var r=function(e,t,r,n,i){if(void 0===i&&(i=new xa(e,r,n)),!i.closed)return t instanceof Jo?t.subscribe(i):ka(t)(i)}(this,e,t);r&&!r.closed&&(this.destination.add(r),this.delayNotifierSubscriptions.push(r))},t.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()},t}(Aa),Yu=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subscriptionDelay=r,n}return Vo(t,e),t.prototype._subscribe=function(e){this.subscriptionDelay.subscribe(new Qu(e,this.source))},t}(Jo),Qu=function(e){function t(t,r){var n=e.call(this)||this;return n.parent=t,n.source=r,n.sourceSubscribed=!1,n}return Vo(t,e),t.prototype._next=function(e){this.subscribeToSource()},t.prototype._error=function(e){this.unsubscribe(),this.parent.error(e)},t.prototype._complete=function(){this.unsubscribe(),this.subscribeToSource()},t.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))},t}(qo);var Xu=function(){function e(e,t,r){void 0===r&&(r=!1),this.accumulator=e,this.seed=t,this.hasSeed=r}return e.prototype.call=function(e,t){return t.subscribe(new Zu(e,this.accumulator,this.seed,this.hasSeed))},e}(),Zu=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o.accumulator=r,o._seed=n,o.hasSeed=i,o.index=0,o}return Vo(t,e),Object.defineProperty(t.prototype,"seed",{get:function(){return this._seed},set:function(e){this.hasSeed=!0,this._seed=e},enumerable:!0,configurable:!0}),t.prototype._next=function(e){if(this.hasSeed)return this._tryNext(e);this.seed=e,this.destination.next(e)},t.prototype._tryNext=function(e){var t,r=this.index++;try{t=this.accumulator(this.seed,e,r)}catch(e){this.destination.error(e)}this.seed=t,this.destination.next(t)},t}(qo);var Ju=function(){function e(e,t){this.subjectFactory=e,this.selector=t}return e.prototype.call=function(e,t){var r=this.selector,n=this.subjectFactory(),i=r(n).subscribe(e);return i.add(t.subscribe(n)),i},e}();var ec=function(){function e(e,t){this.notifier=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new tc(e,this.notifier,this.source))},e}(),tc=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.notifier=r,i.source=n,i}return Vo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=this.errors,n=this.retries,i=this.retriesSubscription;if(n)this.errors=void 0,this.retriesSubscription=void 0;else{r=new ia;try{n=(0,this.notifier)(r)}catch(t){return e.prototype.error.call(this,t)}i=Ua(n,new Va(this))}this._unsubscribeAndRecycle(),this.errors=r,this.retries=n,this.retriesSubscription=i,r.next(t)}},t.prototype._unsubscribe=function(){var e=this.errors,t=this.retriesSubscription;e&&(e.unsubscribe(),this.errors=void 0),t&&(t.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},t.prototype.notifyNext=function(){var e=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=e,this.source.subscribe(this)},t}(Ra);function rc(){return new ia}function nc(){return function(e){return aa()((t=rc,function(e){var n;if(n="function"==typeof t?t:function(){return t},"function"==typeof r)return e.lift(new Ju(n,r));var i=Object.create(e,la);return i.source=e,i.subjectFactory=n,i})(e));var t,r}}function ic(e,t){return"function"==typeof t?function(r){return r.pipe(ic((function(r,n){return Na(e(r,n)).pipe(ja((function(e,i){return t(r,e,n,i)})))})))}:function(t){return t.lift(new oc(e))}}var oc=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new ac(e,this.project))},e}(),ac=function(e){function t(t,r){var n=e.call(this,t)||this;return n.project=r,n.index=0,n}return Vo(t,e),t.prototype._next=function(e){var t,r=this.index++;try{t=this.project(e,r)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var r=new Va(this),n=this.destination;n.add(r),this.innerSubscription=Ua(e,r),this.innerSubscription!==r&&n.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(Ra);function sc(e,t,r){return function(n){return n.lift(new uc(e,t,r))}}var uc=function(){function e(e,t,r){this.nextOrObserver=e,this.error=t,this.complete=r}return e.prototype.call=function(e,t){return t.subscribe(new cc(e,this.nextOrObserver,this.error,this.complete))},e}(),cc=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o._tapNext=Oa,o._tapError=Oa,o._tapComplete=Oa,o._tapError=n||Oa,o._tapComplete=i||Oa,Ro(r)?(o._context=o,o._tapNext=r):r&&(o._context=r,o._tapNext=r.next||Oa,o._tapError=r.error||Oa,o._tapComplete=r.complete||Oa),o}return Vo(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(qo); +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - /** - * Mirror 是 JSpider 中的数据外放接口 - * - * MessageHub 是集合所有事件的事件中心, - * 当 MessageHub 被 emit 时, MessageHub 发出相关的 Update 进行视图的更新 - * 所有的外放接口使用 rxjs 进行 subscribe - */ - - const MessageHub = new EventHub(); - - // 任何一个 Task 数据发生改变时 - const TaskUpdate = MessageHub.createSource$('TaskUpdate'); - - // ControlPanel 的状态发生改变 - /** - * ControlUpdate - * - * MessageHub.emit('ControlUpdate', payload); - * payload: { - * name:'your message token',// stateChange flowStart flowStop - * value:any, - * } - * - */ - - const ControlUpdate = MessageHub.createSource$('ControlUpdate'); - - /** +class lc{all=new Map;constructor(e={},t=null){this.bindThis=t||globalThis,this.on(e),this.createSource$=pu((e=>La((t=>this.on(e,t)),(t=>this.off(e,t))).pipe(nc())))}#on(e,t){const r=this.all.get(e);r?r.unshift(t):this.all.set(e,[t])}on(e,t){"string"==typeof e?this.#on(e,t):e instanceof Object&&Object.entries(e).forEach((([e,t])=>{t instanceof Array?t.forEach((t=>this.#on(e,t))):t instanceof Function&&this.#on(e,t)}))}off(e,t){if("*"===e)return this.all.clear();{const r=this.all.get(e);return!!r&&(t?r.splice(r.indexOf(t)>>>0,1):this.all.set(e,[]))}}emit(e,...t){const r=this.all.get(e);return r?r.map((e=>e.apply(this.bindThis,t))):[]}}class fc{_belongTo=null;constructor(e,t){this.$EventHub=new lc({},this),this.$store=Do({spiderUUID:t,originData:e})}$commit(e,...t){const r=this.$store[e](...t);return this.$EventHub.emit(e,...t),r}$on(...e){return this.$EventHub.on(...e)}$off(...e){return this.$EventHub.off(...e)}$isSameTask(e){return e.$store.spiderUUID===this.$store.spiderUUID&&e.$store.uuid===this.$store.uuid}$destroy(){this._belongTo=null,this.$commit("destroy"),this.$EventHub.off("*")}get[Symbol.toStringTag](){return"Task"}} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - var staticEvent = { - // ! 即使这些函数不会被使用,也必须使用注释的方式写下 - stateChange(state) { - this.status = state; - MessageHub.emit('ControlUpdate', { - name: 'stateChange', - value: state, - }); - }, - 'Flow:stop'() { - this._stop = true; - MessageHub.emit('ControlUpdate', { - name: 'flowStop', - }); - }, - 'Flow:start'() { - console.log('jspider 开始运行'); - this.status = 'pending'; - this._stop = false; - MessageHub.emit('ControlUpdate', { - name: 'flowStart', - }); - }, - - // 'Flow:input'() {} - // 'Spider:clearFlow'(){} - 'Task:success'(task) { - task.$commit('complete'); - if (task instanceof TaskGroup) { - task.$destroy(); - } - MessageHub.emit('ControlUpdate', { - name: 'TaskSuccess', - }); - }, - 'Task:error'(error) { - console.log(error); - }, - // 'Flow:complete'() { - // console.log('线路完成'); - // }, - }; - - /** + */class pc extends fc{constructor(e,t="00000"){super({},e?.[0]?.spiderUUID||t),this.member=new Set(e),this.#linkTask()}#linkTask(){this.member.forEach((e=>{e._belongTo=this,e.$on("destroy",(()=>this.$removeLink(e)))}))}consume=!1;$commit(e,...t){const r=[];return this.member.forEach((n=>r.push(n.$commit(e,...t)))),this.$EventHub.emit(e,...t),this.consume?r[0]:("start"===e&&(this.consume=!0),r)}$destroy(){this.$EventHub.emit("destroy"),this.$store.destroy();const e=this.member;return this.member=null,e}$removeLink(e){this.member.delete(e)}get[Symbol.toStringTag](){return"TaskGroup"}} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - function bindUpdate() { - const backup = this.$store.$backup(); - - MessageHub.emit('TaskUpdate', backup); - } - // ! 用于维护全局 Task 数据的中心 - class TaskManager { - #Tasks = new Map(); // 用于维护所有的 Task - viewModel = []; // 这是放置所有的外部 Mirror 需要监听的对象 - - // 直接代理全局的 task 创建事件,TaskGroup 是不管的,因为 TaskGroup 具有编程场景临时性,一般在 plugin 阶段自己销毁 - // 这好比村长只管理村民人数和状况,但是不管理村民的组织 - createTask(data, pipelineUUID) { - const task = new Task(data, pipelineUUID); - this.#Tasks.set(task.uuid, task); - const that = this; - task.$on({ - start: bindUpdate, - success: bindUpdate, - complete: bindUpdate, - error: bindUpdate, - // 监听事件,并更新响应的 viewModel - destroy() { - that.#Tasks.delete(this.uuid); // this 绑定的是 task - }, - }); - - this.viewModel.push(task.$store); - return task; - } - } - - /** + */const hc=new lc,bc=hc.createSource$("TaskUpdate"),dc=hc.createSource$("ControlUpdate"); +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - /** - * 函数用途描述 - * 这个是用于 async 函数队列 连续执行的函数,只要 enQueue 之后就会连续执行,直至完成 - */ - class functionQueue { - QueuePromise = Promise.resolve(); - enQueue(...args) { - this.QueuePromise = args.reduce((promise, current) => { - return promise.then(current); - }, this.QueuePromise); - return this; - } - } - - /** +var vc={stateChange(e){this.status=e,hc.emit("ControlUpdate",{name:"stateChange",value:e})},"Flow:stop"(){this._stop=!0,hc.emit("ControlUpdate",{name:"flowStop"})},"Flow:start"(){console.log("jspider 开始运行"),this.status="pending",this._stop=!1,hc.emit("ControlUpdate",{name:"flowStart"})},"Task:success"(e){e.$commit("complete"),e instanceof pc&&e.$destroy(),hc.emit("ControlUpdate",{name:"TaskSuccess"})},"Task:error"(e){console.log(e)}}; +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - /** - * pauseToggle - * @date 2021-07-20 - * @author KonghaYao - * @description 用于暂停的 operator, 改编自 bufferToggle 但也不同 - * @param {Observable} openings 发出时触发主流缓存 - * @param {Observable} closings 发出时放出缓存到主流 - * @return {function} - */ - function pauseToggle(openings, closings) { - return (observable) => - new Observable((subscriber) => { - const buffers = new Set(); - let closingSubscription = false; - const subscription = observable.subscribe( - (value) => { - closingSubscription ? buffers.add(value) : subscriber.next(value); - }, - noop, - () => { - buffers.forEach((item) => subscriber.next(item)); - subscriber.complete(); - }, - ); - const openingSubscription = openings.subscribe(() => { - // 输出所有的 buffer - const emitBuffer = () => { - buffers.forEach((item) => subscriber.next(item)); - buffers.clear(); - closingSubscription.unsubscribe(); - closingSubscription = false; - }; - closingSubscription = closings.subscribe(emitBuffer); - }); - return () => { - buffers.clear(); - subscription.unsubscribe(); - openingSubscription.unsubscribe(); - if (closingSubscription) closingSubscription.unsubscribe(); - }; - }); - } - - /** + */function yc(){const e=this.$store.$backup();hc.emit("TaskUpdate",e)}class gc{#Tasks=new Map;viewModel=[];createTask(e,t){const r=new fc(e,t);this.#Tasks.set(r.uuid,r);const n=this;return r.$on({start:yc,success:yc,complete:yc,error:yc,destroy(){n.#Tasks.delete(this.uuid)}}),this.viewModel.push(r.$store),r}} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - function createUUID(string) { - return v5(string, v5.URL); - } - - /** + */class mc{QueuePromise=Promise.resolve();enQueue(...e){return this.QueuePromise=e.reduce(((e,t)=>e.then(t)),this.QueuePromise),this}} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - // Pipeline 是组合 Plugin 实例的工具类,用于创建一个可以不断提供 source 进行固定操作的功能对象。 - class Pipeline { - constructor(Plugins) { - this.Plugins = Plugins; - } - UUID = null; // 唯一的标识 - operator = null; // 组合起来的最终的 operator - pluginUUIDMap = new Map(); - - #PluginQueue = new functionQueue(); // 准备 Plugin 中的异步 init 事件 - preparePipeline() { - let uuidString = ''; - // ! 一次遍历实现取出 operator 和 导出 plugin init 函数的 promise 链,并延长 uuidString 用于创建 UUID - const pipeline = this.Plugins.map((plugin, index) => { - // main 属性和 operator 属性必须存在一个来保证能够生成 uuid - uuidString += (plugin?.main || plugin.operator).toString(); - - if (plugin.init instanceof Function) { - this.#PluginQueue.enQueue(plugin.init); - } - - // 需要注入 index 表示这个程序的位置 - plugin.initUUID(index); - - // 保存 uuid 的映射 - this.pluginUUIDMap.set(plugin.uuid, plugin?.name || plugin.uuid); - - // 将 plugin 中的 operator 注入 pipeline 中 - return plugin.operator(this); - }); - this.operator = pipe(...pipeline); - - this.UUID = createUUID(uuidString); - - return this.#PluginQueue.QueuePromise; - } - } - - /** +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - // ControlPanel 是 JSpider 内部的事件和数据中心。 - // 全部 JSpider 涉及到的边界中,ControlPanel 只有一个,但是 View 可以有多个,而 Spider 就是 View 中的一个 - // 用于分发数据流,提供 Task 的状态变更。 - // TODO 并且可以提供数据的响应给类似于 UI 界面形成可视化 - - class ControlPanel$1 { - status = 'free'; // 'free' 'preparing' - #runningQueue = new functionQueue(); // 异步 Queue 队列 - _stop = false; // 用于直接切断 spiderSource$ 的流 - spiderSource$ = null; - _pipeline = null; - TaskManager = new TaskManager(); - constructor() { - this.$EventHub = new EventHub(staticEvent, this); - } - // ! 这是一个完整的流控 - _createLogicLine() { - this.spiderSource$ = this.$EventHub.createSource$('Flow:input').pipe( - pauseToggle( - this.$EventHub.createSource$('Flow:stop'), - - this.$EventHub.createSource$('Flow:start'), - ), - this._pipeline.operator, - ); - - this.spiderSource$.subscribe( - // 所有的事件分配到 staticEvent 中去写 - (task) => this.$EventHub.emit('Task:success', task), - (error) => this.$EventHub.emit('Task:error', error), - () => this.$EventHub.emit('Flow:complete'), - ); - this.$EventHub.emit('Flow:stop'); - } - - pipeline(...plugins) { - const pipeline = new Pipeline(plugins); - if (this.status === 'free') { - this.$EventHub.emit('stateChange', 'preparing'); - this._pipeline = pipeline; - this.#runningQueue.enQueue( - () => this._pipeline.preparePipeline(), - () => { - this.$EventHub.emit('Spider:clearFlow'); // 先注销流 - this._createLogicLine(); // 创建新流 - this.$EventHub.emit('stateChange', 'free'); - }, - ); - } else { - throw new Error('在运行阶段是不能够进行操作的哦'); - } - } - - // |startInfo| - TaskManager.createTask -> |Task| - emit EventHub -> |Flow| - createFlow(infos, { fromBackup = false } = {}) { - return this.#runningQueue.enQueue(() => { - infos.forEach((info) => { - if (!this._pipeline) throw new Error('没有创建pipeline'); - const task = this.TaskManager.createTask(info, this._pipeline.UUID); - if (fromBackup) task.$store.$import(info); - this.$EventHub.emit('Flow:input', task); - }); - }); - } - - startFlow() { - // 开始流必须要等待其他事件完成 - this.#runningQueue.enQueue(() => { - this.$EventHub.emit('Flow:start'); - }); - } - - stopFlow() { - // 关闭流不需要等待其他事件完成 - this.$EventHub.emit('Flow:stop'); - } - } - - /** +function _c(e){return To(e,To.URL)} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - var ControlPanel = new ControlPanel$1(); - - // 注意,这里只要 View 被实例化了,它就会订阅数据 - class View { - constructor({ tasks = false, controlPanel = false } = {}) { - this.config = { - tasks, - controlPanel, - }; - - if (tasks) { - this.#subscriber.push(TaskUpdate.subscribe((data) => this._update(data))); - } - if (controlPanel) { - this.#subscriber.push(ControlUpdate.subscribe((data) => this._change(data))); - } - } - config = {}; - #subscriber = []; - $destroy() { - this.#subscriber.forEach((sub) => { - sub.unsubscribe(); - }); - } - } - - class ConsoleView extends View { - constructor(config) { - super(Object.assign(config, { tasks: true, controlPanel: true })); - } - tasks = []; - #uuidArray = []; - _update(data) { - const index = this.#uuidArray.indexOf(data.uuid); - if (index === -1) { - this.#uuidArray.push(data.uuid); - this.tasks.push(data); - } else { - // 并不是直接赋值,而是通过数组的 splice 方式进行数组的更新,这样可以方便 Vue 渲染 - this.tasks.splice(index, 1, data); - } - } - _change({ name, value = '' }) {} - } - - /** + */class wc{constructor(e){this.Plugins=e}UUID=null;operator=null;pluginUUIDMap=new Map;#PluginQueue=new mc;preparePipeline(){let e="";const t=this.Plugins.map(((t,r)=>(e+=(t?.main||t.operator).toString(),t.init instanceof Function&&this.#PluginQueue.enQueue(t.init),t.initUUID(r),this.pluginUUIDMap.set(t.uuid,t?.name||t.uuid),t.operator(this))));return this.operator=Xo(...t),this.UUID=_c(e),this.#PluginQueue.QueuePromise}} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - // Spider 是一个 View - class Spider { - constructor({ logEvery = false } = {}) { - this.config = { - logEvery, - }; - this.views = new ConsoleView(this.config); - } - crawl(...args) { - ControlPanel.createFlow(args.flat()); - return this; - } - pipeline(...plugins) { - ControlPanel.pipeline(...plugins); - return this; - } - start() { - ControlPanel.startFlow(); - return this; - } - stop() { - ControlPanel.stopFlow(); - return this; - } - } - - /** +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - // Plugin main 函数发生了错误 - class PluginError extends Error { - constructor(message) { - super(message); - this.name = 'PluginError'; - } - } - - // 重试的时候发生了错误 - class RetryError extends Error { - constructor(message) { - super(message); - this.name = 'FlowError'; - } - } - - /** +var Oc=new class{status="free";#runningQueue=new mc;_stop=!1;spiderSource$=null;_pipeline=null;TaskManager=new gc;constructor(){this.$EventHub=new lc(vc,this)}_createLogicLine(){var e,t;this.spiderSource$=this.$EventHub.createSource$("Flow:input").pipe((e=this.$EventHub.createSource$("Flow:stop"),t=this.$EventHub.createSource$("Flow:start"),r=>new Jo((n=>{const i=new Set;let o=!1;const a=r.subscribe((e=>{o?i.add(e):n.next(e)}),Oa,(()=>{i.forEach((e=>n.next(e))),i.clear(),n.complete()})),s=e.subscribe((()=>{o=t.subscribe((()=>{i.forEach((e=>n.next(e))),i.clear(),o.unsubscribe(),o=!1}))}));return()=>{i.clear(),a.unsubscribe(),s.unsubscribe(),o&&o.unsubscribe()}}))),this._pipeline.operator),this.spiderSource$.subscribe((e=>this.$EventHub.emit("Task:success",e)),(e=>this.$EventHub.emit("Task:error",e)),(()=>this.$EventHub.emit("Flow:complete"))),this.$EventHub.emit("Flow:stop")}pipeline(...e){const t=new wc(e);if("free"!==this.status)throw new Error("在运行阶段是不能够进行操作的哦");this.$EventHub.emit("stateChange","preparing"),this._pipeline=t,this.#runningQueue.enQueue((()=>this._pipeline.preparePipeline()),(()=>{this.$EventHub.emit("Spider:clearFlow"),this._createLogicLine(),this.$EventHub.emit("stateChange","free")}))}createFlow(e,{fromBackup:t=!1}={}){return this.#runningQueue.enQueue((()=>{e.forEach((e=>{if(!this._pipeline)throw new Error("没有创建pipeline");const r=this.TaskManager.createTask(e,this._pipeline.UUID);t&&r.$store.$import(e),this.$EventHub.emit("Flow:input",r)}))}))}startFlow(){this.#runningQueue.enQueue((()=>{this.$EventHub.emit("Flow:start")}))}stopFlow(){this.$EventHub.emit("Flow:stop")}};class jc extends class{constructor({tasks:e=!1,controlPanel:t=!1}={}){this.config={tasks:e,controlPanel:t},e&&this.#subscriber.push(bc.subscribe((e=>this._update(e)))),t&&this.#subscriber.push(dc.subscribe((e=>this._change(e))))}config={};#subscriber=[];$destroy(){this.#subscriber.forEach((e=>{e.unsubscribe()}))}}{constructor(e){super(Object.assign(e,{tasks:!0,controlPanel:!0}))}tasks=[];#uuidArray=[];_update(e){const t=this.#uuidArray.indexOf(e.uuid);-1===t?(this.#uuidArray.push(e.uuid),this.tasks.push(e)):this.tasks.splice(t,1,e)}_change({name:e,value:t=""}){}} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - class PLUGIN$1 { - constructor({ - forceRetry = true, - saveResult = false, - name = null, - main, - init = null, - error = null, - complete = null, - options = {}, - operator, - }) { - if (operator) this.operator = operator; - // 写入自身中 - Object.assign(this, { - name, // 名称,一般用作提示标记 - main, // Plugin 中的功能性函数 - init, // 初始化整个 Plugin 的函数 - error, // operator 错误时的事件,若返回 false 类的数据,将会中断流,返回正常数据会继续流 - complete, // 函数完成时的提示事件 - options, // main 函数接收的 options - saveResult, // 是否保存结果到每一个 Task 中 - forceRetry, // 是否强制重新使用 Plugin - }); - } - initUUID(index) { - this.uuid = createUUID((this?.main || this.operator).toString() + index); - } - // 对 main 函数外包一层,直接启动 main 函数的执行,返回一条流 - TaskStarter(task) { - return of(task).pipe( - // 设置跳过 Plugin 的逻辑 - switchMap((task) => { - return of(task).pipe( - map((task) => [task.$commit('start', this.uuid), task._originData]), - - switchMap(([data, originData]) => { - const result = this.main(data, originData); - return result instanceof Promise || result instanceof Observable ? from$1(result) : of(result); - }), - map((result) => { - task.$commit('success', result, this.uuid, this.saveResult); - return task; - }), - ); - }), - // 捕获到异常 - catchError((...args) => { - if (this.error instanceof Function) { - const afterError = this.error(task, ...args); - if (afterError) throw new PluginError(afterError); - - return EMPTY; - } - throw new PluginError(args[0]); - }), - // 完成 Plugin 时的事件 - tap((task) => this.complete && this.complete(task)), - ); - } - - operator(context) { - // ! 这个是默认的 operator 函数 - // context 为上层的 JSpider 实例 - return pipe(switchMap((task) => this.TaskStarter(task))); - } - } - - function Plugin$1(Process, otherOptions = {}) { - if (Process instanceof Function) { - return new PLUGIN$1( - Object.assign(otherOptions, { - main: Process, - }), - ); - } - if (Process instanceof Object) { - return new PLUGIN$1(Process); - } - throw new PluginError('Plugin 必须是一个函数或者是 Plugin 描述对象'); - } - - /** +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - // delay 可以是一个函数用于产生数字 - const retryAndDelay = (count, delay) => - pipe( - retryWhen((err$) => - err$.pipe( - scan((errCount, err) => { - console.log('尝试次数', errCount, err); - if (errCount >= count) throw new RetryError('超出尝试次数', err); - return errCount + 1; - }, 0), - delayWhen((...args) => { - switch (typeof delay) { - case 'string': - case 'number': - return timer(parseInt(delay, 10)); - case 'function': - return timer(delay(...args)); - default: - throw new RetryError('您输入的 delay 错误'); - } - }), - ), - ), - ); - - /** +class Pc extends Error{constructor(e){super(e),this.name="PluginError"}}class Sc extends Error{constructor(e){super(e),this.name="FlowError"}} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - function concurrent( - promiseFunc, // 并发的异步函数用于接收上流来的数据 - { - retry = 3, // 若发生失败时最大重试次数 - buffer = 3, // 每次并发处理的次数 - delay = 1000, // 每个分组之间的间隔 - retryDelay = 300, // 每次延迟的次数;与 retryAndDelay 相同的一个函数 - handleError = function handleError(err, err$) { - // 重试错误时的操作 - throw new Error(err, err$); - }, - } = {}, - ) { - // 异步函数的处理工作 - const asyncSingle = (data) => - of(data).pipe( - mergeMap((res) => { - // mergeMap 可以直接将 Observable 或者是 Promise 转化为正常流 - return promiseFunc(res); - }), - retryAndDelay(retry, retryDelay), - catchError((...args) => { - // 自定义错误处理 - const clear = handleError instanceof Function ? handleError(...args) : handleError; - - return clear || EMPTY; // 通过 EMPTY 取消掉这个订阅 - }), - ); - - // 这是 concurrent 的核心逻辑 - return pipe( - // ! 这里的 bufferTime 的第二个参数保持 undefined 即可 - bufferTime(1000, undefined, buffer), - filter((i) => i.length), - // 无论如何每一组都会被推迟的时间量 - delayWhen((_, index) => timer(index * delay)), - mergeMap((array) => from$1(array)), - concatMap(asyncSingle), - ); - } - - /** + */class Ac{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=_c((this?.main||this.operator).toString()+e)}TaskStarter(e){return _a(e).pipe(ic((e=>_a(e).pipe(ja((e=>[e.$commit("start",this.uuid),e._originData])),ic((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Jo?Na(r):_a(r)})),ja((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),$u(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new Pc(r);return da}throw new Pc(t[0])})),sc((e=>this.complete&&this.complete(e))))}operator(e){return Xo(ic((e=>this.TaskStarter(e))))}}function xc(e,t={}){if(e instanceof Function)return new Ac(Object.assign(t,{main:e}));if(e instanceof Object)return new Ac(e);throw new Pc("Plugin 必须是一个函数或者是 Plugin 描述对象")} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - // ! 这个 Request 文件是标准的 Plugin 的高级注册示例 - - // Format 是边缘的处理逻辑,用于自动化相应返回数据的格式处理,与 Plugin 关系较小 - function Format(res, returnType) { - const type = res.headers.get('content-type') || ''; - // 根据 returnType 强制返回 - if (!returnType || returnType === 'auto') { - // 自动判断类型并解析 - if (/text|html|rtf|xml/.test(type)) { - return res.text(); - } - if (/json/.test(type)) { - return res.json(); - } - if (/arrayBuffer/.test(type)) { - return res.arrayBuffer(); - } - // 默认返回 Blob 数据 配合 node端 的buffer - return res.buffer ? res.buffer() : res.blob(); - } - if (returnType) { - return res[returnType](); - } - return res.json(); - } - - // Plugin 的核心函数 (this.main),用于请求 - // 第一参数为 Task 内部使用 start 事件返回的参数,你可以看成是上一个 Plugin 返回给你的数据 - // 第二个为 Plugin 内部的 options, 可以调用这些数据进行操作 - - function request({ url, options = {} }) { - const { returnType = 'json' } = this.options; - - // 获取数据为 request - console.log('- 爬取 ', url); - return fetch(url, options) - .then((res) => { - if (!res.ok) { - throw Error(res.statusText); - } - return Format(res, returnType); - }) - .then((res) => { - console.log(`${url} 爬取成功`); - return res; - }) - .catch((err) => { - throw err; - }); - } - - // 在超过重试次数时,进行的操作 - function HandleError(err) { - throw err; - } - function Request(options = {}) { - return Plugin$1({ - init() {}, // 在所有工作开始前会启动的函数,可以用于 Promise 加载一些 js 插件 - name: 'Request', // 这个 name 是负责进行监控的标志符号 - main: request, // 功能性的核心函数 - options, // 接收所有的参数,提供给所有函数使用 - - operator() { - // 复写 operator 函数,属于高级操作,可以操作到最顶层的数据流环节 - - // 通过 this.options 来获取传入的参数,这个参数解析都是由 Plugin 开发者来设置逻辑的 - // 所以灵活性很高 - const { delay = 200, buffer = 3, retry = 3, handleError = null } = this.options; - - return ($source) => - $source.pipe( - concurrent( - (task) => - // 注意此处的 TaskStarter 是 Plugin 内置的函数, - // 通过这个函数可以直接回应 Task - // 使得 Plugin 开发者 不用学 Task 相关知识, - // 而只是调用一下这个形式就可以了 - // TaskStarter 是用于间接调用 main 函数的 Wrapper 函数, - // 主要是对 Task 进行一些操作 - this.TaskStarter(task), - { - delay, - buffer, - retry, - handleError: handleError || HandleError, - }, - ), - ); - }, - }); - } - - /** + */const Ec=(e,t)=>{return Xo((r=r=>r.pipe(function(e,t){var r=!1;return arguments.length>=2&&(r=!0),function(n){return n.lift(new Xu(e,t,r))}}(((t,r)=>{if(console.log("尝试次数",t,r),t>=e)throw new Sc("超出尝试次数",r);return t+1}),0),Ku(((...e)=>{switch(typeof t){case"string":case"number":return Ka(parseInt(t,10));case"function":return Ka(t(...e));default:throw new Sc("您输入的 delay 错误")}}))),function(e){return e.lift(new ec(r,e))})); +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - function toFile(data, name) { - if (data instanceof File) return data; - if (data instanceof Blob) { - data.name = name; - return data; - } - - return new File([JSON.stringify(data)], name); - } - - /** + */var r};function Tc(e,{retry:t=3,buffer:r=3,delay:n=1e3,retryDelay:i=300,handleError:o=function(e,t){throw new Error(e,t)}}={}){return Xo(function(e){var t=arguments.length,r=wa;va(arguments[arguments.length-1])&&(r=arguments[arguments.length-1],t--);var n=null;t>=2&&(n=arguments[1]);var i=Number.POSITIVE_INFINITY;return t>=3&&(i=arguments[2]),function(t){return t.lift(new Ru(e,n,i,r))}}(1e3,void 0,r),Ha((e=>e.length)),Ku(((e,t)=>Ka(t*n))),Ma((e=>Na(e))),Gu((r=>_a(r).pipe(Ma((t=>e(t))),Ec(t,i),$u(((...e)=>(o instanceof Function?o(...e):o)||da))))))} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - // 在 浏览器中下载是不能够同时进行的,也就是说,如果前面的没有下载完,后面的又提交 - // 会导致后面的全部失效,所以设置 Promise 下载队列 - const DownloadQueue = { - main: Promise.resolve(true), - add(file) { - this.main.then(() => aDownload(file)); - }, - }; - // a 标签下载的方式貌似为同步模式(未验证) - const aDownload = function (file) { - const a = document.createElement('a'); - a.href = URL.createObjectURL(file); - a.download = file.name; - a.click(); - URL.revokeObjectURL(a.href); - a.remove(); - console.log('%c 下载完成', 'color:green'); - }; - - const download = (data, { DownloadFileName: name } = {}, originData) => { - const file = toFile(data, name || (typeof url === 'string' ? originData.url.replace(/[^\/]*?\//g, '') : '')); - DownloadQueue.add(file); - return null; - }; - const Download = function (options = {}) { - return Plugin$1({ - name: 'Download', - main: download, - options, - }); - }; - - /** + */function Ic({url:e,options:t={}}){const{returnType:r="json"}=this.options;return console.log("- 爬取 ",e),fetch(e,Object.assign({cache:"force-cache"},t)).then((e=>{if(!e.ok)throw Error(e.statusText);return function(e,t){const r=e.headers.get("content-type")||"";return t&&"auto"!==t?t?e[t]():e.json():/text|html|rtf|xml/.test(r)?e.text():/json/.test(r)?e.json():/arrayBuffer/.test(r)?e.arrayBuffer():e.buffer?e.buffer():e.blob()}(e,r)})).then((t=>(console.log(`${e} 爬取成功`),t))).catch((e=>{throw e}))}function Cc(e){throw e} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - const loaderFunction = { - // 加载 js 文件到 html 文档中 - script(url) { - return new Promise((resolve, reject) => { - const script = document.createElement('script'); - script.src = url; - - script.onload = () => { - console.log(`${url} 加载完成`); - script.remove(); - resolve(); - }; - script.onerror = (err) => reject(err); - document.body.append(script); - }); - }, - // 加载 css 文件到 html 文档中 - css(url) { - return new Promise((resolve, reject) => { - const style = document.createElement('style'); - style.rel = 'stylesheet'; - style.src = url; - style.onload = () => { - console.log(`${url} 加载完成`); - resolve(); - }; - style.onerror = (err) => reject(err); - document.body.append(style); - }); - }, - // TODO UMD AMD 等类型的 JS 代码的载入 - }; - - /** +function kc(e,t){return e instanceof File?e:e instanceof Blob?(e.name=t,e):new File([JSON.stringify(e)],t)} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - var scriptMap = { - zangodb: 'https://cdn.jsdelivr.net/gh/erikolson186/zangodb/dist/zangodb.min.js', - dexie: 'https://cdn.jsdelivr.net/npm/dexie@3.0.3/dist/dexie.min.js', - mockjs: 'https://cdn.jsdelivr.net/npm/mockjs-esm/dist/mock.min.js', - xlsx: 'https://cdn.jsdelivr.net/npm/xlsx@0.17.0/dist/xlsx.full.min.js', - lodash: 'https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js', - gsap: [ - 'https://cdn.jsdelivr.net/npm/gsap@3.6.1/dist/gsap.min.js', - 'https://cdn.jsdelivr.net/npm/gsap@3.6.1/dist/ScrollTrigger.min.js', - ], - animejs: 'https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js', - rxjs: 'https://cdn.jsdelivr.net/npm/rxjs@7.1.0/dist/bundles/rxjs.umd.min.js', - jszip: 'https://cdn.jsdelivr.net/npm/jszip@3.6.0/dist/jszip.min.js', - 'ajax-hook': 'https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js', - axios: 'https://cdn.jsdelivr.net/npm/axios@0.21.1/dist/axios.min.js', - react: [ - 'https://unpkg.com/react@16/umd/react.production.min.js', - 'https://unpkg.com/react-dom@16/umd/react-dom.production.min.js', - ], - vue: [ - 'https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js', - 'https://cdn.jsdelivr.net/npm/vuex@3.6.2/dist/vuex.min.js', - ], - }; - - /** + */const Dc={main:Promise.resolve(!0),add(e){this.main.then((()=>Nc(e)))}},Nc=function(e){const t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=e.name,t.click(),URL.revokeObjectURL(t.href),t.remove(),console.log("%c 下载完成","color:green")},Vc=(e,{DownloadFileName:t}={},r)=>{const n=kc(e,t||("string"==typeof url?r.url.replace(/[^\/]*?\//g,""):""));return Dc.add(n),null},Rc={script:e=>new Promise(((t,r)=>{const n=document.createElement("script");n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),n.remove(),t()},n.onerror=e=>r(e),document.body.append(n)})),css:e=>new Promise(((t,r)=>{const n=document.createElement("style");n.rel="stylesheet",n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),t()},n.onerror=e=>r(e),document.body.append(n)}))}; +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - // 借助 jsdelivr 网站的免费 cdn 实现直接查询导入插件的功能。 - const URI = 'https://cdn.jsdelivr.net'; - const wayMap = Object.entries({ - npm: /^npm?/i, - gh: /gh?|github/i, - wp: /wordpress|wp/i, - }); - - /** - * 描述 - * @date 2021-06-28 - * @param {any} moduleName - * @param {any} options - * @return {any} - */ - function jsdelivr(moduleName, { version = '', store = 'npm', path = '' } = {}) { - const way = wayMap.reduce((final, [key, value]) => (value.test(store) ? key : final), 'npm'); - return `${URI}/${way}/${moduleName}${version ? `@${version}` : ''}${path ? `/${path}` : ''}`; - } - - /** +var Uc={zangodb:"https://cdn.jsdelivr.net/gh/erikolson186/zangodb/dist/zangodb.min.js",dexie:"https://cdn.jsdelivr.net/npm/dexie@3.0.3/dist/dexie.min.js",mockjs:"https://cdn.jsdelivr.net/npm/mockjs-esm/dist/mock.min.js",xlsx:"https://cdn.jsdelivr.net/npm/xlsx@0.17.0/dist/xlsx.full.min.js",lodash:"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js",gsap:["https://cdn.jsdelivr.net/npm/gsap@3.6.1/dist/gsap.min.js","https://cdn.jsdelivr.net/npm/gsap@3.6.1/dist/ScrollTrigger.min.js"],animejs:"https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js",rxjs:"https://cdn.jsdelivr.net/npm/rxjs@7.1.0/dist/bundles/rxjs.umd.min.js",jszip:"https://cdn.jsdelivr.net/npm/jszip@3.6.0/dist/jszip.min.js","ajax-hook":"https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js",axios:"https://cdn.jsdelivr.net/npm/axios@0.21.1/dist/axios.min.js",react:["https://unpkg.com/react@16/umd/react.production.min.js","https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"],vue:["https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js","https://cdn.jsdelivr.net/npm/vuex@3.6.2/dist/vuex.min.js"]}; +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - function type$1(any) { - return Object.prototype.toString.call(any).match(/(?<=\[object\s+)\S+?(?=\])/)[0]; - } - - /** + */const Mc=Object.entries({npm:/^npm?/i,gh:/gh?|github/i,wp:/wordpress|wp/i});function zc(e,{version:t="",store:r="npm",path:n=""}={}){return`https://cdn.jsdelivr.net/${Mc.reduce(((e,[t,n])=>n.test(r)?t:e),"npm")}/${e}${t?`@${t}`:""}${n?`/${n}`:""}`} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - const URLTest$1 = /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/; - - /** - * 根据 name object 获取 url - * @date 2021-06-28 - * @param {any} {name - * @param {any} way - * @param {any} path - * @param {any} version} - * @return {any} - */ - function fromName$1({ name, way, path, version }) { - if (scriptMap.hasOwnProperty(name)) { - // 优先使用自带的位置 - return scriptMap[name]; - } - return jsdelivr(name, { version, store: way, path }); - } - - const handle$1 = { - Object({ url = '', name, way = 'npm', path = '', version = '', type = 'script' }) { - if (!url) { - // 没有 url 属性 - const result = fromName$1({ name, way, path, version }); - if (typeof result === 'string') { - url = result; - } else { - // 发现 scriptMap 内部的描述是完整的 $load 可以接收的 array 和 object 类型 - return $load$1(result); - } - } - return loaderFunction[type](url); - }, - String(Module) { - return this.Object({ [URLTest$1.test(Module) ? 'url' : 'name']: Module }); - }, - Array(arr) { - return Promise.all(arr.map((i) => $load$1(i))); - }, - }; - async function $load$1(Module) { - return handle$1[type$1(Module)](Module); - } - - /** + */function Fc(e){return Object.prototype.toString.call(e).match(/(?<=\[object\s+)\S+?(?=\])/)[0]} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - let XLSX; - function init$1() { - return $load$1('xlsx').then(() => { - XLSX = window.XLSX; - }); - } - - /** + */const Lc=/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;const $c={Object({url:e="",name:t,way:r="npm",path:n="",version:i="",type:o="script"}){if(!e){const o=function({name:e,way:t,path:r,version:n}){return Uc.hasOwnProperty(e)?Uc[e]:zc(e,{version:n,store:t,path:r})}({name:t,way:r,path:n,version:i});if("string"!=typeof o)return Hc(o);e=o}return Rc[o](e)},String(e){return this.Object({[Lc.test(e)?"url":"name"]:e})},Array:e=>Promise.all(e.map((e=>Hc(e))))};async function Hc(e){return $c[Fc(e)](e)} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - // XLSX 通过 script 导入 - function ArrayToSheet(sheetArray) { - sheetArray.forEach((i) => { - Object.entries(i).forEach(([key, value]) => { - if (value instanceof Object) { - i[key] = JSON.stringify(value); - } - }); - // 处理二层数据不能够写入的问题 - }); - return XLSX.utils.json_to_sheet(sheetArray); - } - - function bookToFile(book, name, options) { - const ArrayBuffer = XLSX.write(book, options); - return new File([ArrayBuffer], `${name}.${options.bookType}`); - } - function ObjectToBook(input) { - const book = XLSX.utils.book_new(); - Object.entries(input).forEach(([sheetName, sheetArray]) => { - const sheet = ArrayToSheet(sheetArray); - XLSX.utils.book_append_sheet(book, sheet, sheetName); - }); - return book; - } - - // input: {sheetName1:[],sheetName2:[]} - function createExcelFile(input, fileName, XLSXOptions) { - const { bookType = 'xlsx', bookSST = true, type = 'array' } = XLSXOptions || {}; - return bookToFile(ObjectToBook(input), fileName, { - bookType, - bookSST, - type, - }); - } - - /** + */let Bc;function Gc(){return Hc("xlsx").then((()=>{Bc=window.XLSX}))} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - // 未完成 导入 XLSX 的 Promise 到流的转变 - - // ExcelHelper 是将 Object => Book => File 用于下载的一个库 - const ExcelHelper = function (formatter, options = {}) { - return Plugin$1({ - name: 'ExcelHelper', - init: init$1, - options, - main(data) { - const { fileName = 'result', XLSXOptions = {} } = this.options; - if (formatter instanceof Function) data = formatter(data); - return createExcelFile(data, `${fileName}-${new Date().getTime()}`, XLSXOptions); - }, - }); - }; - - /** + */function Kc(e){const t=Bc.utils.book_new();return Object.entries(e).forEach((([e,r])=>{const n=function(e){return e.forEach((e=>{Object.entries(e).forEach((([t,r])=>{r instanceof Object&&(e[t]=JSON.stringify(r))}))})),Bc.utils.json_to_sheet(e)}(r);Bc.utils.book_append_sheet(t,n,e)})),t}function qc(e,t,r){const{bookType:n="xlsx",bookSST:i=!0,type:o="array"}=r||{};return function(e,t,r){const n=Bc.write(e,r);return new File([n],`${t}.${r.bookType}`)}(Kc(e),t,{bookType:n,bookSST:i,type:o})} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - let JSZip; - function init() { - return $load$1('jszip').then(() => { - JSZip = window.JSZip; - }); - } - - /** +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - let index$1 = 0; - async function zipper(fileArray, zipName) { - // 启动压缩 - const zip = new JSZip(); - // 压入所有文件 - fileArray.forEach((file) => zip.file(file.name, file)); - // 设置压缩格式,开始打包 - const content = await zip.generateAsync({ - type: 'blob', // nodejs用 nodebuffer ,浏览器用 blob - }); - // 给压缩文件一个名称 - content.name = `${zipName}-${index$1++}.zip`; - return content; - } - - /** +let Wc;function Yc(){return Hc("jszip").then((()=>{Wc=window.JSZip}))} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - const ZipFile = function (options = {}) { - if (!options.zipFileName) options.zipFileName = new Date().getTime(); - return Plugin$1({ - init, - name: 'zipFile', - main(blob) { - const { zipFileName } = this.options; - const files = toFile(blob, zipFileName); - return zipper(files, zipFileName); - }, - options, - }); - }; - - /** + */let Qc=0; +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - function Combine(number, waitTime = 5000, options = {}) { - return Plugin$1({ - name: 'Combine', // 这个 name 是负责进行监控的标志符号 - options, // 接收所有的参数,提供给所有函数使用 - operator() { - // 复写 operator - return (source) => - source.pipe( - bufferTime(waitTime, undefined, number), - filter((i) => i.length), // 必须要进行检测是否为空 - concatMap((tasks) => of(new TaskGroup(tasks))), - ); - }, - }); - } - function Break() { - return Plugin$1({ - name: 'Break', // 这个 name 是负责进行监控的标志符号 - options, - operator() { - return (source) => - source.pipe( - concatMap((taskGroup) => { - if (taskGroup instanceof TaskGroup) { - return from(taskGroup.$destroy()); - } else { - return of(taskGroup); - } - }), - ); - }, - }); - } - - /** +function Xc(e=3,t=1e3){return r=>new Jo((n=>{const i=new Set;let o=0;const a=()=>{i.size&&(n.next([...i]),i.clear())},s=r.subscribe((r=>{switch(console.log(o),o&&(clearTimeout(o),o=0),i.size){case 0:return i.add(r);case e-1:return i.add(r),a();default:return o=setTimeout(a,t),i.add(r)}}),Oa,(()=>{a(),n.complete()}));return()=>{i.clear(),s.unsubscribe()}}))} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - var plugins = /*#__PURE__*/Object.freeze({ - __proto__: null, - Request: Request, - Download: Download, - ExcelHelper: ExcelHelper, - ZipFile: ZipFile, - Combine: Combine, - Break: Break - }); - - /** +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - /* - * @Author: KonghaYao - * @Date: 2021-06-29 16:16:29 - * @Last Modified by: KonghaYao - * @Last Modified time: 2021-06-29 16:16:29 - */ - /* eslint-disable no-extend-native */ - - // 解决无限debugger的一种方式 - // 对于无限 debugger 不一定有效 - // TODO 验证有效性 - function $antiDebugger() { - if (!Function.prototype.$constructor) { - // 对 Function 构造函数外包一层 - Function.prototype.$constructor = Function.prototype.constructor; - Function.prototype.constructor = function (...args) { - if (args && typeof args[0] === 'string') { - if (args[0] === 'debugger') { - return; - } - } - return Function.prototype.$constructor.apply(this, args); - }; - } - } - - /** +var Zc=Object.freeze({__proto__:null,Request:function(e={}){return xc({init(){},name:"Request",main:Ic,options:e,operator(){const{delay:e=200,buffer:t=1,retry:r=3,handleError:n=null}=this.options;return i=>i.pipe(Tc((e=>this.TaskStarter(e)),{delay:e,buffer:t,retry:r,handleError:n||Cc}))}})},Download:function(e={}){return xc({name:"Download",main:Vc,options:e})},ExcelHelper:function(e,t={}){return xc({name:"ExcelHelper",init:Gc,options:t,main(t){const{fileName:r="result",XLSXOptions:n={}}=this.options;return e instanceof Function&&(t=e(t)),qc(t,`${r}-${(new Date).getTime()}`,n)}})},ZipFile:function(e={}){return e.zipFileName||(e.zipFileName=(new Date).getTime()),xc({init:Yc,name:"zipFile",main(e){const{zipFileName:t}=this.options;return async function(e,t){const r=new Wc;e.forEach((e=>r.file(e.name,e)));const n=await r.generateAsync({type:"blob"});return n.name=`${t}-${Qc++}.zip`,n} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - /** - * 这是清理copy的函数,目的是为了能够让用户进行复制 - * @date 2021-03-02 - */ - function clearCopyBarriers() { - [document, ...document.querySelectorAll('*')].forEach((ele) => { - // 删除对象属性上的函数 - ele.oncontextmenu = ''; - ele.oncopy = ''; - ele.oncut = ''; - ele.onselectstart = true; - - // 清除事件绑定的控制 - const event = window.getEventListeners(ele); - // 清除 快捷键 copy cut 事件的占用 - ['keydown', 'copy', 'cut'].forEach((eventName) => { - if (event.hasOwnProperty(eventName)) { - event[eventName].forEach((target) => ele.removeEventListener(eventName, target.listener)); - } - }); - }); - console.log('copy 方式清理完成'); - } - /** - * 复制函数 - * @description 这个函数只能用在浏览器环境中 - * @date 2021-03-02 - * @param {any} content 要复制的东西,可以是 DOM - * @param {Boolean} clearBarriers=false 顺便帮你解决不能复制的问题,可能会失败 - */ - function $copy(content, clearBarriers = false) { - if (clearBarriers) clearCopyBarriers(); - - // 询问 window.copy 是否被覆盖了 - if (!(window.copy && window.copy.toString() === 'function copy(value) { [Command Line API] }')) { - // 尝试重置 copy 函数 - delete window.copy; - } - // 直接使用控制台的复制功能 - // ! 在开发者工具中可以调用这个函数 - window.copy(content); - console.log('copy 完成,请您查看您的剪贴版'); - } - - var iframe = [ - "webkitStorageInfo", - "0", - "1", - "cookieStore", - "crossOriginIsolated", - "onbeforexrselect", - "ontransitioncancel", - "ontransitionrun", - "ontransitionstart", - "originAgentCluster", - "showDirectoryPicker", - "showOpenFilePicker", - "showSaveFilePicker", - "trustedTypes", - "parent", - "opener", - "top", - "length", - "frames", - "closed", - "location", - "self", - "window", - "document", - "name", - "customElements", - "history", - "locationbar", - "menubar", - "personalbar", - "scrollbars", - "statusbar", - "toolbar", - "status", - "frameElement", - "navigator", - "origin", - "external", - "screen", - "innerWidth", - "innerHeight", - "scrollX", - "pageXOffset", - "scrollY", - "pageYOffset", - "visualViewport", - "screenX", - "screenY", - "outerWidth", - "outerHeight", - "devicePixelRatio", - "clientInformation", - "screenLeft", - "screenTop", - "defaultStatus", - "defaultstatus", - "styleMedia", - "onsearch", - "isSecureContext", - "onabort", - "onblur", - "oncancel", - "oncanplay", - "oncanplaythrough", - "onchange", - "onclick", - "onclose", - "oncontextmenu", - "oncuechange", - "ondblclick", - "ondrag", - "ondragend", - "ondragenter", - "ondragleave", - "ondragover", - "ondragstart", - "ondrop", - "ondurationchange", - "onemptied", - "onended", - "onerror", - "onfocus", - "onformdata", - "oninput", - "oninvalid", - "onkeydown", - "onkeypress", - "onkeyup", - "onload", - "onloadeddata", - "onloadedmetadata", - "onloadstart", - "onmousedown", - "onmouseenter", - "onmouseleave", - "onmousemove", - "onmouseout", - "onmouseover", - "onmouseup", - "onmousewheel", - "onpause", - "onplay", - "onplaying", - "onprogress", - "onratechange", - "onreset", - "onresize", - "onscroll", - "onseeked", - "onseeking", - "onselect", - "onstalled", - "onsubmit", - "onsuspend", - "ontimeupdate", - "ontoggle", - "onvolumechange", - "onwaiting", - "onwebkitanimationend", - "onwebkitanimationiteration", - "onwebkitanimationstart", - "onwebkittransitionend", - "onwheel", - "onauxclick", - "ongotpointercapture", - "onlostpointercapture", - "onpointerdown", - "onpointermove", - "onpointerup", - "onpointercancel", - "onpointerover", - "onpointerout", - "onpointerenter", - "onpointerleave", - "onselectstart", - "onselectionchange", - "onanimationend", - "onanimationiteration", - "onanimationstart", - "ontransitionend", - "onafterprint", - "onbeforeprint", - "onbeforeunload", - "onhashchange", - "onlanguagechange", - "onmessage", - "onmessageerror", - "onoffline", - "ononline", - "onpagehide", - "onpageshow", - "onpopstate", - "onrejectionhandled", - "onstorage", - "onunhandledrejection", - "onunload", - "performance", - "stop", - "open", - "alert", - "confirm", - "prompt", - "print", - "queueMicrotask", - "requestAnimationFrame", - "cancelAnimationFrame", - "captureEvents", - "releaseEvents", - "requestIdleCallback", - "cancelIdleCallback", - "getComputedStyle", - "matchMedia", - "moveTo", - "moveBy", - "resizeTo", - "resizeBy", - "scroll", - "scrollTo", - "scrollBy", - "getSelection", - "find", - "webkitRequestAnimationFrame", - "webkitCancelAnimationFrame", - "fetch", - "btoa", - "atob", - "setTimeout", - "clearTimeout", - "setInterval", - "clearInterval", - "createImageBitmap", - "close", - "focus", - "blur", - "postMessage", - "onappinstalled", - "onbeforeinstallprompt", - "crypto", - "indexedDB", - "sessionStorage", - "localStorage", - "chrome", - "onpointerrawupdate", - "speechSynthesis", - "webkitRequestFileSystem", - "webkitResolveLocalFileSystemURL", - "openDatabase", - "applicationCache", - "caches", - "ondevicemotion", - "ondeviceorientation", - "ondeviceorientationabsolute" - ]; - - /** + */(kc(e,t),t)},options:e})},Combine:function(e,t=1e3,r){return xc({name:"Combine",main:r,operator(){return n=>n.pipe(Xc(e,t),Ha((e=>e.length)),Gu((e=>{const t=_a(new pc(e));return r instanceof Function?t.pipe(Gu((e=>this.TaskStarter(e)))):t})))}})},Break:function(){return xc({name:"Break",options:options,operator:()=>e=>e.pipe(Gu((e=>e instanceof pc?from(e.$destroy()):_a(e))))})}}); +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - // iframe 是所有的 window 对象下稳定的属性名 - // !若是使用 iframe 标签的属性来得到 window 的自带属性,遇到不能使用 iframe 的网站就会失效 - // ! 所以使用了这种方式。 - - /** - * 全局变量展示 - * @date 2020-09-17 - * @description 将 window 和 上面引入的 iframe 对象做了比较 - * @return {Object} 返回 window 的属性和对象 - */ - function $GlobalVars() { - // 通过比较得出window上的变量 - const diff = difference(Object.keys(window), iframe); - return pick(window, diff); - } - - /** + */var Jc=["webkitStorageInfo","0","1","cookieStore","crossOriginIsolated","onbeforexrselect","ontransitioncancel","ontransitionrun","ontransitionstart","originAgentCluster","showDirectoryPicker","showOpenFilePicker","showSaveFilePicker","trustedTypes","parent","opener","top","length","frames","closed","location","self","window","document","name","customElements","history","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","status","frameElement","navigator","origin","external","screen","innerWidth","innerHeight","scrollX","pageXOffset","scrollY","pageYOffset","visualViewport","screenX","screenY","outerWidth","outerHeight","devicePixelRatio","clientInformation","screenLeft","screenTop","defaultStatus","defaultstatus","styleMedia","onsearch","isSecureContext","onabort","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onmousewheel","onpause","onplay","onplaying","onprogress","onratechange","onreset","onresize","onscroll","onseeked","onseeking","onselect","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel","onauxclick","ongotpointercapture","onlostpointercapture","onpointerdown","onpointermove","onpointerup","onpointercancel","onpointerover","onpointerout","onpointerenter","onpointerleave","onselectstart","onselectionchange","onanimationend","onanimationiteration","onanimationstart","ontransitionend","onafterprint","onbeforeprint","onbeforeunload","onhashchange","onlanguagechange","onmessage","onmessageerror","onoffline","ononline","onpagehide","onpageshow","onpopstate","onrejectionhandled","onstorage","onunhandledrejection","onunload","performance","stop","open","alert","confirm","prompt","print","queueMicrotask","requestAnimationFrame","cancelAnimationFrame","captureEvents","releaseEvents","requestIdleCallback","cancelIdleCallback","getComputedStyle","matchMedia","moveTo","moveBy","resizeTo","resizeBy","scroll","scrollTo","scrollBy","getSelection","find","webkitRequestAnimationFrame","webkitCancelAnimationFrame","fetch","btoa","atob","setTimeout","clearTimeout","setInterval","clearInterval","createImageBitmap","close","focus","blur","postMessage","onappinstalled","onbeforeinstallprompt","crypto","indexedDB","sessionStorage","localStorage","chrome","onpointerrawupdate","speechSynthesis","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","openDatabase","applicationCache","caches","ondevicemotion","ondeviceorientation","ondeviceorientationabsolute"]; +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - function type(any) { - return Object.prototype.toString.call(any).match(/(?<=\[object\s+)\S+?(?=\])/)[0]; - } - - /** +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - const TypeMap = { - RE: '', - StringFunction(all, key, value, keyValue) { - if (this.RE.test(`${value}`)) all.push(keyValue); - return all; - }, - - Array(all, key, value) { - const arr = searchObj(Object.entries(value), this.RE); - - const Value = arr.reduce((final, [k, v]) => { - final[parseInt(k)] = v; - return final; - }, []); - if (arr.length) all.push([key, Value]); - - return all; - }, - Function(all, key, value) { - const entries = searchObj(Object.entries(value), this.RE); - if (entries.length) { - all.push([key, Object.assign(value, Object.fromEntries(entries))]); - } - return all; - }, - Object(all, key, value) { - const entries = searchObj(Object.entries(value), this.RE); - if (entries.length) all.push([key, Object.fromEntries(entries)]); - - return all; - }, - }; - TypeMap.Number = TypeMap.StringFunction; - TypeMap.String = TypeMap.StringFunction; - - /** - * 描述 - * @date 2021-06-28 - * @param {any} arr - * @param {any} RE - * @param {any} keepUnknown=false - * @return {any} - */ - function searchObj(arr, RE, keepUnknown = false) { - return arr.reduce((all, keyValue) => { - const [key, value] = keyValue; - // 判断 key 中是否有符合项 - if (RE.test(key)) { - return [...all, keyValue]; - } - // 判断数据类型 分类操作 - TypeMap.RE = RE; - const type$1 = type(value); - if (TypeMap.hasOwnProperty(type$1)) { - return TypeMap[type$1](all, key, value, keyValue); - } - return keepUnknown ? [all, keyValue] : all; - }, []); - } - - /** +const el={RE:"",StringFunction(e,t,r,n){return this.RE.test(`${r}`)&&e.push(n),e},Array(e,t,r){const n=tl(Object.entries(r),this.RE),i=n.reduce(((e,[t,r])=>(e[parseInt(t)]=r,e)),[]);return n.length&&e.push([t,i]),e},Function(e,t,r){const n=tl(Object.entries(r),this.RE);return n.length&&e.push([t,Object.assign(r,Object.fromEntries(n))]),e},Object(e,t,r){const n=tl(Object.entries(r),this.RE);return n.length&&e.push([t,Object.fromEntries(n)]),e}};function tl(e,t,r=!1){return e.reduce(((e,n)=>{const[i,o]=n;if(t.test(i))return[...e,n];el.RE=t;const a=(s=o,Object.prototype.toString.call(s).match(/(?<=\[object\s+)\S+?(?=\])/)[0]); +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - /** - * 描述 - * @date 2021-06-28 - * @param {any} obj - * @param {any} reg - * @returns {any} - */ - - function $search(obj, reg) { - if (!isRegExp(reg) && isString(reg)) { - reg = new RegExp(reg); - } - if (obj instanceof Array) { - return searchObj(Object.entries({ i: obj }), reg)[0][1]; - } - if (obj instanceof Object) { - return Object.fromEntries(searchObj(Object.entries(obj), reg)); - } - throw new Error('不是对象,不能搜索'); - } - - /** +var s;return el.hasOwnProperty(a)?el[a](e,i,o,n):r?[e,n]:e}),[])} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - const URLTest = /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/; - - /** - * 根据 name object 获取 url - * @date 2021-06-28 - * @param {any} {name - * @param {any} way - * @param {any} path - * @param {any} version} - * @return {any} - */ - function fromName({ name, way, path, version }) { - if (scriptMap.hasOwnProperty(name)) { - // 优先使用自带的位置 - return scriptMap[name]; - } - return jsdelivr(name, { version, store: way, path }); - } - - const handle = { - Object({ url = '', name, way = 'npm', path = '', version = '', type = 'script' }) { - if (!url) { - // 没有 url 属性 - const result = fromName({ name, way, path, version }); - if (typeof result === 'string') { - url = result; - } else { - // 发现 scriptMap 内部的描述是完整的 $load 可以接收的 array 和 object 类型 - return $load(result); - } - } - return loaderFunction[type](url); - }, - String(Module) { - return this.Object({ [URLTest.test(Module) ? 'url' : 'name']: Module }); - }, - Array(arr) { - return Promise.all(arr.map((i) => $load(i))); - }, - }; - async function $load(Module) { - return handle[type$1(Module)](Module); - } - - /** + */el.Number=el.StringFunction,el.String=el.StringFunction; +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - var excelTemplate = { - 'data|100': [ - { - ID: '@increment()', - name: '@cname()', - description: '@csentence()', - avatar: '@dataImage("64x64")', - address: '@region()', - province: '@province()', - }, - ], - }; - - /** +const rl=/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;const nl={Object({url:e="",name:t,way:r="npm",path:n="",version:i="",type:o="script"}){if(!e){const o=function({name:e,way:t,path:r,version:n}){return Uc.hasOwnProperty(e)?Uc[e]:zc(e,{version:n,store:t,path:r})}({name:t,way:r,path:n,version:i});if("string"!=typeof o)return il(o);e=o}return Rc[o](e)},String(e){return this.Object({[rl.test(e)?"url":"name"]:e})},Array:e=>Promise.all(e.map((e=>il(e))))};async function il(e){return nl[Fc(e)](e)} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - // 在这里配置 url 和 type 信息 - const Server = { - excel: { - url: '/fake/excel', - type: 'get', - template: excelTemplate, - }, - }; - - /** +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - async function Mock(MockSiteName) { - // 导入 Mockjs - if (!window.Mock) { - await $load('mockjs'); - console.warn('Mockjs 载入并代理 Ajax 中'); - } - console.warn('mock 启动后台 ', MockSiteName); - const { url, type, template } = Server[MockSiteName]; - window.Mock.mock(url, type, template); - return true; - } - const $Mock = memoize(Mock); - - /** +const ol={excel:{url:"/fake/excel",type:"get",template:{"data|100":[{ID:"@increment()",name:"@cname()",description:"@csentence()",avatar:'@dataImage("64x64")',address:"@region()",province:"@province()"}]}}}; +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - /** - * The Regexps were copied from Purl (A JavaScript URL parser) v2.3.1 - * which developed and maintained by Mark Perkins, mark@allmarkedup.com - * Source repository: https://github.com/allmarkedup/jQuery-URL-Parser - * Licensed under an MIT-style license. - */ - const key = [ - 'source', - 'protocol', - 'authority', - 'userInfo', - 'user', - 'password', - 'host', - 'port', - 'relative', - 'path', - 'directory', - 'file', - 'query', - 'hash', - ]; // keys available to query - const parser = { - // less intuitive, more accurate to the specs - strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, - // more intuitive, fails on relative paths and deviates from specs - loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/, - }; - - function parseUri(url, strictMode = false) { - const res = parser[strictMode ? 'strict' : 'loose'].exec(decodeURI(url)); - - const uri = key.reduce((col, keyName, index) => { - col[keyName] = res[index] || ''; - return col; - }, {}); - - // build query and hash parameters - uri.queryParams = parseString(uri.query); - - // compile a 'base' domain attribute - uri['base'] = uri.host - ? (uri.protocol ? uri.protocol + '://' + uri.host : uri.host) + (uri.port ? ':' + uri.port : '') - : ''; - - return uri; - } - - function parseString(queryString) { - return String(queryString) - .split(/&|;/) - .reduce(function (collection, pair) { - try { - pair = decodeURIComponent(pair.replace(/\+/g, ' ')); - } catch (e) { - // ignore - } - const [key, value] = pair.split(/=/g); - collection[key] = value; - return collection; - }, {}); - } - - function parseURL(url, strictMode = false) { - return parseUri(url, strictMode); - } - - /** + */const al=pu((async function(e){window.Mock||(await il("mockjs"),console.warn("Mockjs 载入并代理 Ajax 中")),console.warn("mock 启动后台 ",e);const{url:t,type:r,template:n}=ol[e];return window.Mock.mock(t,r,n),!0})),sl=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","hash"],ul={strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}; +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - - var tools = /*#__PURE__*/Object.freeze({ - __proto__: null, - $antiDebugger: $antiDebugger, - $copy: $copy, - $GlobalVars: $GlobalVars, - $search: $search, - $load: $load, - $Mock: $Mock, - parseURL: parseURL - }); - - /** + */function cl(e,t=!1){const r=ul[t?"strict":"loose"].exec(decodeURI(e)),n=sl.reduce(((e,t,n)=>(e[t]=r[n]||"",e)),{});var i;return n.queryParams=(i=n.query,String(i).split(/&|;/).reduce((function(e,t){try{t=decodeURIComponent(t.replace(/\+/g," "))}catch(e){}const[r,n]=t.split(/=/g);return e[r]=n,e}),{})),n.base=n.host?(n.protocol?n.protocol+"://"+n.host:n.host)+(n.port?":"+n.port:""):"",n} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ - - class PLUGIN { - constructor({ - forceRetry = true, - saveResult = false, - name = null, - main, - init = null, - error = null, - complete = null, - options = {}, - operator, - }) { - if (operator) this.operator = operator; - // 写入自身中 - Object.assign(this, { - name, // 名称,一般用作提示标记 - main, // Plugin 中的功能性函数 - init, // 初始化整个 Plugin 的函数 - error, // operator 错误时的事件,若返回 false 类的数据,将会中断流,返回正常数据会继续流 - complete, // 函数完成时的提示事件 - options, // main 函数接收的 options - saveResult, // 是否保存结果到每一个 Task 中 - forceRetry, // 是否强制重新使用 Plugin - }); - } - initUUID(index) { - this.uuid = createUUID((this?.main || this.operator).toString() + index); - } - // 对 main 函数外包一层,直接启动 main 函数的执行,返回一条流 - TaskStarter(task) { - return of(task).pipe( - // 设置跳过 Plugin 的逻辑 - switchMap((task) => { - return of(task).pipe( - map((task) => [task.$commit('start', this.uuid), task._originData]), - - switchMap(([data, originData]) => { - const result = this.main(data, originData); - return result instanceof Promise || result instanceof Observable ? from$1(result) : of(result); - }), - map((result) => { - task.$commit('success', result, this.uuid, this.saveResult); - return task; - }), - ); - }), - // 捕获到异常 - catchError((...args) => { - if (this.error instanceof Function) { - const afterError = this.error(task, ...args); - if (afterError) throw new PluginError(afterError); - - return EMPTY; - } - throw new PluginError(args[0]); - }), - // 完成 Plugin 时的事件 - tap((task) => this.complete && this.complete(task)), - ); - } - - operator(context) { - // ! 这个是默认的 operator 函数 - // context 为上层的 JSpider 实例 - return pipe(switchMap((task) => this.TaskStarter(task))); - } - } - - function Plugin(Process, otherOptions = {}) { - if (Process instanceof Function) { - return new PLUGIN( - Object.assign(otherOptions, { - main: Process, - }), - ); - } - if (Process instanceof Object) { - return new PLUGIN(Process); - } - throw new PluginError('Plugin 必须是一个函数或者是 Plugin 描述对象'); - } - - /** +var ll=Object.freeze({__proto__:null,$antiDebugger:function(){Function.prototype.$constructor||(Function.prototype.$constructor=Function.prototype.constructor,Function.prototype.constructor=function(...e){if(!e||"string"!=typeof e[0]||"debugger"!==e[0])return Function.prototype.$constructor.apply(this,e)})} +/** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ - var index = Object.assign(Spider, tools, { - plugins, - Plugin, - Task, - TaskGroup, - version: "3.2.1", - buildDate: new Date(1628326859357), - }); - - return index; - -}()); + */,$copy:function(e,t=!1){t&&([document,...document.querySelectorAll("*")].forEach((e=>{e.oncontextmenu="",e.oncopy="",e.oncut="",e.onselectstart=!0;const t=window.getEventListeners(e);["keydown","copy","cut"].forEach((r=>{t.hasOwnProperty(r)&&t[r].forEach((t=>e.removeEventListener(r,t.listener)))}))})),console.log("copy 方式清理完成")),window.copy&&"function copy(value) { [Command Line API] }"===window.copy.toString()||delete window.copy,window.copy(e),console.log("copy 完成,请您查看您的剪贴版")},$GlobalVars:function(){const e=Iu(Object.keys(window),Jc);return Vu(window,e)},$search:function(e,t){var r;if(!ku(t)&&("string"==typeof(r=t)||!us(r)&&os(r)&&"[object String]"==is(r))&&(t=new RegExp(t)),e instanceof Array)return tl(Object.entries({i:e}),t)[0][1];if(e instanceof Object)return Object.fromEntries(tl(Object.entries(e),t));throw new Error("不是对象,不能搜索")},$load:il,$Mock:al,parseURL:function(e,t=!1){return cl(e,t)}}); +/** + * @license + * Copyright 2021 KonghaYao 江夏尧 + * SPDX-License-Identifier: Apache-2.0 + */class fl{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=_c((this?.main||this.operator).toString()+e)}TaskStarter(e){return _a(e).pipe(ic((e=>_a(e).pipe(ja((e=>[e.$commit("start",this.uuid),e._originData])),ic((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Jo?Na(r):_a(r)})),ja((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),$u(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new Pc(r);return da}throw new Pc(t[0])})),sc((e=>this.complete&&this.complete(e))))}operator(e){return Xo(ic((e=>this.TaskStarter(e))))}}return Object.assign(class{constructor({logEvery:e=!1}={}){this.config={logEvery:e},this.views=new jc(this.config)}crawl(...e){return Oc.createFlow(e.flat()),this}pipeline(...e){return Oc.pipeline(...e),this}start(){return Oc.startFlow(),this}stop(){return Oc.stopFlow(),this}},ll,{plugins:Zc,Plugin:function(e,t={}){if(e instanceof Function)return new fl(Object.assign(t,{main:e}));if(e instanceof Object)return new fl(e);throw new Pc("Plugin 必须是一个函数或者是 Plugin 描述对象")} +/** + * @license + * Copyright 2021 KonghaYao 江夏尧 + * SPDX-License-Identifier: Apache-2.0 + */,Task:fc,TaskGroup:pc,version:"3.2.2",buildDate:new Date(1628382223946)})}(); diff --git a/dist/JSpider.umd.min.js b/dist/JSpider.umd.min.js index 1de8bce..015bea0 100644 --- a/dist/JSpider.umd.min.js +++ b/dist/JSpider.umd.min.js @@ -202,7 +202,7 @@ * limitations under the License. */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).JSpider=t()}(this,(function(){"use strict";function e(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;re.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(n=e[Symbol.iterator]()).next.bind(n)}var R=Symbol("mobx-stored-annotations");function U(e){return Object.assign((function(t,n){M(t,n,e)}),e)}function M(e,t,n){x(e,R)||m(e,R,C({},e[R])),function(e){return e.annotationType_===K}(n)||(e[R][t]=n)}var F=Symbol("mobx administration"),z=function(){function e(e){void 0===e&&(e="Atom"),this.name_=void 0,this.isPendingUnobservation_=!1,this.isBeingObserved_=!1,this.observers_=new Set,this.diffValue_=0,this.lastAccessedBy_=0,this.lowestObserverState_=Fe.NOT_TRACKING_,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return ut(this)},t.reportChanged=function(){at(),ct(this),st()},t.toString=function(){return this.name_},e}(),L=w("Atom",z);function $(e,t,n){void 0===t&&(t=h),void 0===n&&(n=h);var r,i=new z(e);return t!==h&&Ct(Tt,i,t,r),n!==h&&It(i,n),i}var H={identity:function(e,t){return e===t},structural:function(e,t){return Yn(e,t)},default:function(e,t){return Object.is(e,t)},shallow:function(e,t){return Yn(e,t,1)}};function B(e,t,n){return Lt(e)?e:Array.isArray(e)?Oe.array(e,{name:n}):y(e)?Oe.object(e,void 0,{name:n}):O(e)?Oe.map(e,{name:n}):j(e)?Oe.set(e,{name:n}):"function"!=typeof e||St(e)||Mt(e)?e:g(e)?Rt(e):jt(n,e)}function G(e){return e}var K="override";function q(e,t){return{annotationType_:e,options_:t,make_:W,extend_:Y}}function W(e,t,n,r){var i;if(null==(i=this.options_)?void 0:i.bound)return null===this.extend_(e,t,n,!1)?0:1;if(r===e.target_)return null===this.extend_(e,t,n,!1)?0:2;if(St(n.value))return 1;var a=Q(e,this,t,n,!1);return o(r,t,a),2}function Y(e,t,n,r){var i=Q(e,this,t,n);return e.defineProperty_(t,i,r)}function Q(e,t,n,r,i){var o,a,s,u,c,l;void 0===i&&(i=nt.safeDescriptors),l=r,t.annotationType_,l.value;var f,p=r.value;(null==(o=t.options_)?void 0:o.bound)&&(p=p.bind(null!=(f=e.proxy_)?f:e.target_));return{value:ke(null!=(a=null==(s=t.options_)?void 0:s.name)?a:n.toString(),p,null!=(u=null==(c=t.options_)?void 0:c.autoAction)&&u),configurable:!i||e.isPlainObject_,enumerable:!1,writable:!i}}function X(e,t){return{annotationType_:e,options_:t,make_:Z,extend_:J}}function Z(e,t,n,r){var i;if(r===e.target_)return null===this.extend_(e,t,n,!1)?0:2;if((null==(i=this.options_)?void 0:i.bound)&&!Mt(e.target_[t])&&null===this.extend_(e,t,n,!1))return 0;if(Mt(n.value))return 1;var a=ee(e,this,t,n,!1,!1);return o(r,t,a),2}function J(e,t,n,r){var i,o=ee(e,this,t,n,null==(i=this.options_)?void 0:i.bound);return e.defineProperty_(t,o,r)}function ee(e,t,n,r,i,o){var a;void 0===o&&(o=nt.safeDescriptors),a=r,t.annotationType_,a.value;var s,u=r.value;i&&(u=u.bind(null!=(s=e.proxy_)?s:e.target_));return{value:Rt(u),configurable:!o||e.isPlainObject_,enumerable:!1,writable:!o}}function te(e,t){return{annotationType_:e,options_:t,make_:ne,extend_:re}}function ne(e,t,n){return null===this.extend_(e,t,n,!1)?0:1}function re(e,t,n,r){var i;return i=n,this.annotationType_,i.get,e.defineComputedProperty_(t,C({},this.options_,{get:n.get,set:n.set}),r)}function ie(e,t){return{annotationType_:e,options_:t,make_:oe,extend_:ae}}function oe(e,t,n){return null===this.extend_(e,t,n,!1)?0:1}function ae(e,t,n,r){var i,o;return this.annotationType_,e.defineObservableProperty_(t,n.value,null!=(i=null==(o=this.options_)?void 0:o.enhancer)?i:B,r)}var se=ue();function ue(e){return{annotationType_:"true",options_:e,make_:ce,extend_:le}}function ce(e,t,n,r){var i,a,s,u;if(n.get)return Ae.make_(e,t,n,r);if(n.set){var c=ke(t.toString(),n.set);return r===e.target_?null===e.defineProperty_(t,{configurable:!nt.safeDescriptors||e.isPlainObject_,set:c})?0:2:(o(r,t,{configurable:!0,set:c}),2)}if(r!==e.target_&&"function"==typeof n.value)return g(n.value)?((null==(u=this.options_)?void 0:u.autoBind)?Rt.bound:Rt).make_(e,t,n,r):((null==(s=this.options_)?void 0:s.autoBind)?jt.bound:jt).make_(e,t,n,r);var l,f=!1===(null==(i=this.options_)?void 0:i.deep)?Oe.ref:Oe;"function"==typeof n.value&&(null==(a=this.options_)?void 0:a.autoBind)&&(n.value=n.value.bind(null!=(l=e.proxy_)?l:e.target_));return f.make_(e,t,n,r)}function le(e,t,n,r){var i,o,a;if(n.get)return Ae.extend_(e,t,n,r);if(n.set)return e.defineProperty_(t,{configurable:!nt.safeDescriptors||e.isPlainObject_,set:ke(t.toString(),n.set)},r);"function"==typeof n.value&&(null==(i=this.options_)?void 0:i.autoBind)&&(n.value=n.value.bind(null!=(a=e.proxy_)?a:e.target_));return(!1===(null==(o=this.options_)?void 0:o.deep)?Oe.ref:Oe).extend_(e,t,n,r)}var fe={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function pe(e){return e||fe}Object.freeze(fe);var he=ie("observable"),be=ie("observable.ref",{enhancer:G}),de=ie("observable.shallow",{enhancer:function(e,t,n){return null==e||Vn(e)||gn(e)||Sn(e)||En(e)?e:Array.isArray(e)?Oe.array(e,{name:n,deep:!1}):y(e)?Oe.object(e,void 0,{name:n,deep:!1}):O(e)?Oe.map(e,{name:n,deep:!1}):j(e)?Oe.set(e,{name:n,deep:!1}):void 0}}),ve=ie("observable.struct",{enhancer:function(e,t){return Yn(e,t)?t:e}}),ye=U(he);function ge(e){return!0===e.deep?B:!1===e.deep?G:(t=e.defaultDecorator)&&null!=(n=null==(r=t.options_)?void 0:r.enhancer)?n:B;var t,n,r}function me(e,t,n){if(!d(t))return Lt(e)?e:y(e)?Oe.object(e,t,n):Array.isArray(e)?Oe.array(e,t):O(e)?Oe.map(e,t):j(e)?Oe.set(e,t):"object"==typeof e&&null!==e?e:Oe.box(e,t);M(e,t,he)}Object.assign(me,ye);var _e,we,Oe=r(me,{box:function(e,t){var n=pe(t);return new Ue(e,ge(n),n.name,!0,n.equals)},array:function(e,t){var n=pe(t);return(!1===nt.useProxies||!1===n.proxy?Bn:cn)(e,ge(n),n.name)},map:function(e,t){var n=pe(t);return new Pn(e,ge(n),n.name)},set:function(e,t){var n=pe(t);return new xn(e,ge(n),n.name)},object:function(e,t,n){return function(e,t,n,r){var i=E(t),o=kn(e,r)[F];at();try{S(i).forEach((function(e){o.extend_(e,i[e],!n||(!(e in n)||n[e]))}))}finally{st()}return e}(!1===nt.useProxies||!1===(null==n?void 0:n.proxy)?kn({},n):function(e,t){var n,r;return f(),e=kn(e,t),null!=(r=(n=e[F]).proxy_)?r:n.proxy_=new Proxy(e,Qt)}({},n),e,t)},ref:U(be),shallow:U(de),deep:ye,struct:U(ve)}),je="computed",Pe=te(je),Se=te("computed.struct",{equals:H.structural}),Ae=function(e,t){if(d(t))return M(e,t,Pe);if(y(e))return U(te(je,e));var n=y(t)?t:{};return n.get=e,n.name||(n.name=e.name||""),new Le(n)};Object.assign(Ae,Pe),Ae.struct=U(Se);var xe,Ee=0,Te=1,Ie=null!=(_e=null==(we=i((function(){}),"name"))?void 0:we.configurable)&&_e,Ce={value:"action",configurable:!0,writable:!1,enumerable:!1};function ke(e,t,n,r){function i(){return De(e,n,t,r||this,arguments)}return void 0===n&&(n=!1),i.isMobxAction=!0,Ie&&(Ce.value=e,Object.defineProperty(i,"name",Ce)),i}function De(t,n,r,i,o){var a=function(e,t,n,r){var i=!1,o=0,a=nt.trackingDerivation,s=!t||!a;at();var u=nt.allowStateChanges;s&&(Ye(),u=Ne(!0));var c=Xe(!0),l={runAsAction_:s,prevDerivation_:a,prevAllowStateChanges_:u,prevAllowStateReads_:c,notifySpy_:i,startTime_:o,actionId_:Te++,parentActionId_:Ee};return Ee=l.actionId_,l}(0,n);try{return r.apply(i,o)}catch(e){throw a.error_=e,e}finally{!function(t){Ee!==t.actionId_&&e(30);Ee=t.parentActionId_,void 0!==t.error_&&(nt.suppressReactionErrors=!0);Ve(t.prevAllowStateChanges_),Ze(t.prevAllowStateReads_),st(),t.runAsAction_&&Qe(t.prevDerivation_);nt.suppressReactionErrors=!1}(a)}}function Ne(e){var t=nt.allowStateChanges;return nt.allowStateChanges=e,t}function Ve(e){nt.allowStateChanges=e}xe=Symbol.toPrimitive;var Re,Ue=function(e){function t(t,n,r,i,o){var a;return void 0===r&&(r="ObservableValue"),void 0===o&&(o=H.default),(a=e.call(this,r)||this).enhancer=void 0,a.name_=void 0,a.equals=void 0,a.hasUnreportedChange_=!1,a.interceptors_=void 0,a.changeListeners_=void 0,a.value_=void 0,a.dehancer=void 0,a.enhancer=n,a.name_=r,a.equals=o,a.value_=n(t,void 0,r),a}k(t,e);var n=t.prototype;return n.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},n.set=function(e){this.value_,(e=this.prepareNewValue_(e))!==nt.UNCHANGED&&this.setNewValue_(e)},n.prepareNewValue_=function(e){if(Xt(this)){var t=Jt(this,{object:this,type:an,newValue:e});if(!t)return nt.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value_,this.name_),this.equals(this.value_,e)?nt.UNCHANGED:e},n.setNewValue_=function(e){var t=this.value_;this.value_=e,this.reportChanged(),en(this)&&nn(this,{type:an,object:this,newValue:e,oldValue:t})},n.get=function(){return this.reportObserved(),this.dehanceValue(this.value_)},n.intercept_=function(e){return Zt(this,e)},n.observe_=function(e,t){return t&&e({observableKind:"value",debugObjectName:this.name_,object:this,type:an,newValue:this.value_,oldValue:void 0}),tn(this,e)},n.raw=function(){return this.value_},n.toJSON=function(){return this.get()},n.toString=function(){return this.name_+"["+this.value_+"]"},n.valueOf=function(){return A(this.get())},n[xe]=function(){return this.valueOf()},t}(z),Me=w("ObservableValue",Ue);Re=Symbol.toPrimitive;var Fe,ze,Le=function(){function t(t){this.dependenciesState_=Fe.NOT_TRACKING_,this.observing_=[],this.newObserving_=null,this.isBeingObserved_=!1,this.isPendingUnobservation_=!1,this.observers_=new Set,this.diffValue_=0,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=Fe.UP_TO_DATE_,this.unboundDepsCount_=0,this.value_=new He(null),this.name_=void 0,this.triggeredBy_=void 0,this.isComputing_=!1,this.isRunningSetter_=!1,this.derivation=void 0,this.setter_=void 0,this.isTracing_=ze.NONE,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,t.get||e(31),this.derivation=t.get,this.name_=t.name||"ComputedValue",t.set&&(this.setter_=ke("ComputedValue-setter",t.set)),this.equals_=t.equals||(t.compareStructural||t.struct?H.structural:H.default),this.scope_=t.context,this.requiresReaction_=!!t.requiresReaction,this.keepAlive_=!!t.keepAlive}var n=t.prototype;return n.onBecomeStale_=function(){!function(e){if(e.lowestObserverState_!==Fe.UP_TO_DATE_)return;e.lowestObserverState_=Fe.POSSIBLY_STALE_,e.observers_.forEach((function(e){e.dependenciesState_===Fe.UP_TO_DATE_&&(e.dependenciesState_=Fe.POSSIBLY_STALE_,e.onBecomeStale_())}))}(this)},n.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},n.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},n.get=function(){if(this.isComputing_&&e(32,this.name_,this.derivation),0!==nt.inBatch||0!==this.observers_.size||this.keepAlive_){if(ut(this),Ge(this)){var t=nt.trackingContext;this.keepAlive_&&!t&&(nt.trackingContext=this),this.trackAndCompute()&&function(e){if(e.lowestObserverState_===Fe.STALE_)return;e.lowestObserverState_=Fe.STALE_,e.observers_.forEach((function(t){t.dependenciesState_===Fe.POSSIBLY_STALE_?t.dependenciesState_=Fe.STALE_:t.dependenciesState_===Fe.UP_TO_DATE_&&(e.lowestObserverState_=Fe.UP_TO_DATE_)}))}(this),nt.trackingContext=t}}else Ge(this)&&(this.warnAboutUntrackedRead_(),at(),this.value_=this.computeValue_(!1),st());var n=this.value_;if(Be(n))throw n.cause;return n},n.set=function(t){if(this.setter_){this.isRunningSetter_&&e(33,this.name_),this.isRunningSetter_=!0;try{this.setter_.call(this.scope_,t)}finally{this.isRunningSetter_=!1}}else e(34,this.name_)},n.trackAndCompute=function(){var e=this.value_,t=this.dependenciesState_===Fe.NOT_TRACKING_,n=this.computeValue_(!0),r=t||Be(e)||Be(n)||!this.equals_(e,n);return r&&(this.value_=n),r},n.computeValue_=function(e){this.isComputing_=!0;var t,n=Ne(!1);if(e)t=Ke(this,this.derivation,this.scope_);else if(!0===nt.disableErrorBoundaries)t=this.derivation.call(this.scope_);else try{t=this.derivation.call(this.scope_)}catch(e){t=new He(e)}return Ve(n),this.isComputing_=!1,t},n.suspend_=function(){this.keepAlive_||(qe(this),this.value_=void 0)},n.observe_=function(e,t){var n=this,r=!0,i=void 0;return function(e,t){var n,r;void 0===t&&(t=u);var i,o=null!=(n=null==(r=t)?void 0:r.name)?n:"Autorun";if(t.scheduler||t.delay){var a=xt(t),s=!1;i=new lt(o,(function(){s||(s=!0,a((function(){s=!1,i.isDisposed_||i.track(c)})))}),t.onError,t.requiresObservable)}else i=new lt(o,(function(){this.track(c)}),t.onError,t.requiresObservable);function c(){e(i)}return i.schedule_(),i.getDisposer_()}((function(){var o=n.get();if(!r||t){var a=Ye();e({observableKind:"computed",debugObjectName:n.name_,type:an,object:n,newValue:o,oldValue:i}),Qe(a)}r=!1,i=o}))},n.warnAboutUntrackedRead_=function(){},n.toString=function(){return this.name_+"["+this.derivation.toString()+"]"},n.valueOf=function(){return A(this.get())},n[Re]=function(){return this.valueOf()},t}(),$e=w("ComputedValue",Le);!function(e){e[e.NOT_TRACKING_=-1]="NOT_TRACKING_",e[e.UP_TO_DATE_=0]="UP_TO_DATE_",e[e.POSSIBLY_STALE_=1]="POSSIBLY_STALE_",e[e.STALE_=2]="STALE_"}(Fe||(Fe={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(ze||(ze={}));var He=function(e){this.cause=void 0,this.cause=e};function Be(e){return e instanceof He}function Ge(e){switch(e.dependenciesState_){case Fe.UP_TO_DATE_:return!1;case Fe.NOT_TRACKING_:case Fe.STALE_:return!0;case Fe.POSSIBLY_STALE_:for(var t=Xe(!0),n=Ye(),r=e.observing_,i=r.length,o=0;or&&(r=s.dependenciesState_)}n.length=i,e.newObserving_=null,o=t.length;for(;o--;){var u=t[o];0===u.diffValue_&&it(u,e),u.diffValue_=0}for(;i--;){var c=n[i];1===c.diffValue_&&(c.diffValue_=0,rt(c,e))}r!==Fe.UP_TO_DATE_&&(e.dependenciesState_=r,e.onBecomeStale_())}(e),Ze(r),i}function qe(e){var t=e.observing_;e.observing_=[];for(var n=t.length;n--;)it(t[n],e);e.dependenciesState_=Fe.NOT_TRACKING_}function We(e){var t=Ye();try{return e()}finally{Qe(t)}}function Ye(){var e=nt.trackingDerivation;return nt.trackingDerivation=null,e}function Qe(e){nt.trackingDerivation=e}function Xe(e){var t=nt.allowStateReads;return nt.allowStateReads=e,t}function Ze(e){nt.allowStateReads=e}function Je(e){if(e.dependenciesState_!==Fe.UP_TO_DATE_){e.dependenciesState_=Fe.UP_TO_DATE_;for(var t=e.observing_,n=t.length;n--;)t[n].lowestObserverState_=Fe.UP_TO_DATE_}}var et=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},tt=!0,nt=function(){var t=n();return t.__mobxInstanceCount>0&&!t.__mobxGlobals&&(tt=!1),t.__mobxGlobals&&t.__mobxGlobals.version!==(new et).version&&(tt=!1),tt?t.__mobxGlobals?(t.__mobxInstanceCount+=1,t.__mobxGlobals.UNCHANGED||(t.__mobxGlobals.UNCHANGED={}),t.__mobxGlobals):(t.__mobxInstanceCount=1,t.__mobxGlobals=new et):(setTimeout((function(){e(35)}),1),new et)}();function rt(e,t){e.observers_.add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function it(e,t){e.observers_.delete(t),0===e.observers_.size&&ot(e)}function ot(e){!1===e.isPendingUnobservation_&&(e.isPendingUnobservation_=!0,nt.pendingUnobservations.push(e))}function at(){nt.inBatch++}function st(){if(0==--nt.inBatch){ft();for(var e=nt.pendingUnobservations,t=0;t0&&ot(e),!1)}function ct(e){e.lowestObserverState_!==Fe.STALE_&&(e.lowestObserverState_=Fe.STALE_,e.observers_.forEach((function(e){e.dependenciesState_===Fe.UP_TO_DATE_&&e.onBecomeStale_(),e.dependenciesState_=Fe.STALE_})))}var lt=function(){function t(e,t,n,r){void 0===e&&(e="Reaction"),void 0===r&&(r=!1),this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=Fe.NOT_TRACKING_,this.diffValue_=0,this.runId_=0,this.unboundDepsCount_=0,this.isDisposed_=!1,this.isScheduled_=!1,this.isTrackPending_=!1,this.isRunning_=!1,this.isTracing_=ze.NONE,this.name_=e,this.onInvalidate_=t,this.errorHandler_=n,this.requiresObservable_=r}var n=t.prototype;return n.onBecomeStale_=function(){this.schedule_()},n.schedule_=function(){this.isScheduled_||(this.isScheduled_=!0,nt.pendingReactions.push(this),ft())},n.isScheduled=function(){return this.isScheduled_},n.runReaction_=function(){if(!this.isDisposed_){at(),this.isScheduled_=!1;var e=nt.trackingContext;if(nt.trackingContext=this,Ge(this)){this.isTrackPending_=!0;try{this.onInvalidate_()}catch(e){this.reportExceptionInDerivation_(e)}}nt.trackingContext=e,st()}},n.track=function(e){if(!this.isDisposed_){at(),this.isRunning_=!0;var t=nt.trackingContext;nt.trackingContext=this;var n=Ke(this,e,void 0);nt.trackingContext=t,this.isRunning_=!1,this.isTrackPending_=!1,this.isDisposed_&&qe(this),Be(n)&&this.reportExceptionInDerivation_(n.cause),st()}},n.reportExceptionInDerivation_=function(e){var t=this;if(this.errorHandler_)this.errorHandler_(e,this);else{if(nt.disableErrorBoundaries)throw e;var n="[mobx] uncaught error in '"+this+"'";nt.suppressReactionErrors||console.error(n,e),nt.globalReactionErrorHandlers.forEach((function(n){return n(e,t)}))}},n.dispose=function(){this.isDisposed_||(this.isDisposed_=!0,this.isRunning_||(at(),qe(this),st()))},n.getDisposer_=function(){var e=this.dispose.bind(this);return e[F]=this,e},n.toString=function(){return"Reaction["+this.name_+"]"},n.trace=function(t){void 0===t&&(t=!1),function(){e("trace() is not available in production builds");for(var t=!1,n=arguments.length,r=new Array(n),i=0;i0||nt.isRunningReactions||function(e){e()}(pt)}function pt(){nt.isRunningReactions=!0;for(var e=nt.pendingReactions,t=0;e.length>0;){100==++t&&(console.error("[mobx] cycle in reaction: "+e[0]),e.splice(0));for(var n=e.splice(0),r=0,i=n.length;r",i=function(){var e,t=this,i=arguments,o=++kt,a=Ot(r+" - runid: "+o+" - init",n).apply(t,i),s=void 0,u=new Promise((function(t,n){var i=0;function u(e){var t;s=void 0;try{t=Ot(r+" - runid: "+o+" - yield "+i++,a.next).call(a,e)}catch(e){return n(e)}l(t)}function c(e){var t;s=void 0;try{t=Ot(r+" - runid: "+o+" - yield "+i++,a.throw).call(a,e)}catch(e){return n(e)}l(t)}function l(e){if(!b(null==e?void 0:e.then))return e.done?t(e.value):(s=Promise.resolve(e.value)).then(u,c);e.then(l,n)}e=n,u(void 0)}));return u.cancel=Ot(r+" - runid: "+o+" - cancel",(function(){try{s&&Ut(s);var t=a.return(void 0),n=Promise.resolve(t.value);n.then(h,h),Ut(n),e(new Dt)}catch(t){e(t)}})),u};return i.isMobXFlow=!0,i}),Nt);function Ut(e){b(e.cancel)&&e.cancel()}function Mt(e){return!0===(null==e?void 0:e.isMobXFlow)}function Ft(e,t,n){var r;return Sn(e)||gn(e)||Me(e)?r=Kn(e):Vn(e)&&(r=Kn(e,t)),r.dehancer="function"==typeof t?t:n,function(){r.dehancer=void 0}}function zt(e,t,n){return b(n)?function(e,t,n){return Kn(e,t).intercept_(n)}(e,t,n):function(e,t){return Kn(e).intercept_(t)}(e,t)}function Lt(e){return function(e,t){return!!e&&(void 0!==t?!!Vn(e)&&e[F].values_.has(t):Vn(e)||!!e[F]||L(e)||ht(e)||$e(e))}(e)}function $t(t){return Vn(t)?t[F].keys_():Sn(t)||En(t)?Array.from(t.keys()):gn(t)?t.map((function(e,t){return t})):void e(5)}function Ht(t){return Vn(t)?$t(t).map((function(e){return t[e]})):Sn(t)?$t(t).map((function(e){return t.get(e)})):En(t)?Array.from(t.values()):gn(t)?t.slice():void e(6)}function Bt(t,n,r){if(2!==arguments.length||En(t))Vn(t)?t[F].set_(n,r):Sn(t)?t.set(n,r):En(t)?t.add(n):gn(t)?("number"!=typeof n&&(n=parseInt(n,10)),n<0&&e("Invalid index: '"+n+"'"),at(),n>=t.length&&(t.length=n+1),t[n]=r,st()):e(8);else{at();var i=n;try{for(var o in i)Bt(t,o,i[o])}finally{st()}}}function Gt(t,n,r){if(Vn(t))return t[F].defineProperty_(n,r);e(39)}function Kt(e,t,n,r){return b(n)?function(e,t,n,r){return Kn(e,t).observe_(n,r)}(e,t,n,r):function(e,t,n){return Kn(e).observe_(t,n)}(e,t,n)}function qt(e){switch(e.length){case 0:return nt.trackingDerivation;case 1:return Gn(e[0]);case 2:return Gn(e[0],e[1])}}function Wt(e,t){void 0===t&&(t=void 0),at();try{return e.apply(t)}finally{st()}}function Yt(e){return e[F]}Rt.bound=U(Vt);var Qt={has:function(e,t){return Yt(e).has_(t)},get:function(e,t){return Yt(e).get_(t)},set:function(e,t,n){var r;return!!d(t)&&(null==(r=Yt(e).set_(t,n,!0))||r)},deleteProperty:function(e,t){var n;return!!d(t)&&(null==(n=Yt(e).delete_(t,!0))||n)},defineProperty:function(e,t,n){var r;return null==(r=Yt(e).defineProperty_(t,n))||r},ownKeys:function(e){return Yt(e).ownKeys_()},preventExtensions:function(t){e(13)}};function Xt(e){return void 0!==e.interceptors_&&e.interceptors_.length>0}function Zt(e,t){var n=e.interceptors_||(e.interceptors_=[]);return n.push(t),p((function(){var e=n.indexOf(t);-1!==e&&n.splice(e,1)}))}function Jt(t,n){var r=Ye();try{for(var i=[].concat(t.interceptors_||[]),o=0,a=i.length;o0}function tn(e,t){var n=e.changeListeners_||(e.changeListeners_=[]);return n.push(t),p((function(){var e=n.indexOf(t);-1!==e&&n.splice(e,1)}))}function nn(e,t){var n=Ye(),r=e.changeListeners_;if(r){for(var i=0,o=(r=r.slice()).length;i0?e.map(this.dehancer):e},n.intercept_=function(e){return Zt(this,e)},n.observe_=function(e,t){return void 0===t&&(t=!1),t&&e({observableKind:"array",object:this.proxy_,debugObjectName:this.atom_.name_,type:"splice",index:0,added:this.values_.slice(),addedCount:this.values_.length,removed:[],removedCount:0}),tn(this,e)},n.getArrayLength_=function(){return this.atom_.reportObserved(),this.values_.length},n.setArrayLength_=function(t){("number"!=typeof t||t<0)&&e("Out of range: "+t);var n=this.values_.length;if(t!==n)if(t>n){for(var r=new Array(t-n),i=0;i0&&Hn(t+n+1)},n.spliceWithArray_=function(e,t,n){var r=this;this.atom_;var i=this.values_.length;if(void 0===e?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=1===arguments.length?i-e:null==t?0:Math.max(0,Math.min(t,i-e)),void 0===n&&(n=s),Xt(this)){var o=Jt(this,{object:this.proxy_,type:on,index:e,removedCount:t,added:n});if(!o)return s;t=o.removedCount,n=o.added}if(n=0===n.length?n:n.map((function(e){return r.enhancer_(e,void 0)})),this.legacyMode_){var a=n.length-t;this.updateArrayLength_(i,a)}var u=this.spliceItemsIntoValues_(e,t,n);return 0===t&&0===n.length||this.notifyArraySplice_(e,n,u),this.dehanceValues_(u)},n.spliceItemsIntoValues_=function(e,t,n){var r;if(n.length<1e4)return(r=this.values_).splice.apply(r,[e,t].concat(n));var i=this.values_.slice(e,e+t),o=this.values_.slice(e+t);this.values_.length=e+n.length-t;for(var a=0;a2?n-2:0),i=2;i-1&&(this.splice(n,1),!0)}};function fn(e,t){"function"==typeof Array.prototype[e]&&(ln[e]=t(e))}function pn(e){return function(){var t=this[F];t.atom_.reportObserved();var n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function hn(e){return function(t,n){var r=this,i=this[F];return i.atom_.reportObserved(),i.dehanceValues_(i.values_)[e]((function(e,i){return t.call(n,e,i,r)}))}}function bn(e){return function(){var t=this,n=this[F];n.atom_.reportObserved();var r=n.dehanceValues_(n.values_),i=arguments[0];return arguments[0]=function(e,n,r){return i(e,n,r,t)},r[e].apply(r,arguments)}}fn("concat",pn),fn("flat",pn),fn("includes",pn),fn("indexOf",pn),fn("join",pn),fn("lastIndexOf",pn),fn("slice",pn),fn("toString",pn),fn("toLocaleString",pn),fn("every",hn),fn("filter",hn),fn("find",hn),fn("findIndex",hn),fn("flatMap",hn),fn("forEach",hn),fn("map",hn),fn("some",hn),fn("reduce",bn),fn("reduceRight",bn);var dn,vn,yn=w("ObservableArrayAdministration",un);function gn(e){return v(e)&&yn(e[F])}var mn={},_n="add",wn="delete";dn=Symbol.iterator,vn=Symbol.toStringTag;var On,jn,Pn=function(){function t(t,n,r){void 0===n&&(n=B),void 0===r&&(r="ObservableMap"),this.enhancer_=void 0,this.name_=void 0,this[F]=mn,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=n,this.name_=r,b(Map)||e(18),this.keysAtom_=$("ObservableMap.keys()"),this.data_=new Map,this.hasMap_=new Map,this.merge(t)}var n=t.prototype;return n.has_=function(e){return this.data_.has(e)},n.has=function(e){var t=this;if(!nt.trackingDerivation)return this.has_(e);var n=this.hasMap_.get(e);if(!n){var r=n=new Ue(this.has_(e),G,"ObservableMap.key?",!1);this.hasMap_.set(e,r),It(r,(function(){return t.hasMap_.delete(e)}))}return n.get()},n.set=function(e,t){var n=this.has_(e);if(Xt(this)){var r=Jt(this,{type:n?an:_n,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.updateValue_(e,t):this.addValue_(e,t),this},n.delete=function(e){var t=this;if((this.keysAtom_,Xt(this))&&!Jt(this,{type:wn,object:this,name:e}))return!1;if(this.has_(e)){var n=en(this),r=n?{observableKind:"map",debugObjectName:this.name_,type:wn,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return Wt((function(){t.keysAtom_.reportChanged(),t.updateHasMapEntry_(e,!1),t.data_.get(e).setNewValue_(void 0),t.data_.delete(e)})),n&&nn(this,r),!0}return!1},n.updateHasMapEntry_=function(e,t){var n=this.hasMap_.get(e);n&&n.setNewValue_(t)},n.updateValue_=function(e,t){var n=this.data_.get(e);if((t=n.prepareNewValue_(t))!==nt.UNCHANGED){var r=en(this),i=r?{observableKind:"map",debugObjectName:this.name_,type:an,object:this,oldValue:n.value_,name:e,newValue:t}:null;n.setNewValue_(t),r&&nn(this,i)}},n.addValue_=function(e,t){var n=this;this.keysAtom_,Wt((function(){var r=new Ue(t,n.enhancer_,"ObservableMap.key",!1);n.data_.set(e,r),t=r.value_,n.updateHasMapEntry_(e,!0),n.keysAtom_.reportChanged()}));var r=en(this),i=r?{observableKind:"map",debugObjectName:this.name_,type:_n,object:this,name:e,newValue:t}:null;r&&nn(this,i)},n.get=function(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)},n.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},n.keys=function(){return this.keysAtom_.reportObserved(),this.data_.keys()},n.values=function(){var e=this,t=this.keys();return Zn({next:function(){var n=t.next(),r=n.done,i=n.value;return{done:r,value:r?void 0:e.get(i)}}})},n.entries=function(){var e=this,t=this.keys();return Zn({next:function(){var n=t.next(),r=n.done,i=n.value;return{done:r,value:r?void 0:[i,e.get(i)]}}})},n[dn]=function(){return this.entries()},n.forEach=function(e,t){for(var n,r=V(this);!(n=r()).done;){var i=n.value,o=i[0],a=i[1];e.call(t,a,o,this)}},n.merge=function(t){var n=this;return Sn(t)&&(t=new Map(t)),Wt((function(){y(t)?function(e){var t=Object.keys(e);if(!P)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter((function(t){return a.propertyIsEnumerable.call(e,t)}))):t}(t).forEach((function(e){return n.set(e,t[e])})):Array.isArray(t)?t.forEach((function(e){var t=e[0],r=e[1];return n.set(t,r)})):O(t)?(t.constructor!==Map&&e(19,t),t.forEach((function(e,t){return n.set(t,e)}))):null!=t&&e(20,t)})),this},n.clear=function(){var e=this;Wt((function(){We((function(){for(var t,n=V(e.keys());!(t=n()).done;){var r=t.value;e.delete(r)}}))}))},n.replace=function(t){var n=this;return Wt((function(){for(var r,i=function(t){if(O(t)||Sn(t))return t;if(Array.isArray(t))return new Map(t);if(y(t)){var n=new Map;for(var r in t)n.set(r,t[r]);return n}return e(21,t)}(t),o=new Map,a=!1,s=V(n.data_.keys());!(r=s()).done;){var u=r.value;if(!i.has(u))if(n.delete(u))a=!0;else{var c=n.data_.get(u);o.set(u,c)}}for(var l,f=V(i.entries());!(l=f()).done;){var p=l.value,h=p[0],b=p[1],d=n.data_.has(h);if(n.set(h,b),n.data_.has(h)){var v=n.data_.get(h);o.set(h,v),d||(a=!0)}}if(!a)if(n.data_.size!==o.size)n.keysAtom_.reportChanged();else for(var g=n.data_.keys(),m=o.keys(),_=g.next(),w=m.next();!_.done;){if(_.value!==w.value){n.keysAtom_.reportChanged();break}_=g.next(),w=m.next()}n.data_=o})),this},n.toString=function(){return"[object ObservableMap]"},n.toJSON=function(){return Array.from(this)},n.observe_=function(e,t){return tn(this,e)},n.intercept_=function(e){return Zt(this,e)},I(t,[{key:"size",get:function(){return this.keysAtom_.reportObserved(),this.data_.size}},{key:vn,get:function(){return"Map"}}]),t}(),Sn=w("ObservableMap",Pn);var An={};On=Symbol.iterator,jn=Symbol.toStringTag;var xn=function(){function t(t,n,r){void 0===n&&(n=B),void 0===r&&(r="ObservableSet"),this.name_=void 0,this[F]=An,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=r,b(Set)||e(22),this.atom_=$(this.name_),this.enhancer_=function(e,t){return n(e,t,r)},t&&this.replace(t)}var n=t.prototype;return n.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},n.clear=function(){var e=this;Wt((function(){We((function(){for(var t,n=V(e.data_.values());!(t=n()).done;){var r=t.value;e.delete(r)}}))}))},n.forEach=function(e,t){for(var n,r=V(this);!(n=r()).done;){var i=n.value;e.call(t,i,i,this)}},n.add=function(e){var t=this;if((this.atom_,Xt(this))&&!Jt(this,{type:_n,object:this,newValue:e}))return this;if(!this.has(e)){Wt((function(){t.data_.add(t.enhancer_(e,void 0)),t.atom_.reportChanged()}));var n=en(this),r=n?{observableKind:"set",debugObjectName:this.name_,type:_n,object:this,newValue:e}:null;n&&nn(this,r)}return this},n.delete=function(e){var t=this;if(Xt(this)&&!Jt(this,{type:wn,object:this,oldValue:e}))return!1;if(this.has(e)){var n=en(this),r=n?{observableKind:"set",debugObjectName:this.name_,type:wn,object:this,oldValue:e}:null;return Wt((function(){t.atom_.reportChanged(),t.data_.delete(e)})),n&&nn(this,r),!0}return!1},n.has=function(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))},n.entries=function(){var e=0,t=Array.from(this.keys()),n=Array.from(this.values());return Zn({next:function(){var r=e;return e+=1,rFn){for(var t=Fn;t=0&&n++}e=Xn(e),t=Xn(t);var s="[object Array]"===a;if(!s){if("object"!=typeof e||"object"!=typeof t)return!1;var u=e.constructor,c=t.constructor;if(u!==c&&!(b(u)&&u instanceof u&&b(c)&&c instanceof c)&&"constructor"in e&&"constructor"in t)return!1}if(0===n)return!1;n<0&&(n=-1),i=i||[];for(var l=(r=r||[]).length;l--;)if(r[l]===e)return i[l]===t;if(r.push(e),i.push(t),s){if((l=e.length)!==t.length)return!1;for(;l--;)if(!Qn(e[l],t[l],n-1,r,i))return!1}else{var f,p=Object.keys(e);if(l=p.length,Object.keys(t).length!==l)return!1;for(;l--;)if(!x(t,f=p[l])||!Qn(e[f],t[f],n-1,r,i))return!1}return r.pop(),i.pop(),!0}function Xn(e){return gn(e)?e.slice():O(e)||Sn(e)||j(e)||En(e)?Array.from(e.entries()):e}function Zn(e){return e[Symbol.iterator]=Jn,e}function Jn(){return this}["Symbol","Map","Set","Symbol"].forEach((function(t){void 0===n()[t]&&e("MobX requires global '"+t+"' to be available or polyfilled")})),"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:function(e){return console.warn("[mobx.spy] Is a no-op in production builds"),function(){}},extras:{getDebugName:qn},$mobx:F});var er;!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(er||(er={})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).JSpider=t()}(this,(function(){"use strict";function e(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;ne.length)&&(t=e.length);for(var r=0,n=new Array(t);r=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=e[Symbol.iterator]()).next.bind(r)}var R=Symbol("mobx-stored-annotations");function U(e){return Object.assign((function(t,r){M(t,r,e)}),e)}function M(e,t,r){x(e,R)||m(e,R,C({},e[R])),function(e){return e.annotationType_===K}(r)||(e[R][t]=r)}var z=Symbol("mobx administration"),F=function(){function e(e){void 0===e&&(e="Atom"),this.name_=void 0,this.isPendingUnobservation_=!1,this.isBeingObserved_=!1,this.observers_=new Set,this.diffValue_=0,this.lastAccessedBy_=0,this.lowestObserverState_=ze.NOT_TRACKING_,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return ut(this)},t.reportChanged=function(){at(),ct(this),st()},t.toString=function(){return this.name_},e}(),L=w("Atom",F);function $(e,t,r){void 0===t&&(t=h),void 0===r&&(r=h);var n,i=new F(e);return t!==h&&Ct(Tt,i,t,n),r!==h&&It(i,r),i}var H={identity:function(e,t){return e===t},structural:function(e,t){return Wr(e,t)},default:function(e,t){return Object.is(e,t)},shallow:function(e,t){return Wr(e,t,1)}};function B(e,t,r){return Lt(e)?e:Array.isArray(e)?Oe.array(e,{name:r}):y(e)?Oe.object(e,void 0,{name:r}):O(e)?Oe.map(e,{name:r}):j(e)?Oe.set(e,{name:r}):"function"!=typeof e||St(e)||Mt(e)?e:g(e)?Rt(e):jt(r,e)}function G(e){return e}var K="override";function q(e,t){return{annotationType_:e,options_:t,make_:W,extend_:Y}}function W(e,t,r,n){var i;if(null==(i=this.options_)?void 0:i.bound)return null===this.extend_(e,t,r,!1)?0:1;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if(St(r.value))return 1;var a=Q(e,this,t,r,!1);return o(n,t,a),2}function Y(e,t,r,n){var i=Q(e,this,t,r);return e.defineProperty_(t,i,n)}function Q(e,t,r,n,i){var o,a,s,u,c,l;void 0===i&&(i=rt.safeDescriptors),l=n,t.annotationType_,l.value;var f,p=n.value;(null==(o=t.options_)?void 0:o.bound)&&(p=p.bind(null!=(f=e.proxy_)?f:e.target_));return{value:ke(null!=(a=null==(s=t.options_)?void 0:s.name)?a:r.toString(),p,null!=(u=null==(c=t.options_)?void 0:c.autoAction)&&u),configurable:!i||e.isPlainObject_,enumerable:!1,writable:!i}}function X(e,t){return{annotationType_:e,options_:t,make_:Z,extend_:J}}function Z(e,t,r,n){var i;if(n===e.target_)return null===this.extend_(e,t,r,!1)?0:2;if((null==(i=this.options_)?void 0:i.bound)&&!Mt(e.target_[t])&&null===this.extend_(e,t,r,!1))return 0;if(Mt(r.value))return 1;var a=ee(e,this,t,r,!1,!1);return o(n,t,a),2}function J(e,t,r,n){var i,o=ee(e,this,t,r,null==(i=this.options_)?void 0:i.bound);return e.defineProperty_(t,o,n)}function ee(e,t,r,n,i,o){var a;void 0===o&&(o=rt.safeDescriptors),a=n,t.annotationType_,a.value;var s,u=n.value;i&&(u=u.bind(null!=(s=e.proxy_)?s:e.target_));return{value:Rt(u),configurable:!o||e.isPlainObject_,enumerable:!1,writable:!o}}function te(e,t){return{annotationType_:e,options_:t,make_:re,extend_:ne}}function re(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function ne(e,t,r,n){var i;return i=r,this.annotationType_,i.get,e.defineComputedProperty_(t,C({},this.options_,{get:r.get,set:r.set}),n)}function ie(e,t){return{annotationType_:e,options_:t,make_:oe,extend_:ae}}function oe(e,t,r){return null===this.extend_(e,t,r,!1)?0:1}function ae(e,t,r,n){var i,o;return this.annotationType_,e.defineObservableProperty_(t,r.value,null!=(i=null==(o=this.options_)?void 0:o.enhancer)?i:B,n)}var se=ue();function ue(e){return{annotationType_:"true",options_:e,make_:ce,extend_:le}}function ce(e,t,r,n){var i,a,s,u;if(r.get)return Ae.make_(e,t,r,n);if(r.set){var c=ke(t.toString(),r.set);return n===e.target_?null===e.defineProperty_(t,{configurable:!rt.safeDescriptors||e.isPlainObject_,set:c})?0:2:(o(n,t,{configurable:!0,set:c}),2)}if(n!==e.target_&&"function"==typeof r.value)return g(r.value)?((null==(u=this.options_)?void 0:u.autoBind)?Rt.bound:Rt).make_(e,t,r,n):((null==(s=this.options_)?void 0:s.autoBind)?jt.bound:jt).make_(e,t,r,n);var l,f=!1===(null==(i=this.options_)?void 0:i.deep)?Oe.ref:Oe;"function"==typeof r.value&&(null==(a=this.options_)?void 0:a.autoBind)&&(r.value=r.value.bind(null!=(l=e.proxy_)?l:e.target_));return f.make_(e,t,r,n)}function le(e,t,r,n){var i,o,a;if(r.get)return Ae.extend_(e,t,r,n);if(r.set)return e.defineProperty_(t,{configurable:!rt.safeDescriptors||e.isPlainObject_,set:ke(t.toString(),r.set)},n);"function"==typeof r.value&&(null==(i=this.options_)?void 0:i.autoBind)&&(r.value=r.value.bind(null!=(a=e.proxy_)?a:e.target_));return(!1===(null==(o=this.options_)?void 0:o.deep)?Oe.ref:Oe).extend_(e,t,r,n)}var fe={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function pe(e){return e||fe}Object.freeze(fe);var he=ie("observable"),be=ie("observable.ref",{enhancer:G}),de=ie("observable.shallow",{enhancer:function(e,t,r){return null==e||Nr(e)||yr(e)||Pr(e)||xr(e)?e:Array.isArray(e)?Oe.array(e,{name:r,deep:!1}):y(e)?Oe.object(e,void 0,{name:r,deep:!1}):O(e)?Oe.map(e,{name:r,deep:!1}):j(e)?Oe.set(e,{name:r,deep:!1}):void 0}}),ve=ie("observable.struct",{enhancer:function(e,t){return Wr(e,t)?t:e}}),ye=U(he);function ge(e){return!0===e.deep?B:!1===e.deep?G:(t=e.defaultDecorator)&&null!=(r=null==(n=t.options_)?void 0:n.enhancer)?r:B;var t,r,n}function me(e,t,r){if(!d(t))return Lt(e)?e:y(e)?Oe.object(e,t,r):Array.isArray(e)?Oe.array(e,t):O(e)?Oe.map(e,t):j(e)?Oe.set(e,t):"object"==typeof e&&null!==e?e:Oe.box(e,t);M(e,t,he)}Object.assign(me,ye);var _e,we,Oe=n(me,{box:function(e,t){var r=pe(t);return new Ue(e,ge(r),r.name,!0,r.equals)},array:function(e,t){var r=pe(t);return(!1===rt.useProxies||!1===r.proxy?Hr:ur)(e,ge(r),r.name)},map:function(e,t){var r=pe(t);return new jr(e,ge(r),r.name)},set:function(e,t){var r=pe(t);return new Ar(e,ge(r),r.name)},object:function(e,t,r){return function(e,t,r,n){var i=E(t),o=Cr(e,n)[z];at();try{S(i).forEach((function(e){o.extend_(e,i[e],!r||(!(e in r)||r[e]))}))}finally{st()}return e}(!1===rt.useProxies||!1===(null==r?void 0:r.proxy)?Cr({},r):function(e,t){var r,n;return f(),e=Cr(e,t),null!=(n=(r=e[z]).proxy_)?n:r.proxy_=new Proxy(e,Qt)}({},r),e,t)},ref:U(be),shallow:U(de),deep:ye,struct:U(ve)}),je="computed",Pe=te(je),Se=te("computed.struct",{equals:H.structural}),Ae=function(e,t){if(d(t))return M(e,t,Pe);if(y(e))return U(te(je,e));var r=y(t)?t:{};return r.get=e,r.name||(r.name=e.name||""),new Le(r)};Object.assign(Ae,Pe),Ae.struct=U(Se);var xe,Ee=0,Te=1,Ie=null!=(_e=null==(we=i((function(){}),"name"))?void 0:we.configurable)&&_e,Ce={value:"action",configurable:!0,writable:!1,enumerable:!1};function ke(e,t,r,n){function i(){return De(e,r,t,n||this,arguments)}return void 0===r&&(r=!1),i.isMobxAction=!0,Ie&&(Ce.value=e,Object.defineProperty(i,"name",Ce)),i}function De(t,r,n,i,o){var a=function(e,t,r,n){var i=!1,o=0,a=rt.trackingDerivation,s=!t||!a;at();var u=rt.allowStateChanges;s&&(Ye(),u=Ne(!0));var c=Xe(!0),l={runAsAction_:s,prevDerivation_:a,prevAllowStateChanges_:u,prevAllowStateReads_:c,notifySpy_:i,startTime_:o,actionId_:Te++,parentActionId_:Ee};return Ee=l.actionId_,l}(0,r);try{return n.apply(i,o)}catch(e){throw a.error_=e,e}finally{!function(t){Ee!==t.actionId_&&e(30);Ee=t.parentActionId_,void 0!==t.error_&&(rt.suppressReactionErrors=!0);Ve(t.prevAllowStateChanges_),Ze(t.prevAllowStateReads_),st(),t.runAsAction_&&Qe(t.prevDerivation_);rt.suppressReactionErrors=!1}(a)}}function Ne(e){var t=rt.allowStateChanges;return rt.allowStateChanges=e,t}function Ve(e){rt.allowStateChanges=e}xe=Symbol.toPrimitive;var Re,Ue=function(e){function t(t,r,n,i,o){var a;return void 0===n&&(n="ObservableValue"),void 0===o&&(o=H.default),(a=e.call(this,n)||this).enhancer=void 0,a.name_=void 0,a.equals=void 0,a.hasUnreportedChange_=!1,a.interceptors_=void 0,a.changeListeners_=void 0,a.value_=void 0,a.dehancer=void 0,a.enhancer=r,a.name_=n,a.equals=o,a.value_=r(t,void 0,n),a}k(t,e);var r=t.prototype;return r.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.set=function(e){this.value_,(e=this.prepareNewValue_(e))!==rt.UNCHANGED&&this.setNewValue_(e)},r.prepareNewValue_=function(e){if(Xt(this)){var t=Jt(this,{object:this,type:or,newValue:e});if(!t)return rt.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value_,this.name_),this.equals(this.value_,e)?rt.UNCHANGED:e},r.setNewValue_=function(e){var t=this.value_;this.value_=e,this.reportChanged(),er(this)&&rr(this,{type:or,object:this,newValue:e,oldValue:t})},r.get=function(){return this.reportObserved(),this.dehanceValue(this.value_)},r.intercept_=function(e){return Zt(this,e)},r.observe_=function(e,t){return t&&e({observableKind:"value",debugObjectName:this.name_,object:this,type:or,newValue:this.value_,oldValue:void 0}),tr(this,e)},r.raw=function(){return this.value_},r.toJSON=function(){return this.get()},r.toString=function(){return this.name_+"["+this.value_+"]"},r.valueOf=function(){return A(this.get())},r[xe]=function(){return this.valueOf()},t}(F),Me=w("ObservableValue",Ue);Re=Symbol.toPrimitive;var ze,Fe,Le=function(){function t(t){this.dependenciesState_=ze.NOT_TRACKING_,this.observing_=[],this.newObserving_=null,this.isBeingObserved_=!1,this.isPendingUnobservation_=!1,this.observers_=new Set,this.diffValue_=0,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=ze.UP_TO_DATE_,this.unboundDepsCount_=0,this.value_=new He(null),this.name_=void 0,this.triggeredBy_=void 0,this.isComputing_=!1,this.isRunningSetter_=!1,this.derivation=void 0,this.setter_=void 0,this.isTracing_=Fe.NONE,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,t.get||e(31),this.derivation=t.get,this.name_=t.name||"ComputedValue",t.set&&(this.setter_=ke("ComputedValue-setter",t.set)),this.equals_=t.equals||(t.compareStructural||t.struct?H.structural:H.default),this.scope_=t.context,this.requiresReaction_=!!t.requiresReaction,this.keepAlive_=!!t.keepAlive}var r=t.prototype;return r.onBecomeStale_=function(){!function(e){if(e.lowestObserverState_!==ze.UP_TO_DATE_)return;e.lowestObserverState_=ze.POSSIBLY_STALE_,e.observers_.forEach((function(e){e.dependenciesState_===ze.UP_TO_DATE_&&(e.dependenciesState_=ze.POSSIBLY_STALE_,e.onBecomeStale_())}))}(this)},r.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},r.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},r.get=function(){if(this.isComputing_&&e(32,this.name_,this.derivation),0!==rt.inBatch||0!==this.observers_.size||this.keepAlive_){if(ut(this),Ge(this)){var t=rt.trackingContext;this.keepAlive_&&!t&&(rt.trackingContext=this),this.trackAndCompute()&&function(e){if(e.lowestObserverState_===ze.STALE_)return;e.lowestObserverState_=ze.STALE_,e.observers_.forEach((function(t){t.dependenciesState_===ze.POSSIBLY_STALE_?t.dependenciesState_=ze.STALE_:t.dependenciesState_===ze.UP_TO_DATE_&&(e.lowestObserverState_=ze.UP_TO_DATE_)}))}(this),rt.trackingContext=t}}else Ge(this)&&(this.warnAboutUntrackedRead_(),at(),this.value_=this.computeValue_(!1),st());var r=this.value_;if(Be(r))throw r.cause;return r},r.set=function(t){if(this.setter_){this.isRunningSetter_&&e(33,this.name_),this.isRunningSetter_=!0;try{this.setter_.call(this.scope_,t)}finally{this.isRunningSetter_=!1}}else e(34,this.name_)},r.trackAndCompute=function(){var e=this.value_,t=this.dependenciesState_===ze.NOT_TRACKING_,r=this.computeValue_(!0),n=t||Be(e)||Be(r)||!this.equals_(e,r);return n&&(this.value_=r),n},r.computeValue_=function(e){this.isComputing_=!0;var t,r=Ne(!1);if(e)t=Ke(this,this.derivation,this.scope_);else if(!0===rt.disableErrorBoundaries)t=this.derivation.call(this.scope_);else try{t=this.derivation.call(this.scope_)}catch(e){t=new He(e)}return Ve(r),this.isComputing_=!1,t},r.suspend_=function(){this.keepAlive_||(qe(this),this.value_=void 0)},r.observe_=function(e,t){var r=this,n=!0,i=void 0;return function(e,t){var r,n;void 0===t&&(t=u);var i,o=null!=(r=null==(n=t)?void 0:n.name)?r:"Autorun";if(t.scheduler||t.delay){var a=xt(t),s=!1;i=new lt(o,(function(){s||(s=!0,a((function(){s=!1,i.isDisposed_||i.track(c)})))}),t.onError,t.requiresObservable)}else i=new lt(o,(function(){this.track(c)}),t.onError,t.requiresObservable);function c(){e(i)}return i.schedule_(),i.getDisposer_()}((function(){var o=r.get();if(!n||t){var a=Ye();e({observableKind:"computed",debugObjectName:r.name_,type:or,object:r,newValue:o,oldValue:i}),Qe(a)}n=!1,i=o}))},r.warnAboutUntrackedRead_=function(){},r.toString=function(){return this.name_+"["+this.derivation.toString()+"]"},r.valueOf=function(){return A(this.get())},r[Re]=function(){return this.valueOf()},t}(),$e=w("ComputedValue",Le);!function(e){e[e.NOT_TRACKING_=-1]="NOT_TRACKING_",e[e.UP_TO_DATE_=0]="UP_TO_DATE_",e[e.POSSIBLY_STALE_=1]="POSSIBLY_STALE_",e[e.STALE_=2]="STALE_"}(ze||(ze={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(Fe||(Fe={}));var He=function(e){this.cause=void 0,this.cause=e};function Be(e){return e instanceof He}function Ge(e){switch(e.dependenciesState_){case ze.UP_TO_DATE_:return!1;case ze.NOT_TRACKING_:case ze.STALE_:return!0;case ze.POSSIBLY_STALE_:for(var t=Xe(!0),r=Ye(),n=e.observing_,i=n.length,o=0;on&&(n=s.dependenciesState_)}r.length=i,e.newObserving_=null,o=t.length;for(;o--;){var u=t[o];0===u.diffValue_&&it(u,e),u.diffValue_=0}for(;i--;){var c=r[i];1===c.diffValue_&&(c.diffValue_=0,nt(c,e))}n!==ze.UP_TO_DATE_&&(e.dependenciesState_=n,e.onBecomeStale_())}(e),Ze(n),i}function qe(e){var t=e.observing_;e.observing_=[];for(var r=t.length;r--;)it(t[r],e);e.dependenciesState_=ze.NOT_TRACKING_}function We(e){var t=Ye();try{return e()}finally{Qe(t)}}function Ye(){var e=rt.trackingDerivation;return rt.trackingDerivation=null,e}function Qe(e){rt.trackingDerivation=e}function Xe(e){var t=rt.allowStateReads;return rt.allowStateReads=e,t}function Ze(e){rt.allowStateReads=e}function Je(e){if(e.dependenciesState_!==ze.UP_TO_DATE_){e.dependenciesState_=ze.UP_TO_DATE_;for(var t=e.observing_,r=t.length;r--;)t[r].lowestObserverState_=ze.UP_TO_DATE_}}var et=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},tt=!0,rt=function(){var t=r();return t.__mobxInstanceCount>0&&!t.__mobxGlobals&&(tt=!1),t.__mobxGlobals&&t.__mobxGlobals.version!==(new et).version&&(tt=!1),tt?t.__mobxGlobals?(t.__mobxInstanceCount+=1,t.__mobxGlobals.UNCHANGED||(t.__mobxGlobals.UNCHANGED={}),t.__mobxGlobals):(t.__mobxInstanceCount=1,t.__mobxGlobals=new et):(setTimeout((function(){e(35)}),1),new et)}();function nt(e,t){e.observers_.add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function it(e,t){e.observers_.delete(t),0===e.observers_.size&&ot(e)}function ot(e){!1===e.isPendingUnobservation_&&(e.isPendingUnobservation_=!0,rt.pendingUnobservations.push(e))}function at(){rt.inBatch++}function st(){if(0==--rt.inBatch){ft();for(var e=rt.pendingUnobservations,t=0;t0&&ot(e),!1)}function ct(e){e.lowestObserverState_!==ze.STALE_&&(e.lowestObserverState_=ze.STALE_,e.observers_.forEach((function(e){e.dependenciesState_===ze.UP_TO_DATE_&&e.onBecomeStale_(),e.dependenciesState_=ze.STALE_})))}var lt=function(){function t(e,t,r,n){void 0===e&&(e="Reaction"),void 0===n&&(n=!1),this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=ze.NOT_TRACKING_,this.diffValue_=0,this.runId_=0,this.unboundDepsCount_=0,this.isDisposed_=!1,this.isScheduled_=!1,this.isTrackPending_=!1,this.isRunning_=!1,this.isTracing_=Fe.NONE,this.name_=e,this.onInvalidate_=t,this.errorHandler_=r,this.requiresObservable_=n}var r=t.prototype;return r.onBecomeStale_=function(){this.schedule_()},r.schedule_=function(){this.isScheduled_||(this.isScheduled_=!0,rt.pendingReactions.push(this),ft())},r.isScheduled=function(){return this.isScheduled_},r.runReaction_=function(){if(!this.isDisposed_){at(),this.isScheduled_=!1;var e=rt.trackingContext;if(rt.trackingContext=this,Ge(this)){this.isTrackPending_=!0;try{this.onInvalidate_()}catch(e){this.reportExceptionInDerivation_(e)}}rt.trackingContext=e,st()}},r.track=function(e){if(!this.isDisposed_){at(),this.isRunning_=!0;var t=rt.trackingContext;rt.trackingContext=this;var r=Ke(this,e,void 0);rt.trackingContext=t,this.isRunning_=!1,this.isTrackPending_=!1,this.isDisposed_&&qe(this),Be(r)&&this.reportExceptionInDerivation_(r.cause),st()}},r.reportExceptionInDerivation_=function(e){var t=this;if(this.errorHandler_)this.errorHandler_(e,this);else{if(rt.disableErrorBoundaries)throw e;var r="[mobx] uncaught error in '"+this+"'";rt.suppressReactionErrors||console.error(r,e),rt.globalReactionErrorHandlers.forEach((function(r){return r(e,t)}))}},r.dispose=function(){this.isDisposed_||(this.isDisposed_=!0,this.isRunning_||(at(),qe(this),st()))},r.getDisposer_=function(){var e=this.dispose.bind(this);return e[z]=this,e},r.toString=function(){return"Reaction["+this.name_+"]"},r.trace=function(t){void 0===t&&(t=!1),function(){e("trace() is not available in production builds");for(var t=!1,r=arguments.length,n=new Array(r),i=0;i0||rt.isRunningReactions||function(e){e()}(pt)}function pt(){rt.isRunningReactions=!0;for(var e=rt.pendingReactions,t=0;e.length>0;){100==++t&&(console.error("[mobx] cycle in reaction: "+e[0]),e.splice(0));for(var r=e.splice(0),n=0,i=r.length;n",i=function(){var e,t=this,i=arguments,o=++kt,a=Ot(n+" - runid: "+o+" - init",r).apply(t,i),s=void 0,u=new Promise((function(t,r){var i=0;function u(e){var t;s=void 0;try{t=Ot(n+" - runid: "+o+" - yield "+i++,a.next).call(a,e)}catch(e){return r(e)}l(t)}function c(e){var t;s=void 0;try{t=Ot(n+" - runid: "+o+" - yield "+i++,a.throw).call(a,e)}catch(e){return r(e)}l(t)}function l(e){if(!b(null==e?void 0:e.then))return e.done?t(e.value):(s=Promise.resolve(e.value)).then(u,c);e.then(l,r)}e=r,u(void 0)}));return u.cancel=Ot(n+" - runid: "+o+" - cancel",(function(){try{s&&Ut(s);var t=a.return(void 0),r=Promise.resolve(t.value);r.then(h,h),Ut(r),e(new Dt)}catch(t){e(t)}})),u};return i.isMobXFlow=!0,i}),Nt);function Ut(e){b(e.cancel)&&e.cancel()}function Mt(e){return!0===(null==e?void 0:e.isMobXFlow)}function zt(e,t,r){var n;return Pr(e)||yr(e)||Me(e)?n=Gr(e):Nr(e)&&(n=Gr(e,t)),n.dehancer="function"==typeof t?t:r,function(){n.dehancer=void 0}}function Ft(e,t,r){return b(r)?function(e,t,r){return Gr(e,t).intercept_(r)}(e,t,r):function(e,t){return Gr(e).intercept_(t)}(e,t)}function Lt(e){return function(e,t){return!!e&&(void 0!==t?!!Nr(e)&&e[z].values_.has(t):Nr(e)||!!e[z]||L(e)||ht(e)||$e(e))}(e)}function $t(t){return Nr(t)?t[z].keys_():Pr(t)||xr(t)?Array.from(t.keys()):yr(t)?t.map((function(e,t){return t})):void e(5)}function Ht(t){return Nr(t)?$t(t).map((function(e){return t[e]})):Pr(t)?$t(t).map((function(e){return t.get(e)})):xr(t)?Array.from(t.values()):yr(t)?t.slice():void e(6)}function Bt(t,r,n){if(2!==arguments.length||xr(t))Nr(t)?t[z].set_(r,n):Pr(t)?t.set(r,n):xr(t)?t.add(r):yr(t)?("number"!=typeof r&&(r=parseInt(r,10)),r<0&&e("Invalid index: '"+r+"'"),at(),r>=t.length&&(t.length=r+1),t[r]=n,st()):e(8);else{at();var i=r;try{for(var o in i)Bt(t,o,i[o])}finally{st()}}}function Gt(t,r,n){if(Nr(t))return t[z].defineProperty_(r,n);e(39)}function Kt(e,t,r,n){return b(r)?function(e,t,r,n){return Gr(e,t).observe_(r,n)}(e,t,r,n):function(e,t,r){return Gr(e).observe_(t,r)}(e,t,r)}function qt(e){switch(e.length){case 0:return rt.trackingDerivation;case 1:return Br(e[0]);case 2:return Br(e[0],e[1])}}function Wt(e,t){void 0===t&&(t=void 0),at();try{return e.apply(t)}finally{st()}}function Yt(e){return e[z]}Rt.bound=U(Vt);var Qt={has:function(e,t){return Yt(e).has_(t)},get:function(e,t){return Yt(e).get_(t)},set:function(e,t,r){var n;return!!d(t)&&(null==(n=Yt(e).set_(t,r,!0))||n)},deleteProperty:function(e,t){var r;return!!d(t)&&(null==(r=Yt(e).delete_(t,!0))||r)},defineProperty:function(e,t,r){var n;return null==(n=Yt(e).defineProperty_(t,r))||n},ownKeys:function(e){return Yt(e).ownKeys_()},preventExtensions:function(t){e(13)}};function Xt(e){return void 0!==e.interceptors_&&e.interceptors_.length>0}function Zt(e,t){var r=e.interceptors_||(e.interceptors_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function Jt(t,r){var n=Ye();try{for(var i=[].concat(t.interceptors_||[]),o=0,a=i.length;o0}function tr(e,t){var r=e.changeListeners_||(e.changeListeners_=[]);return r.push(t),p((function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}))}function rr(e,t){var r=Ye(),n=e.changeListeners_;if(n){for(var i=0,o=(n=n.slice()).length;i0?e.map(this.dehancer):e},r.intercept_=function(e){return Zt(this,e)},r.observe_=function(e,t){return void 0===t&&(t=!1),t&&e({observableKind:"array",object:this.proxy_,debugObjectName:this.atom_.name_,type:"splice",index:0,added:this.values_.slice(),addedCount:this.values_.length,removed:[],removedCount:0}),tr(this,e)},r.getArrayLength_=function(){return this.atom_.reportObserved(),this.values_.length},r.setArrayLength_=function(t){("number"!=typeof t||t<0)&&e("Out of range: "+t);var r=this.values_.length;if(t!==r)if(t>r){for(var n=new Array(t-r),i=0;i0&&$r(t+r+1)},r.spliceWithArray_=function(e,t,r){var n=this;this.atom_;var i=this.values_.length;if(void 0===e?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=1===arguments.length?i-e:null==t?0:Math.max(0,Math.min(t,i-e)),void 0===r&&(r=s),Xt(this)){var o=Jt(this,{object:this.proxy_,type:ir,index:e,removedCount:t,added:r});if(!o)return s;t=o.removedCount,r=o.added}if(r=0===r.length?r:r.map((function(e){return n.enhancer_(e,void 0)})),this.legacyMode_){var a=r.length-t;this.updateArrayLength_(i,a)}var u=this.spliceItemsIntoValues_(e,t,r);return 0===t&&0===r.length||this.notifyArraySplice_(e,r,u),this.dehanceValues_(u)},r.spliceItemsIntoValues_=function(e,t,r){var n;if(r.length<1e4)return(n=this.values_).splice.apply(n,[e,t].concat(r));var i=this.values_.slice(e,e+t),o=this.values_.slice(e+t);this.values_.length=e+r.length-t;for(var a=0;a2?r-2:0),i=2;i-1&&(this.splice(r,1),!0)}};function lr(e,t){"function"==typeof Array.prototype[e]&&(cr[e]=t(e))}function fr(e){return function(){var t=this[z];t.atom_.reportObserved();var r=t.dehanceValues_(t.values_);return r[e].apply(r,arguments)}}function pr(e){return function(t,r){var n=this,i=this[z];return i.atom_.reportObserved(),i.dehanceValues_(i.values_)[e]((function(e,i){return t.call(r,e,i,n)}))}}function hr(e){return function(){var t=this,r=this[z];r.atom_.reportObserved();var n=r.dehanceValues_(r.values_),i=arguments[0];return arguments[0]=function(e,r,n){return i(e,r,n,t)},n[e].apply(n,arguments)}}lr("concat",fr),lr("flat",fr),lr("includes",fr),lr("indexOf",fr),lr("join",fr),lr("lastIndexOf",fr),lr("slice",fr),lr("toString",fr),lr("toLocaleString",fr),lr("every",pr),lr("filter",pr),lr("find",pr),lr("findIndex",pr),lr("flatMap",pr),lr("forEach",pr),lr("map",pr),lr("some",pr),lr("reduce",hr),lr("reduceRight",hr);var br,dr,vr=w("ObservableArrayAdministration",sr);function yr(e){return v(e)&&vr(e[z])}var gr={},mr="add",_r="delete";br=Symbol.iterator,dr=Symbol.toStringTag;var wr,Or,jr=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableMap"),this.enhancer_=void 0,this.name_=void 0,this[z]=gr,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=r,this.name_=n,b(Map)||e(18),this.keysAtom_=$("ObservableMap.keys()"),this.data_=new Map,this.hasMap_=new Map,this.merge(t)}var r=t.prototype;return r.has_=function(e){return this.data_.has(e)},r.has=function(e){var t=this;if(!rt.trackingDerivation)return this.has_(e);var r=this.hasMap_.get(e);if(!r){var n=r=new Ue(this.has_(e),G,"ObservableMap.key?",!1);this.hasMap_.set(e,n),It(n,(function(){return t.hasMap_.delete(e)}))}return r.get()},r.set=function(e,t){var r=this.has_(e);if(Xt(this)){var n=Jt(this,{type:r?or:mr,object:this,newValue:t,name:e});if(!n)return this;t=n.newValue}return r?this.updateValue_(e,t):this.addValue_(e,t),this},r.delete=function(e){var t=this;if((this.keysAtom_,Xt(this))&&!Jt(this,{type:_r,object:this,name:e}))return!1;if(this.has_(e)){var r=er(this),n=r?{observableKind:"map",debugObjectName:this.name_,type:_r,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return Wt((function(){t.keysAtom_.reportChanged(),t.updateHasMapEntry_(e,!1),t.data_.get(e).setNewValue_(void 0),t.data_.delete(e)})),r&&rr(this,n),!0}return!1},r.updateHasMapEntry_=function(e,t){var r=this.hasMap_.get(e);r&&r.setNewValue_(t)},r.updateValue_=function(e,t){var r=this.data_.get(e);if((t=r.prepareNewValue_(t))!==rt.UNCHANGED){var n=er(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:or,object:this,oldValue:r.value_,name:e,newValue:t}:null;r.setNewValue_(t),n&&rr(this,i)}},r.addValue_=function(e,t){var r=this;this.keysAtom_,Wt((function(){var n=new Ue(t,r.enhancer_,"ObservableMap.key",!1);r.data_.set(e,n),t=n.value_,r.updateHasMapEntry_(e,!0),r.keysAtom_.reportChanged()}));var n=er(this),i=n?{observableKind:"map",debugObjectName:this.name_,type:mr,object:this,name:e,newValue:t}:null;n&&rr(this,i)},r.get=function(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)},r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.keys=function(){return this.keysAtom_.reportObserved(),this.data_.keys()},r.values=function(){var e=this,t=this.keys();return Xr({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:e.get(i)}}})},r.entries=function(){var e=this,t=this.keys();return Xr({next:function(){var r=t.next(),n=r.done,i=r.value;return{done:n,value:n?void 0:[i,e.get(i)]}}})},r[br]=function(){return this.entries()},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value,o=i[0],a=i[1];e.call(t,a,o,this)}},r.merge=function(t){var r=this;return Pr(t)&&(t=new Map(t)),Wt((function(){y(t)?function(e){var t=Object.keys(e);if(!P)return t;var r=Object.getOwnPropertySymbols(e);return r.length?[].concat(t,r.filter((function(t){return a.propertyIsEnumerable.call(e,t)}))):t}(t).forEach((function(e){return r.set(e,t[e])})):Array.isArray(t)?t.forEach((function(e){var t=e[0],n=e[1];return r.set(t,n)})):O(t)?(t.constructor!==Map&&e(19,t),t.forEach((function(e,t){return r.set(t,e)}))):null!=t&&e(20,t)})),this},r.clear=function(){var e=this;Wt((function(){We((function(){for(var t,r=V(e.keys());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.replace=function(t){var r=this;return Wt((function(){for(var n,i=function(t){if(O(t)||Pr(t))return t;if(Array.isArray(t))return new Map(t);if(y(t)){var r=new Map;for(var n in t)r.set(n,t[n]);return r}return e(21,t)}(t),o=new Map,a=!1,s=V(r.data_.keys());!(n=s()).done;){var u=n.value;if(!i.has(u))if(r.delete(u))a=!0;else{var c=r.data_.get(u);o.set(u,c)}}for(var l,f=V(i.entries());!(l=f()).done;){var p=l.value,h=p[0],b=p[1],d=r.data_.has(h);if(r.set(h,b),r.data_.has(h)){var v=r.data_.get(h);o.set(h,v),d||(a=!0)}}if(!a)if(r.data_.size!==o.size)r.keysAtom_.reportChanged();else for(var g=r.data_.keys(),m=o.keys(),_=g.next(),w=m.next();!_.done;){if(_.value!==w.value){r.keysAtom_.reportChanged();break}_=g.next(),w=m.next()}r.data_=o})),this},r.toString=function(){return"[object ObservableMap]"},r.toJSON=function(){return Array.from(this)},r.observe_=function(e,t){return tr(this,e)},r.intercept_=function(e){return Zt(this,e)},I(t,[{key:"size",get:function(){return this.keysAtom_.reportObserved(),this.data_.size}},{key:dr,get:function(){return"Map"}}]),t}(),Pr=w("ObservableMap",jr);var Sr={};wr=Symbol.iterator,Or=Symbol.toStringTag;var Ar=function(){function t(t,r,n){void 0===r&&(r=B),void 0===n&&(n="ObservableSet"),this.name_=void 0,this[z]=Sr,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,b(Set)||e(22),this.atom_=$(this.name_),this.enhancer_=function(e,t){return r(e,t,n)},t&&this.replace(t)}var r=t.prototype;return r.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},r.clear=function(){var e=this;Wt((function(){We((function(){for(var t,r=V(e.data_.values());!(t=r()).done;){var n=t.value;e.delete(n)}}))}))},r.forEach=function(e,t){for(var r,n=V(this);!(r=n()).done;){var i=r.value;e.call(t,i,i,this)}},r.add=function(e){var t=this;if((this.atom_,Xt(this))&&!Jt(this,{type:mr,object:this,newValue:e}))return this;if(!this.has(e)){Wt((function(){t.data_.add(t.enhancer_(e,void 0)),t.atom_.reportChanged()}));var r=er(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:mr,object:this,newValue:e}:null;r&&rr(this,n)}return this},r.delete=function(e){var t=this;if(Xt(this)&&!Jt(this,{type:_r,object:this,oldValue:e}))return!1;if(this.has(e)){var r=er(this),n=r?{observableKind:"set",debugObjectName:this.name_,type:_r,object:this,oldValue:e}:null;return Wt((function(){t.atom_.reportChanged(),t.data_.delete(e)})),r&&rr(this,n),!0}return!1},r.has=function(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))},r.entries=function(){var e=0,t=Array.from(this.keys()),r=Array.from(this.values());return Xr({next:function(){var n=e;return e+=1,nMr){for(var t=Mr;t=0&&r++}e=Qr(e),t=Qr(t);var s="[object Array]"===a;if(!s){if("object"!=typeof e||"object"!=typeof t)return!1;var u=e.constructor,c=t.constructor;if(u!==c&&!(b(u)&&u instanceof u&&b(c)&&c instanceof c)&&"constructor"in e&&"constructor"in t)return!1}if(0===r)return!1;r<0&&(r=-1),i=i||[];for(var l=(n=n||[]).length;l--;)if(n[l]===e)return i[l]===t;if(n.push(e),i.push(t),s){if((l=e.length)!==t.length)return!1;for(;l--;)if(!Yr(e[l],t[l],r-1,n,i))return!1}else{var f,p=Object.keys(e);if(l=p.length,Object.keys(t).length!==l)return!1;for(;l--;)if(!x(t,f=p[l])||!Yr(e[f],t[f],r-1,n,i))return!1}return n.pop(),i.pop(),!0}function Qr(e){return yr(e)?e.slice():O(e)||Pr(e)||j(e)||xr(e)?Array.from(e.entries()):e}function Xr(e){return e[Symbol.iterator]=Zr,e}function Zr(){return this}["Symbol","Map","Set","Symbol"].forEach((function(t){void 0===r()[t]&&e("MobX requires global '"+t+"' to be available or polyfilled")})),"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:function(e){return console.warn("[mobx.spy] Is a no-op in production builds"),function(){}},extras:{getDebugName:Kr},$mobx:z});var Jr;!function(e){e.afterCreate="afterCreate",e.afterAttach="afterAttach",e.afterCreationFinalization="afterCreationFinalization",e.beforeDetach="beforeDetach",e.beforeDestroy="beforeDestroy"}(Jr||(Jr={})); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. @@ -217,7 +217,7 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ -var tr=function(e,t){return(tr=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 nr(e,t){function n(){this.constructor=e}tr(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var rr=function(){return(rr=Object.assign||function(e){for(var t,n=1,r=arguments.length;n=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function or(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 ar(){for(var e=[],t=0;t";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==Mr.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeCreation()}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseAboutToDie()}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.fireInternalHook(e)}}),t}(fr);pr.prototype.die=Ot(pr.prototype.die);var hr,br,dr=1,vr={onError:function(e){throw e}},yr=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;if(Object.defineProperty(a,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:++dr}),Object.defineProperty(a,"identifierAttribute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"unnormalizedIdentifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifierCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"isProtectionEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applyPatches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applySnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_autoUnbox",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"_isRunningAction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_hasSnapshotReaction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_observableInstanceState",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(a,"_childNodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_initialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshotCreated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_snapshotComputed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_snapshotUponDeath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_internalEvents",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),a._snapshotComputed=Ae((function(){return a.getSnapshot()})),a.unbox=a.unbox.bind(a),a._initialSnapshot=o,a.identifierAttribute=t.identifierAttribute,n||(a.identifierCache=new zr),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 u=a._childNodes[a.identifierAttribute];u&&(s=u.value)}if("string"!=typeof s&&"number"!=typeof s)throw Jr("Instance identifier '"+a.identifierAttribute+"' for type '"+a.type.name+"' must be a string or a number");a.identifier=ho(s),a.unnormalizedIdentifier=s}return n?n.root.identifierCache.addNodeToCache(a):a.identifierCache.addNodeToCache(a),a}return nr(t,e),Object.defineProperty(t.prototype,"applyPatches",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)}}),Object.defineProperty(t.prototype,"createObservableInstanceIfNeeded",{enumerable:!1,configurable:!0,writable:!0,value:function(){0===this._observableInstanceState&&this.createObservableInstance()}}),Object.defineProperty(t.prototype,"createObservableInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e,t;this._observableInstanceState=1;for(var n=[],r=this.parent;r&&0===r._observableInstanceState;)n.unshift(r),r=r.parent;try{for(var i=ir(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=Mr.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,this._snapshotComputed.trackAndCompute(),this.isRoot&&this._addSnapshotReaction(),this._childNodes=Xr,this.state=Mr.CREATED,this.fireHook(er.afterCreate),this.finalizeCreation()}}),Object.defineProperty(t.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearParent",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.parent){this.fireHook(er.beforeDetach);var e=this.state;this.state=Mr.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}}}}),Object.defineProperty(t.prototype,"setParent",{enumerable:!1,configurable:!0,writable:!0,value: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(er.afterAttach)):r&&this.baseSetParent(this.parent,t))}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;this.fireInternalHook(e);var n=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof n&&(Pt?Pt((function(){n.apply(t.storedValue)})):n.apply(this.storedValue))}}),Object.defineProperty(t.prototype,"snapshot",{get:function(){return this._snapshotComputed.get()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath}}),Object.defineProperty(t.prototype,"_getActualSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.type.getSnapshot(this)}}),Object.defineProperty(t.prototype,"_getCachedInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value: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}}),Object.defineProperty(t.prototype,"isRunningAction",{enumerable:!1,configurable:!0,writable:!0,value:function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()}}),Object.defineProperty(t.prototype,"assertAlive",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t;if(!this.isAlive){var n=this._getAssertAliveError(e);t=n,console.warn(new Error("[mobx-state-tree] "+t))}}}),Object.defineProperty(t.prototype,"_getAssertAliveError",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",n=e.subpath&&bi(e.subpath)||"",r=e.actionContext||Pr;r&&"action"!==r.type&&r.parentActionEvent&&(r=r.parentActionEvent);var i="";r&&null!=r.name&&(i=(r&&r.context&&Br(r.context).path||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."}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value: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}}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.assertAlive(Xr),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):Wr(this._childNodes)}finally{this._autoUnbox=!0}}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.type.getChildType(e)}}),Object.defineProperty(t.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"assertWritable",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw Jr("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.type.removeChild(this,e)}}),Object.defineProperty(t.prototype,"unbox",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e}}),Object.defineProperty(t.prototype,"toString",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this.baseFinalizeCreation((function(){var t,n;try{for(var r=ir(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(er.afterCreationFinalization)}))}}),Object.defineProperty(t.prototype,"detach",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this.isAlive)throw Jr("Error while detaching, node is not alive.");this.clearParent()}}),Object.defineProperty(t.prototype,"preboot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this._applyPatches=Tr(this.storedValue,"@APPLY_PATCHES",(function(t){t.forEach((function(t){if(t.path){var n=function(e){var t=e.split("/").map(di);if(!(""===e||"."===e||".."===e||fi(e,"/")||fi(e,"./")||fi(e,"../")))throw Jr("a json path must be either rooted, empty or relative, but got '"+e+"'");""===t[0]&&t.shift();return t}(t.path);qr(e,n.slice(0,-1)).applyPatchLocally(n[n.length-1],t)}else e.type.applySnapshot(e,t.value)}))})),this._applySnapshot=Tr(this.storedValue,"@APPLY_SNAPSHOT",(function(t){if(t!==e.snapshot)return e.type.applySnapshot(e,t)})),si(this.storedValue,"$treenode",this),si(this.storedValue,"toJSON",Kr)}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==Mr.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){0!==this._observableInstanceState&&(this.getChildren().forEach((function(e){e.aboutToDie()})),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.getChildren().forEach((function(e){e.finalizeDeath()})),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"onSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)}}),Object.defineProperty(t.prototype,"emitSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this._internalEventsEmit("snapshot",e)}}),Object.defineProperty(t.prototype,"onPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._internalEventsRegister("patch",e)}}),Object.defineProperty(t.prototype,"emitPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._internalEventsHasSubscribers("patch")){var n=or(function(e){if(!("oldValue"in e))throw Jr("Patches without `oldValue` field cannot be inversed");return[pi(e),hi(e)]}(function(e){for(var t=[],n=1;n=0&&this.middlewares.splice(t,1)}}}),Object.defineProperty(t.prototype,"addMiddleWare",{enumerable:!1,configurable:!0,writable:!0,value: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)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)}}),Object.defineProperty(t.prototype,"_addSnapshotReaction",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;if(!this._hasSnapshotReaction){var t=Et((function(){return e.snapshot}),(function(t){return e.emitSnapshot(t)}),vr);this.addDisposer(t),this._hasSnapshotReaction=!0}}}),Object.defineProperty(t.prototype,"_internalEventsHasSubscribers",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)}}),Object.defineProperty(t.prototype,"_internalEventsRegister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n){return void 0===n&&(n=!1),this._internalEvents||(this._internalEvents=new ci),this._internalEvents.register(e,t,n)}}),Object.defineProperty(t.prototype,"_internalEventsHas",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsUnregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsEmit",{enumerable:!1,configurable:!0,writable:!0,value:function(e){for(var t,n=[],r=1;r0},enumerable:!1,configurable:!0})}();var Pr,Sr=1;function Ar(){return Sr++}function xr(e,t){var n=Br(e.context);"action"===e.type&&n.assertAlive({actionContext:e});var r=n._isRunningAction;n._isRunningAction=!0;var i=Pr;Pr=e;try{return function(e,t,n){var r=new Ir(e,n);if(r.isEmpty)return Ot(n).apply(null,t.args);var i=null;function o(e){var t=r.getNextMiddleware(),a=t&&t.handler;if(!a)return Ot(n).apply(null,e.args);if(!t.includeHooks&&er[e.name])return o(e);function s(e,t){i=o(e),t&&(i=t(i))}function u(e){i=e}return a(e,s,u),i}return o(t)}(n,e,t)}finally{Pr=i,n._isRunningAction=r}}function Er(e){if(e)return"action"===e.type?e:e.parentActionEvent}function Tr(e,t,n){var r=function(){var r=Ar(),i=Pr,o=Er(i);return xr({type:"action",name:t,id:r,args:li(arguments),context:e,tree:lr(e),rootId:i?i.rootId:r,parentId:i?i.id:0,allParentIds:i?ar(i.allParentIds,[i.id]):[],parentEvent:i,parentActionEvent:o},n)};return r._isMSTAction=!0,r}var Ir=function(){function e(e,t){Object.defineProperty(this,"arrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"inArrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:[]}),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:!1,configurable:!0}),Object.defineProperty(e.prototype,"getNextMiddleware",{enumerable:!1,configurable:!0,writable:!0,value: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 Cr(e){return"function"==typeof e?"":Hr(e)?"<"+e+">":"`"+function(e){try{return JSON.stringify(e)}catch(e){return""}}(e)+"`"}function kr(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=Hr(t)?"value of type "+Br(t).type.name+":":ai(t)?"value":"snapshot",a=n&&Hr(t)&&n.is(Br(t).snapshot);return""+i+o+" "+Cr(t)+" is not assignable "+(n?"to type: `"+n.name+"`":"")+(e.message?" ("+e.message+")":"")+(n?function(e){return jr(e)&&(e.flags&(br.String|br.Number|br.Integer|br.Boolean|br.Date))>0}(n)||ai(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 Dr(e,t,n){return e.concat([{path:t,type:n}])}function Nr(){return Qr}function Vr(e,t,n){return[{context:e,value:t,message:n}]}function Rr(e){return e.reduce((function(e,t){return e.concat(t)}),[])}function Ur(e,t){"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK&&function(e,t){var n=e.validate(t,[{path:"",type:e}]);if(n.length>0)throw Jr(function(e,t,n){if(0===n.length)return;return"Error while converting "+(r=Cr(t),(r.length<280?r:r.substring(0,272)+"......"+r.substring(r.length-8))+" to `")+e.name+"`:\n\n "+n.map(kr).join("\n ");var r}(e,t,n))}(e,t)}var Mr,Fr=0,zr=function(){function t(){Object.defineProperty(this,"cacheId",{enumerable:!0,configurable:!0,writable:!0,value:Fr++}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:Oe.map()}),Object.defineProperty(this,"lastCacheModificationPerId",{enumerable:!0,configurable:!0,writable:!0,value:Oe.map()})}return Object.defineProperty(t.prototype,"updateLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)}}),Object.defineProperty(t.prototype,"getLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t}}),Object.defineProperty(t.prototype,"addNodeToCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var n=e.identifier;this.cache.has(n)||this.cache.set(n,Oe.array([],Zr));var r=this.cache.get(n);if(-1!==r.indexOf(e))throw Jr("Already registered");r.push(e),t&&this.updateLastCacheModificationPerId(n)}}}),Object.defineProperty(t.prototype,"mergeCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;Ht(e.identifierCache.cache).forEach((function(e){return e.forEach((function(e){t.addNodeToCache(e)}))}))}}),Object.defineProperty(t.prototype,"notifyDied",{enumerable:!1,configurable:!0,writable:!0,value: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))}}}),Object.defineProperty(t.prototype,"splitCache",{enumerable:!1,configurable:!0,writable:!0,value:function(n){var r,i=this,o=new t,a=n.path;return(r=this.cache,Vn(r)?$t(r).map((function(e){return[e,r[e]]})):Sn(r)?$t(r).map((function(e){return[e,r.get(e)]})):En(r)?Array.from(r.entries()):gn(r)?r.map((function(e,t){return[t,e]})):void e(7)).forEach((function(e){for(var t=or(e,2),n=t[0],r=t[1],s=!1,u=r.length-1;u>=0;u--)0===r[u].path.indexOf(a)&&(o.addNodeToCache(r[u],!1),r.splice(u,1),s=!0);s&&i.updateLastCacheModificationPerId(n)})),o}}),Object.defineProperty(t.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var n=this.cache.get(t);return!!n&&n.some((function(t){return e.isAssignableFrom(t.type)}))}}),Object.defineProperty(t.prototype,"resolve",{enumerable:!1,configurable:!0,writable:!0,value: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 Jr("Cannot resolve a reference to type '"+e.name+"' with id: '"+t+"' unambigously, there are multiple candidates: "+r.map((function(e){return e.path})).join(", "))}}}),t}();function Lr(e,t,n,r,i){var o=Gr(i);if(o){if(o.parent)throw Jr("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 yr(e,t,n,r,i)}function $r(e,t,n,r,i){return new pr(e,t,n,r,i)}function Hr(e){return!(!e||!e.$treenode)}function Br(e){if(!Hr(e))throw Jr("Value "+e+" is no MST Node");return e.$treenode}function Gr(e){return e&&e.$treenode||null}function Kr(){return Br(this).snapshot}function qr(e,t,n){void 0===n&&(n=!0);for(var r=e,i=0;i0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"register",{enumerable:!1,configurable:!0,writable:!0,value: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)}}}),Object.defineProperty(e.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.handlers.indexOf(e)>=0}}),Object.defineProperty(e.prototype,"unregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}),Object.defineProperty(e.prototype,"clear",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.handlers.length=0}}),Object.defineProperty(e.prototype,"emit",{enumerable:!1,configurable:!0,writable:!0,value:function(){for(var e=[],t=0;t0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,n)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){return this._determineIdentifierMode(),Lr(this,e,t,n,r)}}),Object.defineProperty(t.prototype,"_determineIdentifierMode",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.identifierMode===gi.UNKNOWN){var e=[];if(_i(this._subType,e)){var t=void 0;e.forEach((function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw Jr("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=gi.YES,this.mapIdentifierAttribute=t):this.identifierMode=gi.NO}}}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value: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}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return new wi(e)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Ft(t,e.unbox),e.type.hookInitializers.forEach((function(e){var n=e(t);Object.keys(n).forEach((function(e){var r=n[e],i=Tr(t,e,r);si(t,e,i)}))})),zt(t,this.willChange),Kt(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"Map"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Ht(e.storedValue)}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var n=e.storedValue.get(""+t);if(!n)throw Jr("Not a child "+t);return n}}),Object.defineProperty(t.prototype,"willChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Br(e.object),n=e.name;t.assertWritable({subpath:n});var r=t.type,i=r._subType;switch(e.type){case"update":var o=e.newValue;if(o===e.object.get(n))return null;Ur(i,o),e.newValue=i.reconcile(t.getChildNode(n),e.newValue,t,n),r.processIdentifier(n,e.newValue);break;case"add":Ur(i,e.newValue),e.newValue=i.instantiate(t,n,void 0,e.newValue),r.processIdentifier(n,e.newValue)}return e}}),Object.defineProperty(t.prototype,"processIdentifier",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.identifierMode===gi.YES&&t instanceof yr){var n=t.identifier;if(n!==e)throw Jr("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '"+n+"', but expected: '"+e+"'")}}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return e.getChildren().forEach((function(e){t[e.subpath]=e.snapshot})),t}}),Object.defineProperty(t.prototype,"processInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return Object.keys(e).forEach((function(n){t[n]=e[n].getSnapshot()})),t}}),Object.defineProperty(t.prototype,"didChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Br(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:bi(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:bi(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":var n=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:bi(e.name),oldValue:n},t)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n){var r=e.storedValue;switch(n.op){case"add":case"replace":r.set(t,n.value);break;case"remove":r.delete(t)}}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Ur(this,t);var n=e.storedValue,r={};if(Array.from(n.keys()).forEach((function(e){r[e]=!1})),t)for(var i in t)n.set(i,t[i]),r[""+i]=!0;Object.keys(r).forEach((function(e){!1===r[e]&&n.delete(e)}))}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var n=this;return ii(e)?Rr(Object.keys(e).map((function(r){return n._subType.validate(e[r],Dr(t,r,n._subType))}))):Vr(t,e,"Value is not a plain object")}}),Object.defineProperty(t.prototype,"getDefaultSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return Xr}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){e.storedValue.delete(t)}}),t}(wr);Oi.prototype.applySnapshot=Ot(Oi.prototype.applySnapshot);var ji=function(e){function t(t,n,r){void 0===r&&(r=[]);var i=e.call(this,t)||this;return Object.defineProperty(i,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(i,"flags",{enumerable:!0,configurable:!0,writable:!0,value:br.Array}),Object.defineProperty(i,"hookInitializers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),i.hookInitializers=r,i}return nr(t,e),Object.defineProperty(t.prototype,"hooks",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var n=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,n)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){return Lr(this,e,t,n,r)}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t=[]);var n=e.type._subType,r={};return t.forEach((function(t,i){var o=""+i;r[o]=n.instantiate(e,o,void 0,t)})),r}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Oe.array(Wr(e),Zr)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Kn(t).dehancer=e.unbox,e.type.hookInitializers.forEach((function(e){var n=e(t);Object.keys(n).forEach((function(e){var r=n[e],i=Tr(t,e,r);si(t,e,i)}))})),zt(t,this.willChange),Kt(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType.describe()+"[]"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.slice()}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var n=Number(t);if(n=0;n--)t.emitPatch({op:"remove",path:""+(e.index+n),oldValue:e.removed[n].snapshot},t);for(n=0;n0)return n;var r=Hr(e)?Br(e).snapshot:e;return this._predicate(r)?Nr():Vr(t,e,this._message(e))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){return this._subtype.reconcile(e,t,n,r)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(_r);var Gi=function(e){function t(t,n,r){var i=e.call(this,t)||this;return Object.defineProperty(i,"_types",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(i,"_dispatcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"_eager",{enumerable:!0,configurable:!0,writable:!0,value:!0}),r=rr({eager:!0,dispatcher:void 0},r),i._dispatcher=r.dispatcher,r.eager||(i._eager=!1),i}return nr(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){var e=br.Union;return this._types.forEach((function(t){e|=t.flags})),e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._types.some((function(t){return t.isAssignableFrom(e)}))}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"("+this._types.map((function(e){return e.describe()})).join(" | ")+")"}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){var i=this.determineType(r,void 0);if(!i)throw Jr("No matching type for union "+this.describe());return i.instantiate(e,t,n,r)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){var i=this.determineType(t,e.type);if(!i)throw Jr("No matching type for union "+this.describe());return i.reconcile(e,t,n,r)}}),Object.defineProperty(t.prototype,"determineType",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter((function(e){return e!==t})).find((function(t){return t.is(e)})):this._types.find((function(t){return t.is(e)}))}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);for(var n=[],r=0,i=0;i=0){var i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,n,i)}return this._subtype.instantiate(e,t,n,r)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),n,r)}}),Object.defineProperty(t.prototype,"getDefaultInstanceOrSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&Ur(this,e),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this.optionalValues.indexOf(e)>=0?Nr():this._subtype.validate(e,t)}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._subtype.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(_r);function Wi(e,t,n){return function(e,t){if("function"!=typeof t&&Hr(t))throw Jr("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}(0,t),new qi(e,t,n||Yi)}var Yi=[void 0],Qi=Wi(Fi,void 0),Xi=Wi(Mi,null);function Zi(e){return Ki(e,Qi)}var Ji=function(e){function t(t,n){var r=e.call(this,t)||this;return Object.defineProperty(r,"_definition",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(r,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r}return nr(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return(this._subType?this._subType.flags:0)|br.Late},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSubType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(!this._subType){var t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw Jr("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){return this.getSubType(!0).instantiate(e,t,n,r)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){return this.getSubType(!0).reconcile(e,t,n,r)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e?e.name:""}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var n=this.getSubType(!1);return n?n.validate(e,t):Nr()}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e||gr}}),t}(_r);var eo=function(e){function t(t){var n=e.call(this,t?"frozen("+t.name+")":"frozen")||this;return Object.defineProperty(n,"subType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:br.Frozen}),n}return nr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return""}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){return $r(this,e,t,n,r)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return function(e){return"function"!=typeof e}(e)?this.subType?this.subType.validate(e,t):Nr():Vr(t,e,"Value is not serializable and cannot be frozen")}}),t}(Or),to=new eo;var no=function(){function e(e,t){if(Object.defineProperty(this,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolvedReference",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),bo(e))this.identifier=e;else{if(!Hr(e))throw Jr("Can only store references to tree nodes or identifiers, got: '"+e+"'");var n=Br(e);if(!n.identifierAttribute)throw Jr("Can only store references with a defined identifier attribute.");var r=n.unnormalizedIdentifier;if(null==r)throw Jr("Can only store references to tree nodes with a defined identifier.");this.identifier=r}}return Object.defineProperty(e.prototype,"updateResolvedReference",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=ho(this.identifier),n=e.root,r=n.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==r){var i=this.targetType,o=n.identifierCache.resolve(i,t);if(!o)throw new ro("[mobx-state-tree] Failed to resolve reference '"+this.identifier+"' to type '"+this.targetType.name+"' (from node: "+e.path+")");this.resolvedReference={node:o,lastCacheModification:r}}}}),Object.defineProperty(e.prototype,"resolvedValue",{get:function(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value},enumerable:!1,configurable:!0}),e}(),ro=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r}return nr(t,e),t}(Error),io=function(e){function t(t,n){var r=e.call(this,"reference("+t.name+")")||this;return Object.defineProperty(r,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"onInvalidated",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:br.Reference}),r}return nr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.targetType.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return bo(e)?Nr():Vr(t,e,"Value is not a valid identifier, which is a string or a number")}}),Object.defineProperty(t.prototype,"fireInvalidated",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){var i=t.parent;if(i&&i.isAlive){var o=i.storedValue;o&&this.onInvalidated({cause:e,parent:o,invalidTarget:r?r.storedValue:void 0,invalidId:n,replaceRef:function(e){ur(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef:function(){!function(e){return jr(e)&&(e.flags&br.Object)>0}(i.type)?ur(t.root.storedValue,{op:"remove",path:t.path}):this.replaceRef(void 0)}})}}}),Object.defineProperty(t.prototype,"addTargetNodeWatcher",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var n=this,r=this.getValue(e);if(r){var i=Br(r),o=function(r,o){var a=function(e){switch(e){case er.beforeDestroy:return"destroy";case er.beforeDetach:return"detach";default:return}}(o);a&&n.fireInvalidated(a,e,t,i)},a=i.registerHook(er.beforeDetach,o),s=i.registerHook(er.beforeDestroy,o);return function(){a(),s()}}}}),Object.defineProperty(t.prototype,"watchTargetNodeForInvalidations",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n){var r=this;if(this.onInvalidated){var i;e.registerHook(er.beforeDestroy,(function(){i&&i()}));var o=function(o){i&&i();var a=e.parent,s=a&&a.storedValue;if(a&&a.isAlive&&s){(n?!!n.get(t,s):e.root.identifierCache.has(r.targetType,ho(t)))?i=r.addTargetNodeWatcher(e,t):o||r.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===Mr.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(er.afterCreationFinalization,(function(){e.parent&&e.parent.createObservableInstanceIfNeeded()})),e.registerHook(er.afterAttach,(function(){o(!1)})))}}}),t}(Or),oo=function(e){function t(t,n){return e.call(this,t,n)||this}return nr(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return e.storedValue.resolvedValue}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.identifier}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){var i=Hr(r)?Br(r).identifier:r,o=new no(r,this.targetType),a=$r(this,e,t,n,o);return o.node=a,this.watchTargetNodeForInvalidations(a,i,void 0),a}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){if(!e.isDetaching&&e.type===this){var i=Hr(t),o=e.storedValue;if(!i&&o.identifier===t||i&&o.resolvedValue===t)return e.setParent(n,r),e}var a=this.instantiate(n,r,void 0,t);return e.die(),a}}),t}(io),ao=function(e){function t(t,n,r){var i=e.call(this,t,r)||this;return Object.defineProperty(i,"options",{enumerable:!0,configurable:!0,writable:!0,value:n}),i}return nr(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){var i=Hr(r)?this.options.set(r,e?e.storedValue:null):r,o=$r(this,e,t,n,i);return this.watchTargetNodeForInvalidations(o,i,this.options),o}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){var i=Hr(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===i)return e.setParent(n,r),e;var o=this.instantiate(n,r,void 0,i);return e.die(),o}}),t}(io);function so(e,t){var n=t||void 0,r=t?t.onInvalidated:void 0;return n&&(n.get||n.set)?new ao(e,{get:n.get,set:n.set},r):new oo(e,r)}var uo=function(e){function t(t,n){var r=e.call(this,t)||this;return Object.defineProperty(r,"validType",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:br.Identifier}),r}return nr(t,e),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){if(!(e&&e.type instanceof ki))throw Jr("Identifier types can only be instantiated as direct child of a model type");return $r(this,e,t,n,r)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){if(e.storedValue!==t)throw Jr("Tried to change identifier from '"+e.storedValue+"' to '"+t+"'. Changing identifiers is not allowed.");return e.setParent(n,r),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return typeof e!==this.validType?Vr(t,e,"Value is not a valid "+this.describe()+", expected a "+this.validType):Nr()}}),t}(Or),co=function(e){function t(){var t=e.call(this,"identifier","string")||this;return Object.defineProperty(t,"flags",{enumerable:!0,configurable:!0,writable:!0,value:br.Identifier}),t}return nr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifier"}}),t}(uo),lo=function(e){function t(){return e.call(this,"identifierNumber","number")||this}return nr(t,e),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifierNumber"}}),t}(uo),fo=new co,po=new lo;function ho(e){return""+e}function bo(e){return"string"==typeof e||"number"==typeof e}var vo,yo=function(e){function t(t){var n=e.call(this,t.name)||this;return Object.defineProperty(n,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:br.Custom}),n}return nr(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.options.isTargetType(e))return Nr();var n=this.options.getValidationMessage(e);return n?Vr(t,e,"Invalid value for type '"+this.name+"': "+n):Nr()}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.options.toSnapshot(e.storedValue)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){return $r(this,e,t,n,this.options.isTargetType(r)?r:this.options.fromSnapshot(r,e&&e.root.environment))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,n,r){var i=!this.options.isTargetType(t);if(!e.isDetaching&&(e.type===this&&(i?t===e.snapshot:t===e.storedValue)))return e.setParent(n,r),e;var o=i?this.options.fromSnapshot(t,n.root.environment):t,a=this.instantiate(n,r,void 0,o);return e.die(),a}}),t}(Or),go={enumeration:function(e,t){var n="string"==typeof e?t:e,r=Ki.apply(void 0,ar(n.map((function(e){return Hi(""+e)}))));return"string"==typeof e&&(r.name=e),r},model:function(){for(var e=[],t=0;t",e)},array:function(e){return new ji(e.name+"[]",e)},frozen:function(e){return 0===arguments.length?to:jr(e)?new eo(e):Wi(to,e)},identifier:fo,identifierNumber:po,late:function(e,t){var n="string"==typeof e?e:"late("+e.toString()+")";return new Ji(n,"string"==typeof e?t:e)},undefined:Fi,null:Mi,snapshotProcessor:function(e,t,n){return new yi(e,t,n)}},mo=new Uint8Array(16);function _o(){if(!vo&&!(vo="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vo(mo)}var wo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Oo(e){return"string"==typeof e&&wo.test(e)}for(var jo=[],Po=0;Po<256;++Po)jo.push((Po+256).toString(16).substr(1));function So(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(jo[e[t+0]]+jo[e[t+1]]+jo[e[t+2]]+jo[e[t+3]]+"-"+jo[e[t+4]]+jo[e[t+5]]+"-"+jo[e[t+6]]+jo[e[t+7]]+"-"+jo[e[t+8]]+jo[e[t+9]]+"-"+jo[e[t+10]]+jo[e[t+11]]+jo[e[t+12]]+jo[e[t+13]]+jo[e[t+14]]+jo[e[t+15]]).toLowerCase();if(!Oo(n))throw TypeError("Stringified UUID is invalid");return n}function Ao(e,t,n){var r=(e=e||{}).random||(e.rng||_o)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return So(r)}function xo(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Eo(e,t){return e<>>32-t}var To=function(e,t,n){function r(e,r,i,o){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=255&t,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=255&t,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=255&t,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=255&t,n}(r)),16!==r.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var a=new Uint8Array(16+e.length);if(a.set(r),a.set(e,r.length),(a=n(a))[6]=15&a[6]|t,a[8]=63&a[8]|128,i){o=o||0;for(var s=0;s<16;++s)i[o+s]=a[s];return i}return So(a)}try{r.name=e}catch(e){}return r.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",r.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",r}("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var r=unescape(encodeURIComponent(e));e=[];for(var i=0;i>>0;m=g,g=y,y=Eo(v,30)>>>0,v=d,d=O}n[0]=n[0]+d>>>0,n[1]=n[1]+v>>>0,n[2]=n[2]+y>>>0,n[3]=n[3]+g>>>0,n[4]=n[4]+m>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]})); +var en=function(e,t){return(en=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function tn(e,t){function r(){this.constructor=e}en(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var rn=function(){return(rn=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function on(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function an(){for(var e=[],t=0;t";return this.type.name+"@"+e+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==Mn.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeCreation()}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseAboutToDie()}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.fireInternalHook(e)}}),t}(fn);pn.prototype.die=Ot(pn.prototype.die);var hn,bn,dn=1,vn={onError:function(e){throw e}},yn=function(e){function t(t,r,n,i,o){var a=e.call(this,t,r,n,i)||this;if(Object.defineProperty(a,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:++dn}),Object.defineProperty(a,"identifierAttribute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"unnormalizedIdentifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"identifierCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"isProtectionEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applyPatches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_applySnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_autoUnbox",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(a,"_isRunningAction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_hasSnapshotReaction",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_observableInstanceState",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(a,"_childNodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_initialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_cachedInitialSnapshotCreated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(a,"_snapshotComputed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_snapshotUponDeath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"_internalEvents",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),a._snapshotComputed=Ae((function(){return a.getSnapshot()})),a.unbox=a.unbox.bind(a),a._initialSnapshot=o,a.identifierAttribute=t.identifierAttribute,r||(a.identifierCache=new Fn),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 u=a._childNodes[a.identifierAttribute];u&&(s=u.value)}if("string"!=typeof s&&"number"!=typeof s)throw Jn("Instance identifier '"+a.identifierAttribute+"' for type '"+a.type.name+"' must be a string or a number");a.identifier=ho(s),a.unnormalizedIdentifier=s}return r?r.root.identifierCache.addNodeToCache(a):a.identifierCache.addNodeToCache(a),a}return tn(t,e),Object.defineProperty(t.prototype,"applyPatches",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applyPatches(e)}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.createObservableInstanceIfNeeded(),this._applySnapshot(e)}}),Object.defineProperty(t.prototype,"createObservableInstanceIfNeeded",{enumerable:!1,configurable:!0,writable:!0,value:function(){0===this._observableInstanceState&&this.createObservableInstance()}}),Object.defineProperty(t.prototype,"createObservableInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e,t;this._observableInstanceState=1;for(var r=[],n=this.parent;n&&0===n._observableInstanceState;)r.unshift(n),n=n.parent;try{for(var i=nn(r),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=Mn.DEAD,e}finally{this._isRunningAction=!1}this._observableInstanceState=2,this._snapshotComputed.trackAndCompute(),this.isRoot&&this._addSnapshotReaction(),this._childNodes=Xn,this.state=Mn.CREATED,this.fireHook(Jr.afterCreate),this.finalizeCreation()}}),Object.defineProperty(t.prototype,"root",{get:function(){var e=this.parent;return e?e.root:this},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearParent",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.parent){this.fireHook(Jr.beforeDetach);var e=this.state;this.state=Mn.DETACHING;var t=this.root,r=t.environment,n=t.identifierCache.splitCache(this);try{this.parent.removeChild(this.subpath),this.baseSetParent(null,""),this.environment=r,this.identifierCache=n}finally{this.state=e}}}}),Object.defineProperty(t.prototype,"setParent",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e!==this.parent,n=t!==this.subpath;(r||n)&&(r?(this.environment=void 0,e.root.identifierCache.mergeCache(this),this.baseSetParent(e,t),this.fireHook(Jr.afterAttach)):n&&this.baseSetParent(this.parent,t))}}),Object.defineProperty(t.prototype,"fireHook",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;this.fireInternalHook(e);var r=this.storedValue&&"object"==typeof this.storedValue&&this.storedValue[e];"function"==typeof r&&(Pt?Pt((function(){r.apply(t.storedValue)})):r.apply(this.storedValue))}}),Object.defineProperty(t.prototype,"snapshot",{get:function(){return this._snapshotComputed.get()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.isAlive?2===this._observableInstanceState?this._getActualSnapshot():this._getCachedInitialSnapshot():this._snapshotUponDeath}}),Object.defineProperty(t.prototype,"_getActualSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.type.getSnapshot(this)}}),Object.defineProperty(t.prototype,"_getCachedInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this._cachedInitialSnapshotCreated){var e=this.type,t=this._childNodes,r=this._initialSnapshot;this._cachedInitialSnapshot=e.processInitialSnapshot(t,r),this._cachedInitialSnapshotCreated=!0}return this._cachedInitialSnapshot}}),Object.defineProperty(t.prototype,"isRunningAction",{enumerable:!1,configurable:!0,writable:!0,value:function(){return!!this._isRunningAction||!this.isRoot&&this.parent.isRunningAction()}}),Object.defineProperty(t.prototype,"assertAlive",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t;if(!this.isAlive){var r=this._getAssertAliveError(e);t=r,console.warn(new Error("[mobx-state-tree] "+t))}}}),Object.defineProperty(t.prototype,"_getAssertAliveError",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getEscapedPath(!1)||this.pathUponDeath||"",r=e.subpath&&bi(e.subpath)||"",n=e.actionContext||Pn;n&&"action"!==n.type&&n.parentActionEvent&&(n=n.parentActionEvent);var i="";n&&null!=n.name&&(i=(n&&n.context&&Bn(n.context).path||t)+"."+n.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: '"+r+"', Action: '"+i+"'). Either detach nodes first, or don't use objects after removing / replacing them in the tree."}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value: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}}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.assertAlive(Xn),this._autoUnbox=!1;try{return 2===this._observableInstanceState?this.type.getChildren(this):Wn(this._childNodes)}finally{this._autoUnbox=!0}}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.type.getChildType(e)}}),Object.defineProperty(t.prototype,"isProtected",{get:function(){return this.root.isProtectionEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"assertWritable",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(this.assertAlive(e),!this.isRunningAction()&&this.isProtected)throw Jn("Cannot modify '"+this+"', the object is protected and can only be modified by using an action.")}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this.type.removeChild(this,e)}}),Object.defineProperty(t.prototype,"unbox",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e?(this.assertAlive({subpath:e.subpath||e.subpathUponDeath}),this._autoUnbox?e.value:e):e}}),Object.defineProperty(t.prototype,"toString",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=(this.isAlive?this.path:this.pathUponDeath)||"",t=this.identifier?"(id: "+this.identifier+")":"";return this.type.name+"@"+e+t+(this.isAlive?"":" [dead]")}}),Object.defineProperty(t.prototype,"finalizeCreation",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this.baseFinalizeCreation((function(){var t,r;try{for(var n=nn(e.getChildren()),i=n.next();!i.done;i=n.next()){i.value.finalizeCreation()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}e.fireInternalHook(Jr.afterCreationFinalization)}))}}),Object.defineProperty(t.prototype,"detach",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(!this.isAlive)throw Jn("Error while detaching, node is not alive.");this.clearParent()}}),Object.defineProperty(t.prototype,"preboot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;this._applyPatches=Tn(this.storedValue,"@APPLY_PATCHES",(function(t){t.forEach((function(t){if(t.path){var r=function(e){var t=e.split("/").map(di);if(!(""===e||"."===e||".."===e||fi(e,"/")||fi(e,"./")||fi(e,"../")))throw Jn("a json path must be either rooted, empty or relative, but got '"+e+"'");""===t[0]&&t.shift();return t}(t.path);qn(e,r.slice(0,-1)).applyPatchLocally(r[r.length-1],t)}else e.type.applySnapshot(e,t.value)}))})),this._applySnapshot=Tn(this.storedValue,"@APPLY_SNAPSHOT",(function(t){if(t!==e.snapshot)return e.type.applySnapshot(e,t)})),si(this.storedValue,"$treenode",this),si(this.storedValue,"toJSON",Kn)}}),Object.defineProperty(t.prototype,"die",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.isAlive&&this.state!==Mn.DETACHING&&(this.aboutToDie(),this.finalizeDeath())}}),Object.defineProperty(t.prototype,"aboutToDie",{enumerable:!1,configurable:!0,writable:!0,value:function(){0!==this._observableInstanceState&&(this.getChildren().forEach((function(e){e.aboutToDie()})),this.baseAboutToDie(),this._internalEventsEmit("dispose"),this._internalEventsClear("dispose"))}}),Object.defineProperty(t.prototype,"finalizeDeath",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.getChildren().forEach((function(e){e.finalizeDeath()})),this.root.identifierCache.notifyDied(this);var e=this.snapshot;this._snapshotUponDeath=e,this._internalEventsClearAll(),this.baseFinalizeDeath()}}),Object.defineProperty(t.prototype,"onSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._addSnapshotReaction(),this._internalEventsRegister("snapshot",e)}}),Object.defineProperty(t.prototype,"emitSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){this._internalEventsEmit("snapshot",e)}}),Object.defineProperty(t.prototype,"onPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._internalEventsRegister("patch",e)}}),Object.defineProperty(t.prototype,"emitPatch",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._internalEventsHasSubscribers("patch")){var r=on(function(e){if(!("oldValue"in e))throw Jn("Patches without `oldValue` field cannot be inversed");return[pi(e),hi(e)]}(function(e){for(var t=[],r=1;r=0&&this.middlewares.splice(t,1)}}}),Object.defineProperty(t.prototype,"addMiddleWare",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;void 0===t&&(t=!0);var n={handler:e,includeHooks:t};return this.middlewares?this.middlewares.push(n):this.middlewares=[n],function(){r.removeMiddleware(n)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this.assertWritable({subpath:e}),this.createObservableInstanceIfNeeded(),this.type.applyPatchLocally(this,e,t)}}),Object.defineProperty(t.prototype,"_addSnapshotReaction",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;if(!this._hasSnapshotReaction){var t=Et((function(){return e.snapshot}),(function(t){return e.emitSnapshot(t)}),vn);this.addDisposer(t),this._hasSnapshotReaction=!0}}}),Object.defineProperty(t.prototype,"_internalEventsHasSubscribers",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return!!this._internalEvents&&this._internalEvents.hasSubscribers(e)}}),Object.defineProperty(t.prototype,"_internalEventsRegister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){return void 0===r&&(r=!1),this._internalEvents||(this._internalEvents=new ci),this._internalEvents.register(e,t,r)}}),Object.defineProperty(t.prototype,"_internalEventsHas",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return!!this._internalEvents&&this._internalEvents.has(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsUnregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){this._internalEvents&&this._internalEvents.unregister(e,t)}}),Object.defineProperty(t.prototype,"_internalEventsEmit",{enumerable:!1,configurable:!0,writable:!0,value:function(e){for(var t,r=[],n=1;n0},enumerable:!1,configurable:!0})}();var Pn,Sn=1;function An(){return Sn++}function xn(e,t){var r=Bn(e.context);"action"===e.type&&r.assertAlive({actionContext:e});var n=r._isRunningAction;r._isRunningAction=!0;var i=Pn;Pn=e;try{return function(e,t,r){var n=new In(e,r);if(n.isEmpty)return Ot(r).apply(null,t.args);var i=null;function o(e){var t=n.getNextMiddleware(),a=t&&t.handler;if(!a)return Ot(r).apply(null,e.args);if(!t.includeHooks&&Jr[e.name])return o(e);function s(e,t){i=o(e),t&&(i=t(i))}function u(e){i=e}return a(e,s,u),i}return o(t)}(r,e,t)}finally{Pn=i,r._isRunningAction=n}}function En(e){if(e)return"action"===e.type?e:e.parentActionEvent}function Tn(e,t,r){var n=function(){var n=An(),i=Pn,o=En(i);return xn({type:"action",name:t,id:n,args:li(arguments),context:e,tree:ln(e),rootId:i?i.rootId:n,parentId:i?i.id:0,allParentIds:i?an(i.allParentIds,[i.id]):[],parentEvent:i,parentActionEvent:o},r)};return n._isMSTAction=!0,n}var In=function(){function e(e,t){Object.defineProperty(this,"arrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"inArrayIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"middlewares",{enumerable:!0,configurable:!0,writable:!0,value:[]}),t.$mst_middleware&&this.middlewares.push(t.$mst_middleware);for(var r=e;r;)r.middlewares&&this.middlewares.push(r.middlewares),r=r.parent}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return this.middlewares.length<=0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"getNextMiddleware",{enumerable:!1,configurable:!0,writable:!0,value: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 Cn(e){return"function"==typeof e?"":Hn(e)?"<"+e+">":"`"+function(e){try{return JSON.stringify(e)}catch(e){return""}}(e)+"`"}function kn(e){var t=e.value,r=e.context[e.context.length-1].type,n=e.context.map((function(e){return e.path})).filter((function(e){return e.length>0})).join("/"),i=n.length>0?'at path "/'+n+'" ':"",o=Hn(t)?"value of type "+Bn(t).type.name+":":ai(t)?"value":"snapshot",a=r&&Hn(t)&&r.is(Bn(t).snapshot);return""+i+o+" "+Cn(t)+" is not assignable "+(r?"to type: `"+r.name+"`":"")+(e.message?" ("+e.message+")":"")+(r?function(e){return jn(e)&&(e.flags&(bn.String|bn.Number|bn.Integer|bn.Boolean|bn.Date))>0}(r)||ai(t)?".":", expected an instance of `"+r.name+"` or a snapshot like `"+r.describe()+"` instead."+(a?" (Note that a snapshot of the provided value is compatible with the targeted type)":""):".")}function Dn(e,t,r){return e.concat([{path:t,type:r}])}function Nn(){return Qn}function Vn(e,t,r){return[{context:e,value:t,message:r}]}function Rn(e){return e.reduce((function(e,t){return e.concat(t)}),[])}function Un(e,t){"undefined"!=typeof process&&process.env&&"true"===process.env.ENABLE_TYPE_CHECK&&function(e,t){var r=e.validate(t,[{path:"",type:e}]);if(r.length>0)throw Jn(function(e,t,r){if(0===r.length)return;return"Error while converting "+(n=Cn(t),(n.length<280?n:n.substring(0,272)+"......"+n.substring(n.length-8))+" to `")+e.name+"`:\n\n "+r.map(kn).join("\n ");var n}(e,t,r))}(e,t)}var Mn,zn=0,Fn=function(){function t(){Object.defineProperty(this,"cacheId",{enumerable:!0,configurable:!0,writable:!0,value:zn++}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:Oe.map()}),Object.defineProperty(this,"lastCacheModificationPerId",{enumerable:!0,configurable:!0,writable:!0,value:Oe.map()})}return Object.defineProperty(t.prototype,"updateLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e);this.lastCacheModificationPerId.set(e,void 0===t?1:t+1)}}),Object.defineProperty(t.prototype,"getLastCacheModificationPerId",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.lastCacheModificationPerId.get(e)||0;return this.cacheId+"-"+t}}),Object.defineProperty(t.prototype,"addNodeToCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(void 0===t&&(t=!0),e.identifierAttribute){var r=e.identifier;this.cache.has(r)||this.cache.set(r,Oe.array([],Zn));var n=this.cache.get(r);if(-1!==n.indexOf(e))throw Jn("Already registered");n.push(e),t&&this.updateLastCacheModificationPerId(r)}}}),Object.defineProperty(t.prototype,"mergeCache",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this;Ht(e.identifierCache.cache).forEach((function(e){return e.forEach((function(e){t.addNodeToCache(e)}))}))}}),Object.defineProperty(t.prototype,"notifyDied",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.identifierAttribute){var t=e.identifier,r=this.cache.get(t);r&&(r.remove(e),r.length||this.cache.delete(t),this.updateLastCacheModificationPerId(e.identifier))}}}),Object.defineProperty(t.prototype,"splitCache",{enumerable:!1,configurable:!0,writable:!0,value:function(r){var n,i=this,o=new t,a=r.path;return(n=this.cache,Nr(n)?$t(n).map((function(e){return[e,n[e]]})):Pr(n)?$t(n).map((function(e){return[e,n.get(e)]})):xr(n)?Array.from(n.entries()):yr(n)?n.map((function(e,t){return[t,e]})):void e(7)).forEach((function(e){for(var t=on(e,2),r=t[0],n=t[1],s=!1,u=n.length-1;u>=0;u--)0===n[u].path.indexOf(a)&&(o.addNodeToCache(n[u],!1),n.splice(u,1),s=!0);s&&i.updateLastCacheModificationPerId(r)})),o}}),Object.defineProperty(t.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);return!!r&&r.some((function(t){return e.isAssignableFrom(t.type)}))}}),Object.defineProperty(t.prototype,"resolve",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.cache.get(t);if(!r)return null;var n=r.filter((function(t){return e.isAssignableFrom(t.type)}));switch(n.length){case 0:return null;case 1:return n[0];default:throw Jn("Cannot resolve a reference to type '"+e.name+"' with id: '"+t+"' unambigously, there are multiple candidates: "+n.map((function(e){return e.path})).join(", "))}}}),t}();function Ln(e,t,r,n,i){var o=Gn(i);if(o){if(o.parent)throw Jn("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:"")+"/"+r+"', but it lives already at '"+o.path+"'");return t&&o.setParent(t,r),o}return new yn(e,t,r,n,i)}function $n(e,t,r,n,i){return new pn(e,t,r,n,i)}function Hn(e){return!(!e||!e.$treenode)}function Bn(e){if(!Hn(e))throw Jn("Value "+e+" is no MST Node");return e.$treenode}function Gn(e){return e&&e.$treenode||null}function Kn(){return Bn(this).snapshot}function qn(e,t,r){void 0===r&&(r=!0);for(var n=e,i=0;i0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"register",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return void 0===t&&(t=!1),t?this.handlers.unshift(e):this.handlers.push(e),function(){r.unregister(e)}}}),Object.defineProperty(e.prototype,"has",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.handlers.indexOf(e)>=0}}),Object.defineProperty(e.prototype,"unregister",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}),Object.defineProperty(e.prototype,"clear",{enumerable:!1,configurable:!0,writable:!0,value:function(){this.handlers.length=0}}),Object.defineProperty(e.prototype,"emit",{enumerable:!1,configurable:!0,writable:!0,value:function(){for(var e=[],t=0;t0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._determineIdentifierMode(),Ln(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"_determineIdentifierMode",{enumerable:!1,configurable:!0,writable:!0,value:function(){if(this.identifierMode===gi.UNKNOWN){var e=[];if(_i(this._subType,e)){var t=void 0;e.forEach((function(e){if(e.identifierAttribute){if(t&&t!==e.identifierAttribute)throw Jn("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=gi.YES,this.mapIdentifierAttribute=t):this.identifierMode=gi.NO}}}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t={});var r=e.type._subType,n={};return Object.keys(t).forEach((function(i){n[i]=r.instantiate(e,i,void 0,t[i])})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return new wi(e)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){zt(t,e.unbox),e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=Tn(t,e,n);si(t,e,i)}))})),Ft(t,this.willChange),Kt(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"Map"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Ht(e.storedValue)}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=e.storedValue.get(""+t);if(!r)throw Jn("Not a child "+t);return r}}),Object.defineProperty(t.prototype,"willChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Bn(e.object),r=e.name;t.assertWritable({subpath:r});var n=t.type,i=n._subType;switch(e.type){case"update":var o=e.newValue;if(o===e.object.get(r))return null;Un(i,o),e.newValue=i.reconcile(t.getChildNode(r),e.newValue,t,r),n.processIdentifier(r,e.newValue);break;case"add":Un(i,e.newValue),e.newValue=i.instantiate(t,r,void 0,e.newValue),n.processIdentifier(r,e.newValue)}return e}}),Object.defineProperty(t.prototype,"processIdentifier",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.identifierMode===gi.YES&&t instanceof yn){var r=t.identifier;if(r!==e)throw Jn("A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '"+r+"', but expected: '"+e+"'")}}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return e.getChildren().forEach((function(e){t[e.subpath]=e.snapshot})),t}}),Object.defineProperty(t.prototype,"processInitialSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t={};return Object.keys(e).forEach((function(r){t[r]=e[r].getSnapshot()})),t}}),Object.defineProperty(t.prototype,"didChange",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=Bn(e.object);switch(e.type){case"update":return void t.emitPatch({op:"replace",path:bi(e.name),value:e.newValue.snapshot,oldValue:e.oldValue?e.oldValue.snapshot:void 0},t);case"add":return void t.emitPatch({op:"add",path:bi(e.name),value:e.newValue.snapshot,oldValue:void 0},t);case"delete":var r=e.oldValue.snapshot;return e.oldValue.die(),void t.emitPatch({op:"remove",path:bi(e.name),oldValue:r},t)}}}),Object.defineProperty(t.prototype,"applyPatchLocally",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=e.storedValue;switch(r.op){case"add":case"replace":n.set(t,r.value);break;case"remove":n.delete(t)}}}),Object.defineProperty(t.prototype,"applySnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Un(this,t);var r=e.storedValue,n={};if(Array.from(r.keys()).forEach((function(e){n[e]=!1})),t)for(var i in t)r.set(i,t[i]),n[""+i]=!0;Object.keys(n).forEach((function(e){!1===n[e]&&r.delete(e)}))}}),Object.defineProperty(t.prototype,"getChildType",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this;return ii(e)?Rn(Object.keys(e).map((function(n){return r._subType.validate(e[n],Dn(t,n,r._subType))}))):Vn(t,e,"Value is not a plain object")}}),Object.defineProperty(t.prototype,"getDefaultSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){return Xn}}),Object.defineProperty(t.prototype,"removeChild",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){e.storedValue.delete(t)}}),t}(wn);Oi.prototype.applySnapshot=Ot(Oi.prototype.applySnapshot);var ji=function(e){function t(t,r,n){void 0===n&&(n=[]);var i=e.call(this,t)||this;return Object.defineProperty(i,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Array}),Object.defineProperty(i,"hookInitializers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),i.hookInitializers=n,i}return tn(t,e),Object.defineProperty(t.prototype,"hooks",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var r=this.hookInitializers.length>0?this.hookInitializers.concat(e):[e];return new t(this.name,this._subType,r)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return Ln(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"initializeChildNodes",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){void 0===t&&(t=[]);var r=e.type._subType,n={};return t.forEach((function(t,i){var o=""+i;n[o]=r.instantiate(e,o,void 0,t)})),n}}),Object.defineProperty(t.prototype,"createNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return Oe.array(Wn(e),Zn)}}),Object.defineProperty(t.prototype,"finalizeNewInstance",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){Gr(t).dehancer=e.unbox,e.type.hookInitializers.forEach((function(e){var r=e(t);Object.keys(r).forEach((function(e){var n=r[e],i=Tn(t,e,n);si(t,e,i)}))})),Ft(t,this.willChange),Kt(t,this.didChange)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subType.describe()+"[]"}}),Object.defineProperty(t.prototype,"getChildren",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.slice()}}),Object.defineProperty(t.prototype,"getChildNode",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=Number(t);if(r=0;r--)t.emitPatch({op:"remove",path:""+(e.index+r),oldValue:e.removed[r].snapshot},t);for(r=0;r0)return r;var n=Hn(e)?Bn(e).snapshot:e;return this._predicate(n)?Nn():Vn(t,e,this._message(e))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(_n);var Gi=function(e){function t(t,r,n){var i=e.call(this,t)||this;return Object.defineProperty(i,"_types",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"_dispatcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"_eager",{enumerable:!0,configurable:!0,writable:!0,value:!0}),n=rn({eager:!0,dispatcher:void 0},n),i._dispatcher=n.dispatcher,n.eager||(i._eager=!1),i}return tn(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){var e=bn.Union;return this._types.forEach((function(t){e|=t.flags})),e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._types.some((function(t){return t.isAssignableFrom(e)}))}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"("+this._types.map((function(e){return e.describe()})).join(" | ")+")"}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(n,void 0);if(!i)throw Jn("No matching type for union "+this.describe());return i.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=this.determineType(t,e.type);if(!i)throw Jn("No matching type for union "+this.describe());return i.reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"determineType",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this._dispatcher?this._dispatcher(e):t?t.is(e)?t:this._types.filter((function(e){return e!==t})).find((function(t){return t.is(e)})):this._types.find((function(t){return t.is(e)}))}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this._dispatcher)return this._dispatcher(e).validate(e,t);for(var r=[],n=0,i=0;i=0){var i=this.getDefaultInstanceOrSnapshot();return this._subtype.instantiate(e,t,r,i)}return this._subtype.instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this._subtype.reconcile(e,this.optionalValues.indexOf(t)<0&&this._subtype.is(t)?t:this.getDefaultInstanceOrSnapshot(),r,n)}}),Object.defineProperty(t.prototype,"getDefaultInstanceOrSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e="function"==typeof this._defaultValue?this._defaultValue():this._defaultValue;return"function"==typeof this._defaultValue&&Un(this,e),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return this.optionalValues.indexOf(e)>=0?Nn():this._subtype.validate(e,t)}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this._subtype.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this._subtype}}),t}(_n);function Wi(e,t,r){return function(e,t){if("function"!=typeof t&&Hn(t))throw Jn("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead")}(0,t),new qi(e,t,r||Yi)}var Yi=[void 0],Qi=Wi(zi,void 0),Xi=Wi(Mi,null);function Zi(e){return Ki(e,Qi)}var Ji=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"_definition",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"_subType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n}return tn(t,e),Object.defineProperty(t.prototype,"flags",{get:function(){return(this._subType?this._subType.flags:0)|bn.Late},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getSubType",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(!this._subType){var t=void 0;try{t=this._definition()}catch(e){if(!(e instanceof ReferenceError))throw e;t=void 0}if(e&&void 0===t)throw Jn("Late type seems to be used too early, the definition (still) returns undefined");t&&(this._subType=t)}return this._subType}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).instantiate(e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return this.getSubType(!0).reconcile(e,t,r,n)}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e?e.name:""}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this.getSubType(!1);return r?r.validate(e,t):Nn()}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=this.getSubType(!1);return!!t&&t.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"getSubTypes",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this.getSubType(!1);return e||gn}}),t}(_n);var eo=function(e){function t(t){var r=e.call(this,t?"frozen("+t.name+")":"frozen")||this;return Object.defineProperty(r,"subType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Frozen}),r}return tn(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return""}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return $n(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return function(e){return"function"!=typeof e}(e)?this.subType?this.subType.validate(e,t):Nn():Vn(t,e,"Value is not serializable and cannot be frozen")}}),t}(On),to=new eo;var ro=function(){function e(e,t){if(Object.defineProperty(this,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"identifier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolvedReference",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),bo(e))this.identifier=e;else{if(!Hn(e))throw Jn("Can only store references to tree nodes or identifiers, got: '"+e+"'");var r=Bn(e);if(!r.identifierAttribute)throw Jn("Can only store references with a defined identifier attribute.");var n=r.unnormalizedIdentifier;if(null==n)throw Jn("Can only store references to tree nodes with a defined identifier.");this.identifier=n}}return Object.defineProperty(e.prototype,"updateResolvedReference",{enumerable:!1,configurable:!0,writable:!0,value:function(e){var t=ho(this.identifier),r=e.root,n=r.identifierCache.getLastCacheModificationPerId(t);if(!this.resolvedReference||this.resolvedReference.lastCacheModification!==n){var i=this.targetType,o=r.identifierCache.resolve(i,t);if(!o)throw new no("[mobx-state-tree] Failed to resolve reference '"+this.identifier+"' to type '"+this.targetType.name+"' (from node: "+e.path+")");this.resolvedReference={node:o,lastCacheModification:n}}}}),Object.defineProperty(e.prototype,"resolvedValue",{get:function(){return this.updateResolvedReference(this.node),this.resolvedReference.node.value},enumerable:!1,configurable:!0}),e}(),no=function(e){function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return tn(t,e),t}(Error),io=function(e){function t(t,r){var n=e.call(this,"reference("+t.name+")")||this;return Object.defineProperty(n,"targetType",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"onInvalidated",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Reference}),n}return tn(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isAssignableFrom",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.targetType.isAssignableFrom(e)}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return bo(e)?Nn():Vn(t,e,"Value is not a valid identifier, which is a string or a number")}}),Object.defineProperty(t.prototype,"fireInvalidated",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=t.parent;if(i&&i.isAlive){var o=i.storedValue;o&&this.onInvalidated({cause:e,parent:o,invalidTarget:n?n.storedValue:void 0,invalidId:r,replaceRef:function(e){un(t.root.storedValue,{op:"replace",value:e,path:t.path})},removeRef:function(){!function(e){return jn(e)&&(e.flags&bn.Object)>0}(i.type)?un(t.root.storedValue,{op:"remove",path:t.path}):this.replaceRef(void 0)}})}}}),Object.defineProperty(t.prototype,"addTargetNodeWatcher",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){var r=this,n=this.getValue(e);if(n){var i=Bn(n),o=function(n,o){var a=function(e){switch(e){case Jr.beforeDestroy:return"destroy";case Jr.beforeDetach:return"detach";default:return}}(o);a&&r.fireInvalidated(a,e,t,i)},a=i.registerHook(Jr.beforeDetach,o),s=i.registerHook(Jr.beforeDestroy,o);return function(){a(),s()}}}}),Object.defineProperty(t.prototype,"watchTargetNodeForInvalidations",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r){var n=this;if(this.onInvalidated){var i;e.registerHook(Jr.beforeDestroy,(function(){i&&i()}));var o=function(o){i&&i();var a=e.parent,s=a&&a.storedValue;if(a&&a.isAlive&&s){(r?!!r.get(t,s):e.root.identifierCache.has(n.targetType,ho(t)))?i=n.addTargetNodeWatcher(e,t):o||n.fireInvalidated("invalidSnapshotReference",e,t,null)}};e.state===Mn.FINALIZED?o(!0):(e.isRoot||e.root.registerHook(Jr.afterCreationFinalization,(function(){e.parent&&e.parent.createObservableInstanceIfNeeded()})),e.registerHook(Jr.afterAttach,(function(){o(!1)})))}}}),t}(On),oo=function(e){function t(t,r){return e.call(this,t,r)||this}return tn(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return e.storedValue.resolvedValue}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue.identifier}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Hn(n)?Bn(n).identifier:n,o=new ro(n,this.targetType),a=$n(this,e,t,r,o);return o.node=a,this.watchTargetNodeForInvalidations(a,i,void 0),a}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!e.isDetaching&&e.type===this){var i=Hn(t),o=e.storedValue;if(!i&&o.identifier===t||i&&o.resolvedValue===t)return e.setParent(r,n),e}var a=this.instantiate(r,n,void 0,t);return e.die(),a}}),t}(io),ao=function(e){function t(t,r,n){var i=e.call(this,t,n)||this;return Object.defineProperty(i,"options",{enumerable:!0,configurable:!0,writable:!0,value:r}),i}return tn(t,e),Object.defineProperty(t.prototype,"getValue",{enumerable:!1,configurable:!0,writable:!0,value:function(e){if(e.isAlive)return this.options.get(e.storedValue,e.parent?e.parent.storedValue:null)}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Hn(n)?this.options.set(n,e?e.storedValue:null):n,o=$n(this,e,t,r,i);return this.watchTargetNodeForInvalidations(o,i,this.options),o}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=Hn(t)?this.options.set(t,e?e.storedValue:null):t;if(!e.isDetaching&&e.type===this&&e.storedValue===i)return e.setParent(r,n),e;var o=this.instantiate(r,n,void 0,i);return e.die(),o}}),t}(io);function so(e,t){var r=t||void 0,n=t?t.onInvalidated:void 0;return r&&(r.get||r.set)?new ao(e,{get:r.get,set:r.set},n):new oo(e,n)}var uo=function(e){function t(t,r){var n=e.call(this,t)||this;return Object.defineProperty(n,"validType",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Identifier}),n}return tn(t,e),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(!(e&&e.type instanceof ki))throw Jn("Identifier types can only be instantiated as direct child of a model type");return $n(this,e,t,r,n)}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){if(e.storedValue!==t)throw Jn("Tried to change identifier from '"+e.storedValue+"' to '"+t+"'. Changing identifiers is not allowed.");return e.setParent(r,n),e}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){return typeof e!==this.validType?Vn(t,e,"Value is not a valid "+this.describe()+", expected a "+this.validType):Nn()}}),t}(On),co=function(e){function t(){var t=e.call(this,"identifier","string")||this;return Object.defineProperty(t,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Identifier}),t}return tn(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifier"}}),t}(uo),lo=function(e){function t(){return e.call(this,"identifierNumber","number")||this}return tn(t,e),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return e.storedValue}}),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return"identifierNumber"}}),t}(uo),fo=new co,po=new lo;function ho(e){return""+e}function bo(e){return"string"==typeof e||"number"==typeof e}var vo,yo=function(e){function t(t){var r=e.call(this,t.name)||this;return Object.defineProperty(r,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"flags",{enumerable:!0,configurable:!0,writable:!0,value:bn.Custom}),r}return tn(t,e),Object.defineProperty(t.prototype,"describe",{enumerable:!1,configurable:!0,writable:!0,value:function(){return this.name}}),Object.defineProperty(t.prototype,"isValidSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t){if(this.options.isTargetType(e))return Nn();var r=this.options.getValidationMessage(e);return r?Vn(t,e,"Invalid value for type '"+this.name+"': "+r):Nn()}}),Object.defineProperty(t.prototype,"getSnapshot",{enumerable:!1,configurable:!0,writable:!0,value:function(e){return this.options.toSnapshot(e.storedValue)}}),Object.defineProperty(t.prototype,"instantiate",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){return $n(this,e,t,r,this.options.isTargetType(n)?n:this.options.fromSnapshot(n,e&&e.root.environment))}}),Object.defineProperty(t.prototype,"reconcile",{enumerable:!1,configurable:!0,writable:!0,value:function(e,t,r,n){var i=!this.options.isTargetType(t);if(!e.isDetaching&&(e.type===this&&(i?t===e.snapshot:t===e.storedValue)))return e.setParent(r,n),e;var o=i?this.options.fromSnapshot(t,r.root.environment):t,a=this.instantiate(r,n,void 0,o);return e.die(),a}}),t}(On),go={enumeration:function(e,t){var r="string"==typeof e?t:e,n=Ki.apply(void 0,an(r.map((function(e){return Hi(""+e)}))));return"string"==typeof e&&(n.name=e),n},model:function(){for(var e=[],t=0;t",e)},array:function(e){return new ji(e.name+"[]",e)},frozen:function(e){return 0===arguments.length?to:jn(e)?new eo(e):Wi(to,e)},identifier:fo,identifierNumber:po,late:function(e,t){var r="string"==typeof e?e:"late("+e.toString()+")";return new Ji(r,"string"==typeof e?t:e)},undefined:zi,null:Mi,snapshotProcessor:function(e,t,r){return new yi(e,t,r)}},mo=new Uint8Array(16);function _o(){if(!vo&&!(vo="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vo(mo)}var wo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Oo(e){return"string"==typeof e&&wo.test(e)}for(var jo=[],Po=0;Po<256;++Po)jo.push((Po+256).toString(16).substr(1));function So(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(jo[e[t+0]]+jo[e[t+1]]+jo[e[t+2]]+jo[e[t+3]]+"-"+jo[e[t+4]]+jo[e[t+5]]+"-"+jo[e[t+6]]+jo[e[t+7]]+"-"+jo[e[t+8]]+jo[e[t+9]]+"-"+jo[e[t+10]]+jo[e[t+11]]+jo[e[t+12]]+jo[e[t+13]]+jo[e[t+14]]+jo[e[t+15]]).toLowerCase();if(!Oo(r))throw TypeError("Stringified UUID is invalid");return r}function Ao(e,t,r){var n=(e=e||{}).random||(e.rng||_o)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return So(n)}function xo(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function Eo(e,t){return e<>>32-t}var To=function(e,t,r){function n(e,n,i,o){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}(n)),16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var a=new Uint8Array(16+e.length);if(a.set(n),a.set(e,n.length),(a=r(a))[6]=15&a[6]|t,a[8]=63&a[8]|128,i){o=o||0;for(var s=0;s<16;++s)i[o+s]=a[s];return i}return So(a)}try{n.name=e}catch(e){}return n.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",n.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",n}("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i>>0;m=g,g=y,y=Eo(v,30)>>>0,v=d,d=O}r[0]=r[0]+d>>>0,r[1]=r[1]+v>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+g>>>0,r[4]=r[4]+m>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]})); /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -228,7 +228,7 @@ var tr=function(e,t){return(tr=Object.setPrototypeOf||{__proto__:[]}instanceof A * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -const Io=go.enumeration("TaskState",["free","pending","complete","error","destroyed"]),Co={anyType:go.custom({name:"any",fromSnapshot:e=>e,toSnapshot:e=>e,isTargetType:()=>!0,getValidationMessage:()=>""})},ko=go.model({uuid:go.string,spiderUUID:go.string,dataSlide:go.array(go.string),dataSlideUUID:go.string,createdAt:go.Date,errorMessage:go.optional(go.string,""),status:Io,updatedAt:go.Date,originData:go.maybe(Co.anyType),output:go.maybe(Co.anyType)}).actions((e=>({$backup:()=>cr(e),$import(e){return Br(e).applySnapshot(t);var t},start(){if("pending"===e.status)throw new Error("Task 处在 pending 状态");return e.dataSlide=[],e.dataSlideUUID="",e.status="pending",e.output||e.originData},success(t,n){e.status="free",e.output=t,this._addUUIDToDataSlide(n)},complete(t){e.status="complete",this._addUUIDToDataSlide(t)},error(t="",n){e.status="error",e.errorMessage=t,this._addUUIDToDataSlide(n)},destroy(){var t;(t=Br(e)).isRoot?t.die():t.parent.removeChild(t.subpath)},_addUUIDToDataSlide(t){t&&(e.dataSlide.push(t),e.dataSlideUUID=t)}})));function Do(e){return ko.create(function({spiderUUID:e,originData:t}){return{uuid:Ao(),spiderUUID:e,createdAt:new Date,errorMessage:"",status:"free",updatedAt:new Date,dataSlideUUID:e,dataSlide:[],originData:t,output:null}}(e))} +const Io=go.enumeration("TaskState",["free","pending","complete","error","destroyed"]),Co={anyType:go.custom({name:"any",fromSnapshot:e=>e,toSnapshot:e=>e,isTargetType:()=>!0,getValidationMessage:()=>""})},ko=go.model({uuid:go.string,spiderUUID:go.string,dataSlide:go.array(go.string),dataSlideUUID:go.string,createdAt:go.Date,errorMessage:go.optional(go.string,""),status:Io,updatedAt:go.Date,originData:go.maybe(Co.anyType),output:go.maybe(Co.anyType)}).actions((e=>({$backup:()=>cn(e),$import(e){return Bn(e).applySnapshot(t);var t},start(){if("pending"===e.status)throw new Error("Task 处在 pending 状态");return e.dataSlide=[],e.dataSlideUUID="",e.status="pending",e.output||e.originData},success(t,r){e.status="free",e.output=t,this._addUUIDToDataSlide(r)},complete(t){e.status="complete",this._addUUIDToDataSlide(t)},error(t="",r){e.status="error",e.errorMessage=t,this._addUUIDToDataSlide(r)},destroy(){var t;(t=Bn(e)).isRoot?t.die():t.parent.removeChild(t.subpath)},_addUUIDToDataSlide(t){t&&(e.dataSlide.push(t),e.dataSlideUUID=t)}})));function Do(e){return ko.create(function({spiderUUID:e,originData:t}){return{uuid:Ao(),spiderUUID:e,createdAt:new Date,errorMessage:"",status:"free",updatedAt:new Date,dataSlideUUID:e,dataSlide:[],originData:t,output:null}}(e))} /*! ***************************************************************************** Copyright (c) Microsoft Corporation. @@ -242,39 +242,39 @@ const Io=go.enumeration("TaskState",["free","pending","complete","error","destro LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */var No=function(e,t){return(No=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 Vo(e,t){function n(){this.constructor=e}No(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function Ro(e){return"function"==typeof e}var Uo=!1,Mo={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;Uo=e},get useDeprecatedSynchronousErrorHandling(){return Uo}};function Fo(e){setTimeout((function(){throw e}),0)}var zo={closed:!0,next:function(e){},error:function(e){if(Mo.useDeprecatedSynchronousErrorHandling)throw e;Fo(e)},complete:function(){}},Lo=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function $o(e){return null!==e&&"object"==typeof e}var Ho=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),Bo=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var n=this,r=n._parentOrParents,i=n._ctorUnsubscribe,o=n._unsubscribe,a=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,r instanceof e)r.remove(this);else if(null!==r)for(var s=0;s1)this.connection=null;else{var n=this.connection,r=e._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},t}(qo),ca=function(e){function t(t,n){var r=e.call(this)||this;return r.source=t,r.subjectFactory=n,r._refCount=0,r._isComplete=!1,r}return Vo(t,e),t.prototype._subscribe=function(e){return this.getSubject().subscribe(e)},t.prototype.getSubject=function(){var e=this._subject;return e&&!e.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype.connect=function(){var e=this._connection;return e||(this._isComplete=!1,(e=this._connection=new Bo).add(this.source.subscribe(new fa(this.getSubject(),this))),e.closed&&(this._connection=null,e=Bo.EMPTY)),e},t.prototype.refCount=function(){return aa()(this)},t}(Jo),la=function(){var e=ca.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:e._subscribe},_isComplete:{value:e._isComplete,writable:!0},getSubject:{value:e.getSubject},connect:{value:e.connect},refCount:{value:e.refCount}}}(),fa=function(e){function t(t,n){var r=e.call(this,t)||this;return r.connectable=n,r}return Vo(t,e),t.prototype._error=function(t){this._unsubscribe(),e.prototype._error.call(this,t)},t.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){var e=this.connectable;if(e){this.connectable=null;var t=e._connection;e._refCount=0,e._subject=null,e._connection=null,t&&t.unsubscribe()}},t}(ra),pa=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.scheduler=t,r.work=n,r.pending=!1,r}return Vo(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(r,this.id,t),this},t.prototype.requestAsyncId=function(e,t,n){return void 0===n&&(n=0),setInterval(e.flush.bind(e,this),n)},t.prototype.recycleAsyncId=function(e,t,n){if(void 0===n&&(n=0),null!==n&&this.delay===n&&!1===this.pending)return t;clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(e,t);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n=!1,r=void 0;try{this.work(e)}catch(e){n=!0,r=!!e&&e||new Error(e)}if(n)return this.unsubscribe(),r},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,n=t.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,n){return e.call(this)||this}return Vo(t,e),t.prototype.schedule=function(e,t){return this},t}(Bo)),ha=function(){function e(t,n){void 0===n&&(n=e.now),this.SchedulerAction=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(n,t)},e.now=function(){return Date.now()},e}(),ba=function(e){function t(n,r){void 0===r&&(r=ha.now);var i=e.call(this,n,(function(){return t.delegate&&t.delegate!==i?t.delegate.now():r()}))||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return Vo(t,e),t.prototype.schedule=function(n,r,i){return void 0===r&&(r=0),t.delegate&&t.delegate!==this?t.delegate.schedule(n,r,i):e.prototype.schedule.call(this,n,r,i)},t.prototype.flush=function(e){var t=this.actions;if(this.active)t.push(e);else{var n;this.active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this.active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(ha),da=new Jo((function(e){return e.complete()}));function va(e){return e&&"function"==typeof e.schedule}var ya=function(e){return function(t){for(var n=0,r=e.length;n0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(Ra);function La(e,t,n){return n?La(e,t).pipe(ja((function(e){return Lo(e)?n.apply(void 0,e):n(e)}))):new Jo((function(n){var r,i=function(){for(var e=[],t=0;t=0}function Ha(e,t){return function(n){return n.lift(new Ba(e,t))}}var Ba=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Ga(e,this.predicate,this.thisArg))},e}(),Ga=function(e){function t(t,n,r){var i=e.call(this,t)||this;return i.predicate=n,i.thisArg=r,i.count=0,i}return Vo(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(qo);function Ka(e,t,n){void 0===e&&(e=0);var r=-1;return $a(t)?r=Number(t)<1?1:Number(t):va(t)&&(n=t),va(n)||(n=wa),new Jo((function(t){var i=$a(e)?e:+e-n.now();return n.schedule(qa,i,{index:0,period:r,subscriber:t})}))}function qa(e){var t=e.index,n=e.period,r=e.subscriber;if(r.next(t),!r.closed){if(-1===n)return r.complete();e.index=t+1,this.schedule(e,n)}}var Wa="object"==typeof global&&global&&global.Object===Object&&global,Ya="object"==typeof self&&self&&self.Object===Object&&self,Qa=Wa||Ya||Function("return this")(),Xa=Qa.Symbol,Za=Object.prototype,Ja=Za.hasOwnProperty,es=Za.toString,ts=Xa?Xa.toStringTag:void 0;var ns=Object.prototype.toString;var rs=Xa?Xa.toStringTag:void 0;function is(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":rs&&rs in Object(e)?function(e){var t=Ja.call(e,ts),n=e[ts];try{e[ts]=void 0;var r=!0}catch(e){}var i=es.call(e);return r&&(t?e[ts]=n:delete e[ts]),i}(e):function(e){return ns.call(e)}(e)}function os(e){return null!=e&&"object"==typeof e}function as(e){return"symbol"==typeof e||os(e)&&"[object Symbol]"==is(e)}function ss(e,t){for(var n=-1,r=null==e?0:e.length,i=Array(r);++n0){if(++Is>=800)return arguments[0]}else Is=0;return Ts.apply(void 0,arguments)});function Ns(e){return e!=e}function Vs(e,t){return!!(null==e?0:e.length)&&function(e,t,n){return t==t?function(e,t,n){for(var r=n-1,i=e.length;++r-1}var Rs=/^(?:0|[1-9]\d*)$/;function Us(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&Rs.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}function Bs(e){return os(e)&&"[object Arguments]"==is(e)}var Gs=Object.prototype,Ks=Gs.hasOwnProperty,qs=Gs.propertyIsEnumerable,Ws=Bs(function(){return arguments}())?Bs:function(e){return os(e)&&Ks.call(e,"callee")&&!qs.call(e,"callee")};function Ys(e){return function(t){return e(t)}}var Qs="object"==typeof exports&&exports&&!exports.nodeType&&exports,Xs=Qs&&"object"==typeof module&&module&&!module.nodeType&&module,Zs=Xs&&Xs.exports===Qs&&Wa.process,Js=function(){try{var e=Xs&&Xs.require&&Xs.require("util").types;return e||Zs&&Zs.binding&&Zs.binding("util")}catch(e){}}(),eu=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,tu=/^\w*$/;var nu=As(Object,"create");var ru=Object.prototype.hasOwnProperty;var iu=Object.prototype.hasOwnProperty;function ou(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t-1},uu.prototype.set=function(e,t){var n=this.__data__,r=au(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this};var cu=As(Qa,"Map");function lu(e,t){var n=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?n["string"==typeof t?"string":"hash"]:n.map}function fu(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t0&&n(s)?t>1?Ou(s,t-1,n,r,i):mu(i,s):r||(i[i.length]=s)}return i}function ju(e){return(null==e?0:e.length)?Ou(e,1):[]}function Pu(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new fu;++t=200&&(o=Su,a=!1,t=new Pu(t));e:for(;++i=2&&(r=arguments[1]);var i=Number.POSITIVE_INFINITY;return t>=3&&(i=arguments[2]),function(t){return t.lift(new Uu(e,r,i,n))}}var Uu=function(){function e(e,t,n,r){this.bufferTimeSpan=e,this.bufferCreationInterval=t,this.maxBufferSize=n,this.scheduler=r}return e.prototype.call=function(e,t){return t.subscribe(new Fu(e,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))},e}(),Mu=function(){return function(){this.buffer=[]}}(),Fu=function(e){function t(t,n,r,i,o){var a=e.call(this,t)||this;a.bufferTimeSpan=n,a.bufferCreationInterval=r,a.maxBufferSize=i,a.scheduler=o,a.contexts=[];var s=a.openContext();if(a.timespanOnly=null==r||r<0,a.timespanOnly){var u={subscriber:a,context:s,bufferTimeSpan:n};a.add(s.closeAction=o.schedule(zu,n,u))}else{var c={subscriber:a,context:s},l={bufferTimeSpan:n,bufferCreationInterval:r,subscriber:a,scheduler:o};a.add(s.closeAction=o.schedule($u,n,c)),a.add(o.schedule(Lu,r,l))}return a}return Vo(t,e),t.prototype._next=function(e){for(var t,n=this.contexts,r=n.length,i=0;i0;){var r=t.shift();n.next(r.buffer)}e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){this.contexts=null},t.prototype.onBufferFull=function(e){this.closeContext(e);var t=e.closeAction;if(t.unsubscribe(),this.remove(t),!this.closed&&this.timespanOnly){e=this.openContext();var n=this.bufferTimeSpan,r={subscriber:this,context:e,bufferTimeSpan:n};this.add(e.closeAction=this.scheduler.schedule(zu,n,r))}},t.prototype.openContext=function(){var e=new Mu;return this.contexts.push(e),e},t.prototype.closeContext=function(e){this.destination.next(e.buffer);var t=this.contexts;(t?t.indexOf(e):-1)>=0&&t.splice(t.indexOf(e),1)},t}(qo);function zu(e){var t=e.subscriber,n=e.context;n&&t.closeContext(n),t.closed||(e.context=t.openContext(),e.context.closeAction=this.schedule(e,e.bufferTimeSpan))}function Lu(e){var t=e.bufferCreationInterval,n=e.bufferTimeSpan,r=e.subscriber,i=e.scheduler,o=r.openContext();r.closed||(r.add(o.closeAction=i.schedule($u,n,{subscriber:r,context:o})),this.schedule(e,t))}function $u(e){var t=e.subscriber,n=e.context;t.closeContext(n)}function Hu(e){return function(t){var n=new Bu(e),r=t.lift(n);return n.caught=r}}var Bu=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new Gu(e,this.selector,this.caught))},e}(),Gu=function(e){function t(t,n,r){var i=e.call(this,t)||this;return i.selector=n,i.caught=r,i}return Vo(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=void 0;try{n=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var r=new Va(this);this.add(r);var i=Ua(n,r);i!==r&&this.add(i)}},t}(Ra);function Ku(e,t){return Ma(e,t,1)}function qu(e,t){return t?function(n){return new Qu(n,t).lift(new Wu(e))}:function(t){return t.lift(new Wu(e))}}var Wu=function(){function e(e){this.delayDurationSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new Yu(e,this.delayDurationSelector))},e}(),Yu=function(e){function t(t,n){var r=e.call(this,t)||this;return r.delayDurationSelector=n,r.completed=!1,r.delayNotifierSubscriptions=[],r.index=0,r}return Vo(t,e),t.prototype.notifyNext=function(e,t,n,r,i){this.destination.next(e),this.removeSubscription(i),this.tryComplete()},t.prototype.notifyError=function(e,t){this._error(e)},t.prototype.notifyComplete=function(e){var t=this.removeSubscription(e);t&&this.destination.next(t),this.tryComplete()},t.prototype._next=function(e){var t=this.index++;try{var n=this.delayDurationSelector(e,t);n&&this.tryDelay(n,e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){this.completed=!0,this.tryComplete(),this.unsubscribe()},t.prototype.removeSubscription=function(e){e.unsubscribe();var t=this.delayNotifierSubscriptions.indexOf(e);return-1!==t&&this.delayNotifierSubscriptions.splice(t,1),e.outerValue},t.prototype.tryDelay=function(e,t){var n=function(e,t,n,r,i){if(void 0===i&&(i=new xa(e,n,r)),!i.closed)return t instanceof Jo?t.subscribe(i):ka(t)(i)}(this,e,t);n&&!n.closed&&(this.destination.add(n),this.delayNotifierSubscriptions.push(n))},t.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()},t}(Aa),Qu=function(e){function t(t,n){var r=e.call(this)||this;return r.source=t,r.subscriptionDelay=n,r}return Vo(t,e),t.prototype._subscribe=function(e){this.subscriptionDelay.subscribe(new Xu(e,this.source))},t}(Jo),Xu=function(e){function t(t,n){var r=e.call(this)||this;return r.parent=t,r.source=n,r.sourceSubscribed=!1,r}return Vo(t,e),t.prototype._next=function(e){this.subscribeToSource()},t.prototype._error=function(e){this.unsubscribe(),this.parent.error(e)},t.prototype._complete=function(){this.unsubscribe(),this.subscribeToSource()},t.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))},t}(qo);var Zu=function(){function e(e,t,n){void 0===n&&(n=!1),this.accumulator=e,this.seed=t,this.hasSeed=n}return e.prototype.call=function(e,t){return t.subscribe(new Ju(e,this.accumulator,this.seed,this.hasSeed))},e}(),Ju=function(e){function t(t,n,r,i){var o=e.call(this,t)||this;return o.accumulator=n,o._seed=r,o.hasSeed=i,o.index=0,o}return Vo(t,e),Object.defineProperty(t.prototype,"seed",{get:function(){return this._seed},set:function(e){this.hasSeed=!0,this._seed=e},enumerable:!0,configurable:!0}),t.prototype._next=function(e){if(this.hasSeed)return this._tryNext(e);this.seed=e,this.destination.next(e)},t.prototype._tryNext=function(e){var t,n=this.index++;try{t=this.accumulator(this.seed,e,n)}catch(e){this.destination.error(e)}this.seed=t,this.destination.next(t)},t}(qo);var ec=function(){function e(e,t){this.subjectFactory=e,this.selector=t}return e.prototype.call=function(e,t){var n=this.selector,r=this.subjectFactory(),i=n(r).subscribe(e);return i.add(t.subscribe(r)),i},e}();var tc=function(){function e(e,t){this.notifier=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new nc(e,this.notifier,this.source))},e}(),nc=function(e){function t(t,n,r){var i=e.call(this,t)||this;return i.notifier=n,i.source=r,i}return Vo(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=this.errors,r=this.retries,i=this.retriesSubscription;if(r)this.errors=void 0,this.retriesSubscription=void 0;else{n=new ia;try{r=(0,this.notifier)(n)}catch(t){return e.prototype.error.call(this,t)}i=Ua(r,new Va(this))}this._unsubscribeAndRecycle(),this.errors=n,this.retries=r,this.retriesSubscription=i,n.next(t)}},t.prototype._unsubscribe=function(){var e=this.errors,t=this.retriesSubscription;e&&(e.unsubscribe(),this.errors=void 0),t&&(t.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},t.prototype.notifyNext=function(){var e=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=e,this.source.subscribe(this)},t}(Ra);function rc(){return new ia}function ic(){return function(e){return aa()((t=rc,function(e){var r;if(r="function"==typeof t?t:function(){return t},"function"==typeof n)return e.lift(new ec(r,n));var i=Object.create(e,la);return i.source=e,i.subjectFactory=r,i})(e));var t,n}}function oc(e,t){return"function"==typeof t?function(n){return n.pipe(oc((function(n,r){return Na(e(n,r)).pipe(ja((function(e,i){return t(n,e,r,i)})))})))}:function(t){return t.lift(new ac(e))}}var ac=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new sc(e,this.project))},e}(),sc=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return Vo(t,e),t.prototype._next=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var n=new Va(this),r=this.destination;r.add(n),this.innerSubscription=Ua(e,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(Ra);function uc(e,t,n){return function(r){return r.lift(new cc(e,t,n))}}var cc=function(){function e(e,t,n){this.nextOrObserver=e,this.error=t,this.complete=n}return e.prototype.call=function(e,t){return t.subscribe(new lc(e,this.nextOrObserver,this.error,this.complete))},e}(),lc=function(e){function t(t,n,r,i){var o=e.call(this,t)||this;return o._tapNext=Oa,o._tapError=Oa,o._tapComplete=Oa,o._tapError=r||Oa,o._tapComplete=i||Oa,Ro(n)?(o._context=o,o._tapNext=n):n&&(o._context=n,o._tapNext=n.next||Oa,o._tapError=n.error||Oa,o._tapComplete=n.complete||Oa),o}return Vo(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(qo); + ***************************************************************************** */var No=function(e,t){return(No=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function Vo(e,t){function r(){this.constructor=e}No(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Ro(e){return"function"==typeof e}var Uo=!1,Mo={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;Uo=e},get useDeprecatedSynchronousErrorHandling(){return Uo}};function zo(e){setTimeout((function(){throw e}),0)}var Fo={closed:!0,next:function(e){},error:function(e){if(Mo.useDeprecatedSynchronousErrorHandling)throw e;zo(e)},complete:function(){}},Lo=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function $o(e){return null!==e&&"object"==typeof e}var Ho=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),Bo=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var r=this,n=r._parentOrParents,i=r._ctorUnsubscribe,o=r._unsubscribe,a=r._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,n instanceof e)n.remove(this);else if(null!==n)for(var s=0;s1)this.connection=null;else{var r=this.connection,n=e._connection;this.connection=null,!n||r&&n!==r||n.unsubscribe()}}else this.connection=null},t}(qo),ca=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subjectFactory=r,n._refCount=0,n._isComplete=!1,n}return Vo(t,e),t.prototype._subscribe=function(e){return this.getSubject().subscribe(e)},t.prototype.getSubject=function(){var e=this._subject;return e&&!e.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype.connect=function(){var e=this._connection;return e||(this._isComplete=!1,(e=this._connection=new Bo).add(this.source.subscribe(new fa(this.getSubject(),this))),e.closed&&(this._connection=null,e=Bo.EMPTY)),e},t.prototype.refCount=function(){return aa()(this)},t}(Jo),la=function(){var e=ca.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:e._subscribe},_isComplete:{value:e._isComplete,writable:!0},getSubject:{value:e.getSubject},connect:{value:e.connect},refCount:{value:e.refCount}}}(),fa=function(e){function t(t,r){var n=e.call(this,t)||this;return n.connectable=r,n}return Vo(t,e),t.prototype._error=function(t){this._unsubscribe(),e.prototype._error.call(this,t)},t.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){var e=this.connectable;if(e){this.connectable=null;var t=e._connection;e._refCount=0,e._subject=null,e._connection=null,t&&t.unsubscribe()}},t}(na),pa=function(e){function t(t,r){var n=e.call(this,t,r)||this;return n.scheduler=t,n.work=r,n.pending=!1,n}return Vo(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var r=this.id,n=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(n,r,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(n,this.id,t),this},t.prototype.requestAsyncId=function(e,t,r){return void 0===r&&(r=0),setInterval(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,t,r){if(void 0===r&&(r=0),null!==r&&this.delay===r&&!1===this.pending)return t;clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,t);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var r=!1,n=void 0;try{this.work(e)}catch(e){r=!0,n=!!e&&e||new Error(e)}if(r)return this.unsubscribe(),n},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,r=t.actions,n=r.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==n&&r.splice(n,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,r){return e.call(this)||this}return Vo(t,e),t.prototype.schedule=function(e,t){return this},t}(Bo)),ha=function(){function e(t,r){void 0===r&&(r=e.now),this.SchedulerAction=t,this.now=r}return e.prototype.schedule=function(e,t,r){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(r,t)},e.now=function(){return Date.now()},e}(),ba=function(e){function t(r,n){void 0===n&&(n=ha.now);var i=e.call(this,r,(function(){return t.delegate&&t.delegate!==i?t.delegate.now():n()}))||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return Vo(t,e),t.prototype.schedule=function(r,n,i){return void 0===n&&(n=0),t.delegate&&t.delegate!==this?t.delegate.schedule(r,n,i):e.prototype.schedule.call(this,r,n,i)},t.prototype.flush=function(e){var t=this.actions;if(this.active)t.push(e);else{var r;this.active=!0;do{if(r=e.execute(e.state,e.delay))break}while(e=t.shift());if(this.active=!1,r){for(;e=t.shift();)e.unsubscribe();throw r}}},t}(ha),da=new Jo((function(e){return e.complete()}));function va(e){return e&&"function"==typeof e.schedule}var ya=function(e){return function(t){for(var r=0,n=e.length;r0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(Ra);function La(e,t,r){return r?La(e,t).pipe(ja((function(e){return Lo(e)?r.apply(void 0,e):r(e)}))):new Jo((function(r){var n,i=function(){for(var e=[],t=0;t=0}function Ha(e,t){return function(r){return r.lift(new Ba(e,t))}}var Ba=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Ga(e,this.predicate,this.thisArg))},e}(),Ga=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.predicate=r,i.thisArg=n,i.count=0,i}return Vo(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(qo);function Ka(e,t,r){void 0===e&&(e=0);var n=-1;return $a(t)?n=Number(t)<1?1:Number(t):va(t)&&(r=t),va(r)||(r=wa),new Jo((function(t){var i=$a(e)?e:+e-r.now();return r.schedule(qa,i,{index:0,period:n,subscriber:t})}))}function qa(e){var t=e.index,r=e.period,n=e.subscriber;if(n.next(t),!n.closed){if(-1===r)return n.complete();e.index=t+1,this.schedule(e,r)}}var Wa="object"==typeof global&&global&&global.Object===Object&&global,Ya="object"==typeof self&&self&&self.Object===Object&&self,Qa=Wa||Ya||Function("return this")(),Xa=Qa.Symbol,Za=Object.prototype,Ja=Za.hasOwnProperty,es=Za.toString,ts=Xa?Xa.toStringTag:void 0;var rs=Object.prototype.toString;var ns=Xa?Xa.toStringTag:void 0;function is(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ns&&ns in Object(e)?function(e){var t=Ja.call(e,ts),r=e[ts];try{e[ts]=void 0;var n=!0}catch(e){}var i=es.call(e);return n&&(t?e[ts]=r:delete e[ts]),i}(e):function(e){return rs.call(e)}(e)}function os(e){return null!=e&&"object"==typeof e}function as(e){return"symbol"==typeof e||os(e)&&"[object Symbol]"==is(e)}function ss(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r0){if(++Is>=800)return arguments[0]}else Is=0;return Ts.apply(void 0,arguments)});function Ns(e){return e!=e}function Vs(e,t){return!!(null==e?0:e.length)&&function(e,t,r){return t==t?function(e,t,r){for(var n=r-1,i=e.length;++n-1}var Rs=/^(?:0|[1-9]\d*)$/;function Us(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&Rs.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}function Bs(e){return os(e)&&"[object Arguments]"==is(e)}var Gs=Object.prototype,Ks=Gs.hasOwnProperty,qs=Gs.propertyIsEnumerable,Ws=Bs(function(){return arguments}())?Bs:function(e){return os(e)&&Ks.call(e,"callee")&&!qs.call(e,"callee")};function Ys(e){return function(t){return e(t)}}var Qs="object"==typeof exports&&exports&&!exports.nodeType&&exports,Xs=Qs&&"object"==typeof module&&module&&!module.nodeType&&module,Zs=Xs&&Xs.exports===Qs&&Wa.process,Js=function(){try{var e=Xs&&Xs.require&&Xs.require("util").types;return e||Zs&&Zs.binding&&Zs.binding("util")}catch(e){}}(),eu=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,tu=/^\w*$/;var ru=As(Object,"create");var nu=Object.prototype.hasOwnProperty;var iu=Object.prototype.hasOwnProperty;function ou(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1},uu.prototype.set=function(e,t){var r=this.__data__,n=au(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};var cu=As(Qa,"Map");function lu(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function fu(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t0&&r(s)?t>1?Ou(s,t-1,r,n,i):mu(i,s):n||(i[i.length]=s)}return i}function ju(e){return(null==e?0:e.length)?Ou(e,1):[]}function Pu(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new fu;++t=200&&(o=Su,a=!1,t=new Pu(t));e:for(;++i0;){var n=t.shift();r.next(n.buffer)}e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){this.contexts=null},t.prototype.onBufferFull=function(e){this.closeContext(e);var t=e.closeAction;if(t.unsubscribe(),this.remove(t),!this.closed&&this.timespanOnly){e=this.openContext();var r=this.bufferTimeSpan,n={subscriber:this,context:e,bufferTimeSpan:r};this.add(e.closeAction=this.scheduler.schedule(zu,r,n))}},t.prototype.openContext=function(){var e=new Uu;return this.contexts.push(e),e},t.prototype.closeContext=function(e){this.destination.next(e.buffer);var t=this.contexts;(t?t.indexOf(e):-1)>=0&&t.splice(t.indexOf(e),1)},t}(qo);function zu(e){var t=e.subscriber,r=e.context;r&&t.closeContext(r),t.closed||(e.context=t.openContext(),e.context.closeAction=this.schedule(e,e.bufferTimeSpan))}function Fu(e){var t=e.bufferCreationInterval,r=e.bufferTimeSpan,n=e.subscriber,i=e.scheduler,o=n.openContext();n.closed||(n.add(o.closeAction=i.schedule(Lu,r,{subscriber:n,context:o})),this.schedule(e,t))}function Lu(e){var t=e.subscriber,r=e.context;t.closeContext(r)}function $u(e){return function(t){var r=new Hu(e),n=t.lift(r);return r.caught=n}}var Hu=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new Bu(e,this.selector,this.caught))},e}(),Bu=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.selector=r,i.caught=n,i}return Vo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=void 0;try{r=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var n=new Va(this);this.add(n);var i=Ua(r,n);i!==n&&this.add(i)}},t}(Ra);function Gu(e,t){return Ma(e,t,1)}function Ku(e,t){return t?function(r){return new Yu(r,t).lift(new qu(e))}:function(t){return t.lift(new qu(e))}}var qu=function(){function e(e){this.delayDurationSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new Wu(e,this.delayDurationSelector))},e}(),Wu=function(e){function t(t,r){var n=e.call(this,t)||this;return n.delayDurationSelector=r,n.completed=!1,n.delayNotifierSubscriptions=[],n.index=0,n}return Vo(t,e),t.prototype.notifyNext=function(e,t,r,n,i){this.destination.next(e),this.removeSubscription(i),this.tryComplete()},t.prototype.notifyError=function(e,t){this._error(e)},t.prototype.notifyComplete=function(e){var t=this.removeSubscription(e);t&&this.destination.next(t),this.tryComplete()},t.prototype._next=function(e){var t=this.index++;try{var r=this.delayDurationSelector(e,t);r&&this.tryDelay(r,e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){this.completed=!0,this.tryComplete(),this.unsubscribe()},t.prototype.removeSubscription=function(e){e.unsubscribe();var t=this.delayNotifierSubscriptions.indexOf(e);return-1!==t&&this.delayNotifierSubscriptions.splice(t,1),e.outerValue},t.prototype.tryDelay=function(e,t){var r=function(e,t,r,n,i){if(void 0===i&&(i=new xa(e,r,n)),!i.closed)return t instanceof Jo?t.subscribe(i):ka(t)(i)}(this,e,t);r&&!r.closed&&(this.destination.add(r),this.delayNotifierSubscriptions.push(r))},t.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()},t}(Aa),Yu=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subscriptionDelay=r,n}return Vo(t,e),t.prototype._subscribe=function(e){this.subscriptionDelay.subscribe(new Qu(e,this.source))},t}(Jo),Qu=function(e){function t(t,r){var n=e.call(this)||this;return n.parent=t,n.source=r,n.sourceSubscribed=!1,n}return Vo(t,e),t.prototype._next=function(e){this.subscribeToSource()},t.prototype._error=function(e){this.unsubscribe(),this.parent.error(e)},t.prototype._complete=function(){this.unsubscribe(),this.subscribeToSource()},t.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))},t}(qo);var Xu=function(){function e(e,t,r){void 0===r&&(r=!1),this.accumulator=e,this.seed=t,this.hasSeed=r}return e.prototype.call=function(e,t){return t.subscribe(new Zu(e,this.accumulator,this.seed,this.hasSeed))},e}(),Zu=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o.accumulator=r,o._seed=n,o.hasSeed=i,o.index=0,o}return Vo(t,e),Object.defineProperty(t.prototype,"seed",{get:function(){return this._seed},set:function(e){this.hasSeed=!0,this._seed=e},enumerable:!0,configurable:!0}),t.prototype._next=function(e){if(this.hasSeed)return this._tryNext(e);this.seed=e,this.destination.next(e)},t.prototype._tryNext=function(e){var t,r=this.index++;try{t=this.accumulator(this.seed,e,r)}catch(e){this.destination.error(e)}this.seed=t,this.destination.next(t)},t}(qo);var Ju=function(){function e(e,t){this.subjectFactory=e,this.selector=t}return e.prototype.call=function(e,t){var r=this.selector,n=this.subjectFactory(),i=r(n).subscribe(e);return i.add(t.subscribe(n)),i},e}();var ec=function(){function e(e,t){this.notifier=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new tc(e,this.notifier,this.source))},e}(),tc=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.notifier=r,i.source=n,i}return Vo(t,e),t.prototype.error=function(t){if(!this.isStopped){var r=this.errors,n=this.retries,i=this.retriesSubscription;if(n)this.errors=void 0,this.retriesSubscription=void 0;else{r=new ia;try{n=(0,this.notifier)(r)}catch(t){return e.prototype.error.call(this,t)}i=Ua(n,new Va(this))}this._unsubscribeAndRecycle(),this.errors=r,this.retries=n,this.retriesSubscription=i,r.next(t)}},t.prototype._unsubscribe=function(){var e=this.errors,t=this.retriesSubscription;e&&(e.unsubscribe(),this.errors=void 0),t&&(t.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},t.prototype.notifyNext=function(){var e=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=e,this.source.subscribe(this)},t}(Ra);function rc(){return new ia}function nc(){return function(e){return aa()((t=rc,function(e){var n;if(n="function"==typeof t?t:function(){return t},"function"==typeof r)return e.lift(new Ju(n,r));var i=Object.create(e,la);return i.source=e,i.subjectFactory=n,i})(e));var t,r}}function ic(e,t){return"function"==typeof t?function(r){return r.pipe(ic((function(r,n){return Na(e(r,n)).pipe(ja((function(e,i){return t(r,e,n,i)})))})))}:function(t){return t.lift(new oc(e))}}var oc=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new ac(e,this.project))},e}(),ac=function(e){function t(t,r){var n=e.call(this,t)||this;return n.project=r,n.index=0,n}return Vo(t,e),t.prototype._next=function(e){var t,r=this.index++;try{t=this.project(e,r)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var r=new Va(this),n=this.destination;n.add(r),this.innerSubscription=Ua(e,r),this.innerSubscription!==r&&n.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(Ra);function sc(e,t,r){return function(n){return n.lift(new uc(e,t,r))}}var uc=function(){function e(e,t,r){this.nextOrObserver=e,this.error=t,this.complete=r}return e.prototype.call=function(e,t){return t.subscribe(new cc(e,this.nextOrObserver,this.error,this.complete))},e}(),cc=function(e){function t(t,r,n,i){var o=e.call(this,t)||this;return o._tapNext=Oa,o._tapError=Oa,o._tapComplete=Oa,o._tapError=n||Oa,o._tapComplete=i||Oa,Ro(r)?(o._context=o,o._tapNext=r):r&&(o._context=r,o._tapNext=r.next||Oa,o._tapError=r.error||Oa,o._tapComplete=r.complete||Oa),o}return Vo(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(qo); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -class fc{all=new Map;constructor(e={},t=null){this.bindThis=t||globalThis,this.on(e),this.createSource$=pu((e=>La((t=>this.on(e,t)),(t=>this.off(e,t))).pipe(ic())))}#on(e,t){const n=this.all.get(e);n?n.unshift(t):this.all.set(e,[t])}on(e,t){"string"==typeof e?this.#on(e,t):e instanceof Object&&Object.entries(e).forEach((([e,t])=>{t instanceof Array?t.forEach((t=>this.#on(e,t))):t instanceof Function&&this.#on(e,t)}))}off(e,t){if("*"===e)return this.all.clear();{const n=this.all.get(e);return!!n&&(t?n.splice(n.indexOf(t)>>>0,1):this.all.set(e,[]))}}emit(e,...t){const n=this.all.get(e);return n?n.map((e=>e.apply(this.bindThis,t))):[]}}class pc{_belongTo=null;constructor(e,t){this.$EventHub=new fc({},this),this.$store=Do({spiderUUID:t,originData:e})}$commit(e,...t){const n=this.$store[e](...t);return this.$EventHub.emit(e,...t),n}$on(...e){return this.$EventHub.on(...e)}$off(...e){return this.$EventHub.off(...e)}$isSameTask(e){return e.$store.spiderUUID===this.$store.spiderUUID&&e.$store.uuid===this.$store.uuid}$destroy(){this._belongTo=null,this.$commit("destroy"),this.$EventHub.off("*")}get[Symbol.toStringTag](){return"Task"}} +class lc{all=new Map;constructor(e={},t=null){this.bindThis=t||globalThis,this.on(e),this.createSource$=pu((e=>La((t=>this.on(e,t)),(t=>this.off(e,t))).pipe(nc())))}#on(e,t){const r=this.all.get(e);r?r.unshift(t):this.all.set(e,[t])}on(e,t){"string"==typeof e?this.#on(e,t):e instanceof Object&&Object.entries(e).forEach((([e,t])=>{t instanceof Array?t.forEach((t=>this.#on(e,t))):t instanceof Function&&this.#on(e,t)}))}off(e,t){if("*"===e)return this.all.clear();{const r=this.all.get(e);return!!r&&(t?r.splice(r.indexOf(t)>>>0,1):this.all.set(e,[]))}}emit(e,...t){const r=this.all.get(e);return r?r.map((e=>e.apply(this.bindThis,t))):[]}}class fc{_belongTo=null;constructor(e,t){this.$EventHub=new lc({},this),this.$store=Do({spiderUUID:t,originData:e})}$commit(e,...t){const r=this.$store[e](...t);return this.$EventHub.emit(e,...t),r}$on(...e){return this.$EventHub.on(...e)}$off(...e){return this.$EventHub.off(...e)}$isSameTask(e){return e.$store.spiderUUID===this.$store.spiderUUID&&e.$store.uuid===this.$store.uuid}$destroy(){this._belongTo=null,this.$commit("destroy"),this.$EventHub.off("*")}get[Symbol.toStringTag](){return"Task"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class hc extends pc{constructor(e,t="00000"){super(new Set(e),e?.[0]?._spiderUUID||t),this.#linkTask()}#linkTask(){this._originData.forEach((e=>{e._belongTo=this,e.$on("destroy",(()=>this.$removeLink(e)))}))}$commit(e,...t){const n=[];this._originData.forEach((r=>n.push(r.$commit(e,...t))));const r=this.$EventHub.emit(e,...t);return"start"===e&&this._output?r[0]:n}$destroy(){const e=[...this._originData];return this.$EventHub.emit("destroy"),e}$removeLink(e){this._originData.delete(e)}get[Symbol.toStringTag](){return"TaskGroup"}} + */class pc extends fc{constructor(e,t="00000"){super({},e?.[0]?.spiderUUID||t),this.member=new Set(e),this.#linkTask()}#linkTask(){this.member.forEach((e=>{e._belongTo=this,e.$on("destroy",(()=>this.$removeLink(e)))}))}consume=!1;$commit(e,...t){const r=[];return this.member.forEach((n=>r.push(n.$commit(e,...t)))),this.$EventHub.emit(e,...t),this.consume?r[0]:("start"===e&&(this.consume=!0),r)}$destroy(){this.$EventHub.emit("destroy"),this.$store.destroy();const e=this.member;return this.member=null,e}$removeLink(e){this.member.delete(e)}get[Symbol.toStringTag](){return"TaskGroup"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const bc=new fc,dc=bc.createSource$("TaskUpdate"),vc=bc.createSource$("ControlUpdate"); + */const hc=new lc,bc=hc.createSource$("TaskUpdate"),dc=hc.createSource$("ControlUpdate"); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var yc={stateChange(e){this.status=e,bc.emit("ControlUpdate",{name:"stateChange",value:e})},"Flow:stop"(){this._stop=!0,bc.emit("ControlUpdate",{name:"flowStop"})},"Flow:start"(){console.log("jspider 开始运行"),this.status="pending",this._stop=!1,bc.emit("ControlUpdate",{name:"flowStart"})},"Task:success"(e){e.$commit("complete"),e instanceof hc&&e.$destroy(),bc.emit("ControlUpdate",{name:"TaskSuccess"})},"Task:error"(e){console.log(e)}}; +var vc={stateChange(e){this.status=e,hc.emit("ControlUpdate",{name:"stateChange",value:e})},"Flow:stop"(){this._stop=!0,hc.emit("ControlUpdate",{name:"flowStop"})},"Flow:start"(){console.log("jspider 开始运行"),this.status="pending",this._stop=!1,hc.emit("ControlUpdate",{name:"flowStart"})},"Task:success"(e){e.$commit("complete"),e instanceof pc&&e.$destroy(),hc.emit("ControlUpdate",{name:"TaskSuccess"})},"Task:error"(e){console.log(e)}}; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */function gc(){const e=this.$store.$backup();bc.emit("TaskUpdate",e)}class mc{#Tasks=new Map;viewModel=[];createTask(e,t){const n=new pc(e,t);this.#Tasks.set(n.uuid,n);const r=this;return n.$on({start:gc,success:gc,complete:gc,error:gc,destroy(){r.#Tasks.delete(this.uuid)}}),this.viewModel.push(n.$store),n}} + */function yc(){const e=this.$store.$backup();hc.emit("TaskUpdate",e)}class gc{#Tasks=new Map;viewModel=[];createTask(e,t){const r=new fc(e,t);this.#Tasks.set(r.uuid,r);const n=this;return r.$on({start:yc,success:yc,complete:yc,error:yc,destroy(){n.#Tasks.delete(this.uuid)}}),this.viewModel.push(r.$store),r}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class _c{QueuePromise=Promise.resolve();enQueue(...e){return this.QueuePromise=e.reduce(((e,t)=>e.then(t)),this.QueuePromise),this}} + */class mc{QueuePromise=Promise.resolve();enQueue(...e){return this.QueuePromise=e.reduce(((e,t)=>e.then(t)),this.QueuePromise),this}} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -285,12 +285,12 @@ var yc={stateChange(e){this.status=e,bc.emit("ControlUpdate",{name:"stateChange" * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -function wc(e){return To(e,To.URL)} +function _c(e){return To(e,To.URL)} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class Oc{constructor(e){this.Plugins=e}UUID=null;operator=null;pluginUUIDMap=new Map;#PluginQueue=new _c;preparePipeline(){let e="";const t=this.Plugins.map(((t,n)=>(e+=t.main.toString(),t.init instanceof Function&&this.#PluginQueue.enQueue(t.init),t.initUUID(n),this.pluginUUIDMap.set(t.uuid,t?.name||t.uuid),t.operator(this))));return this.operator=Xo(...t),this.UUID=wc(e),this.#PluginQueue.QueuePromise}} + */class wc{constructor(e){this.Plugins=e}UUID=null;operator=null;pluginUUIDMap=new Map;#PluginQueue=new mc;preparePipeline(){let e="";const t=this.Plugins.map(((t,r)=>(e+=(t?.main||t.operator).toString(),t.init instanceof Function&&this.#PluginQueue.enQueue(t.init),t.initUUID(r),this.pluginUUIDMap.set(t.uuid,t?.name||t.uuid),t.operator(this))));return this.operator=Xo(...t),this.UUID=_c(e),this.#PluginQueue.QueuePromise}} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -301,7 +301,7 @@ function wc(e){return To(e,To.URL)} * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var jc=new class{status="free";#runningQueue=new _c;_stop=!1;spiderSource$=null;_pipeline=null;TaskManager=new mc;constructor(){this.$EventHub=new fc(yc,this)}_createLogicLine(){var e,t;this.spiderSource$=this.$EventHub.createSource$("Flow:input").pipe((e=this.$EventHub.createSource$("Flow:stop"),t=this.$EventHub.createSource$("Flow:start"),n=>new Jo((r=>{const i=new Set;let o=!1;const a=n.subscribe((e=>{o?i.add(e):r.next(e)}),Oa,(()=>{i.forEach((e=>r.next(e))),r.complete()})),s=e.subscribe((()=>{o=t.subscribe((()=>{i.forEach((e=>r.next(e))),i.clear(),o.unsubscribe(),o=!1}))}));return()=>{i.clear(),a.unsubscribe(),s.unsubscribe(),o&&o.unsubscribe()}}))),this._pipeline.operator),this.spiderSource$.subscribe((e=>this.$EventHub.emit("Task:success",e)),(e=>this.$EventHub.emit("Task:error",e)),(()=>this.$EventHub.emit("Flow:complete"))),this.$EventHub.emit("Flow:stop")}pipeline(...e){const t=new Oc(e);if("free"!==this.status)throw new Error("在运行阶段是不能够进行操作的哦");this.$EventHub.emit("stateChange","preparing"),this._pipeline=t,this.#runningQueue.enQueue((()=>this._pipeline.preparePipeline()),(()=>{this.$EventHub.emit("Spider:clearFlow"),this._createLogicLine(),this.$EventHub.emit("stateChange","free")}))}createFlow(e,{fromBackup:t=!1}={}){return this.#runningQueue.enQueue((()=>{e.forEach((e=>{if(!this._pipeline)throw new Error("没有创建pipeline");const n=this.TaskManager.createTask(e,this._pipeline.UUID);t&&n.$store.$import(e),this.$EventHub.emit("Flow:input",n)}))}))}startFlow(){this.#runningQueue.enQueue((()=>{this.$EventHub.emit("Flow:start")}))}stopFlow(){this.$EventHub.emit("Flow:stop")}};class Pc extends class{constructor({tasks:e=!1,controlPanel:t=!1}={}){this.config={tasks:e,controlPanel:t},e&&this.#subscriber.push(dc.subscribe((e=>this._update(e)))),t&&this.#subscriber.push(vc.subscribe((e=>this._change(e))))}config={};#subscriber=[];$destroy(){this.#subscriber.forEach((e=>{e.unsubscribe()}))}}{constructor(e){super(Object.assign(e,{tasks:!0,controlPanel:!0}))}tasks=[];#uuidArray=[];_update(e){const t=this.#uuidArray.indexOf(e.uuid);-1===t?(this.#uuidArray.push(e.uuid),this.tasks.push(e)):this.tasks.splice(t,1,e)}_change({name:e,value:t=""}){}} +var Oc=new class{status="free";#runningQueue=new mc;_stop=!1;spiderSource$=null;_pipeline=null;TaskManager=new gc;constructor(){this.$EventHub=new lc(vc,this)}_createLogicLine(){var e,t;this.spiderSource$=this.$EventHub.createSource$("Flow:input").pipe((e=this.$EventHub.createSource$("Flow:stop"),t=this.$EventHub.createSource$("Flow:start"),r=>new Jo((n=>{const i=new Set;let o=!1;const a=r.subscribe((e=>{o?i.add(e):n.next(e)}),Oa,(()=>{i.forEach((e=>n.next(e))),i.clear(),n.complete()})),s=e.subscribe((()=>{o=t.subscribe((()=>{i.forEach((e=>n.next(e))),i.clear(),o.unsubscribe(),o=!1}))}));return()=>{i.clear(),a.unsubscribe(),s.unsubscribe(),o&&o.unsubscribe()}}))),this._pipeline.operator),this.spiderSource$.subscribe((e=>this.$EventHub.emit("Task:success",e)),(e=>this.$EventHub.emit("Task:error",e)),(()=>this.$EventHub.emit("Flow:complete"))),this.$EventHub.emit("Flow:stop")}pipeline(...e){const t=new wc(e);if("free"!==this.status)throw new Error("在运行阶段是不能够进行操作的哦");this.$EventHub.emit("stateChange","preparing"),this._pipeline=t,this.#runningQueue.enQueue((()=>this._pipeline.preparePipeline()),(()=>{this.$EventHub.emit("Spider:clearFlow"),this._createLogicLine(),this.$EventHub.emit("stateChange","free")}))}createFlow(e,{fromBackup:t=!1}={}){return this.#runningQueue.enQueue((()=>{e.forEach((e=>{if(!this._pipeline)throw new Error("没有创建pipeline");const r=this.TaskManager.createTask(e,this._pipeline.UUID);t&&r.$store.$import(e),this.$EventHub.emit("Flow:input",r)}))}))}startFlow(){this.#runningQueue.enQueue((()=>{this.$EventHub.emit("Flow:start")}))}stopFlow(){this.$EventHub.emit("Flow:stop")}};class jc extends class{constructor({tasks:e=!1,controlPanel:t=!1}={}){this.config={tasks:e,controlPanel:t},e&&this.#subscriber.push(bc.subscribe((e=>this._update(e)))),t&&this.#subscriber.push(dc.subscribe((e=>this._change(e))))}config={};#subscriber=[];$destroy(){this.#subscriber.forEach((e=>{e.unsubscribe()}))}}{constructor(e){super(Object.assign(e,{tasks:!0,controlPanel:!0}))}tasks=[];#uuidArray=[];_update(e){const t=this.#uuidArray.indexOf(e.uuid);-1===t?(this.#uuidArray.push(e.uuid),this.tasks.push(e)):this.tasks.splice(t,1,e)}_change({name:e,value:t=""}){}} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -312,28 +312,27 @@ var jc=new class{status="free";#runningQueue=new _c;_stop=!1;spiderSource$=null; * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -class Sc extends Error{constructor(e){super(e),this.name="PluginError"}}class Ac extends Error{constructor(e){super(e),this.name="FlowError"}} +class Pc extends Error{constructor(e){super(e),this.name="PluginError"}}class Sc extends Error{constructor(e){super(e),this.name="FlowError"}} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class xc{constructor({forceRetry:e=!0,saveResult:t=!1,name:n=null,main:r,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:n,main:r,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=wc(this.main.toString()+e)}TaskStarter(e){return _a(e).pipe(oc((e=>_a(e).pipe(ja((e=>[e.$commit("start",this.uuid),e._originData])),oc((([e,t])=>{const n=this.main(e,t);return n instanceof Promise||n instanceof Jo?Na(n):_a(n)})),ja((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),Hu(((...t)=>{if(this.error instanceof Function){const n=this.error(e,...t);if(n)throw new Sc(n);return da}throw new Sc(t[0])})),uc((e=>this.complete&&this.complete(e))))}operator(e){return Xo(oc((e=>this.TaskStarter(e))))}}function Ec(e,t={}){if(e instanceof Function)return new xc(Object.assign(t,{main:e}));if(e instanceof Object)return new xc(e);throw new Sc("Plugin 必须是一个函数或者是 Plugin 描述对象")} + */class Ac{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=_c((this?.main||this.operator).toString()+e)}TaskStarter(e){return _a(e).pipe(ic((e=>_a(e).pipe(ja((e=>[e.$commit("start",this.uuid),e._originData])),ic((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Jo?Na(r):_a(r)})),ja((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),$u(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new Pc(r);return da}throw new Pc(t[0])})),sc((e=>this.complete&&this.complete(e))))}operator(e){return Xo(ic((e=>this.TaskStarter(e))))}}function xc(e,t={}){if(e instanceof Function)return new Ac(Object.assign(t,{main:e}));if(e instanceof Object)return new Ac(e);throw new Pc("Plugin 必须是一个函数或者是 Plugin 描述对象")} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const Tc=(e,t)=>{return Xo((n=n=>n.pipe(function(e,t){var n=!1;return arguments.length>=2&&(n=!0),function(r){return r.lift(new Zu(e,t,n))}}(((t,n)=>{if(console.log("尝试次数",t,n),t>=e)throw new Ac("超出尝试次数",n);return t+1}),0),qu(((...e)=>{switch(typeof t){case"string":case"number":return Ka(parseInt(t,10));case"function":return Ka(t(...e));default:throw new Ac("您输入的 delay 错误")}}))),function(e){return e.lift(new tc(n,e))})); + */const Ec=(e,t)=>{return Xo((r=r=>r.pipe(function(e,t){var r=!1;return arguments.length>=2&&(r=!0),function(n){return n.lift(new Xu(e,t,r))}}(((t,r)=>{if(console.log("尝试次数",t,r),t>=e)throw new Sc("超出尝试次数",r);return t+1}),0),Ku(((...e)=>{switch(typeof t){case"string":case"number":return Ka(parseInt(t,10));case"function":return Ka(t(...e));default:throw new Sc("您输入的 delay 错误")}}))),function(e){return e.lift(new ec(r,e))})); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */var n};function Ic({url:e,options:t={}}){const{returnType:n="json"}=this.options;return console.log("- 爬取 ",e),fetch(e,t).then((e=>{if(!e.ok)throw Error(e.statusText); + */var r};function Tc(e,{retry:t=3,buffer:r=3,delay:n=1e3,retryDelay:i=300,handleError:o=function(e,t){throw new Error(e,t)}}={}){return Xo(function(e){var t=arguments.length,r=wa;va(arguments[arguments.length-1])&&(r=arguments[arguments.length-1],t--);var n=null;t>=2&&(n=arguments[1]);var i=Number.POSITIVE_INFINITY;return t>=3&&(i=arguments[2]),function(t){return t.lift(new Ru(e,n,i,r))}}(1e3,void 0,r),Ha((e=>e.length)),Ku(((e,t)=>Ka(t*n))),Ma((e=>Na(e))),Gu((r=>_a(r).pipe(Ma((t=>e(t))),Ec(t,i),$u(((...e)=>(o instanceof Function?o(...e):o)||da))))))} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */ -return function(e,t){const n=e.headers.get("content-type")||"";return t&&"auto"!==t?t?e[t]():e.json():/text|html|rtf|xml/.test(n)?e.text():/json/.test(n)?e.json():/arrayBuffer/.test(n)?e.arrayBuffer():e.buffer?e.buffer():e.blob()}(e,n)})).then((t=>(console.log(`${e} 爬取成功`),t))).catch((e=>{throw e}))}function Cc(e){throw e} + */function Ic({url:e,options:t={}}){const{returnType:r="json"}=this.options;return console.log("- 爬取 ",e),fetch(e,Object.assign({cache:"force-cache"},t)).then((e=>{if(!e.ok)throw Error(e.statusText);return function(e,t){const r=e.headers.get("content-type")||"";return t&&"auto"!==t?t?e[t]():e.json():/text|html|rtf|xml/.test(r)?e.text():/json/.test(r)?e.json():/arrayBuffer/.test(r)?e.arrayBuffer():e.buffer?e.buffer():e.blob()}(e,r)})).then((t=>(console.log(`${e} 爬取成功`),t))).catch((e=>{throw e}))}function Cc(e){throw e} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -344,7 +343,7 @@ function kc(e,t){return e instanceof File?e:e instanceof Blob?(e.name=t,e):new F * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const Dc={main:Promise.resolve(!0),add(e){this.main.then((()=>Nc(e)))}},Nc=function(e){const t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=e.name,t.click(),URL.revokeObjectURL(t.href),t.remove(),console.log("%c 下载完成","color:green")},Vc=(e,{DownloadFileName:t},n)=>{const r=kc(e,t||("string"==typeof url?n.url.replace(/[^\/]*?\//g,""):""));return Dc.add(r),null},Rc={script:e=>new Promise(((t,n)=>{const r=document.createElement("script");r.src=e,r.onload=()=>{console.log(`${e} 加载完成`),r.remove(),t()},r.onerror=e=>n(e),document.body.append(r)})),css:e=>new Promise(((t,n)=>{const r=document.createElement("style");r.rel="stylesheet",r.src=e,r.onload=()=>{console.log(`${e} 加载完成`),t()},r.onerror=e=>n(e),document.body.append(r)}))}; + */const Dc={main:Promise.resolve(!0),add(e){this.main.then((()=>Nc(e)))}},Nc=function(e){const t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=e.name,t.click(),URL.revokeObjectURL(t.href),t.remove(),console.log("%c 下载完成","color:green")},Vc=(e,{DownloadFileName:t}={},r)=>{const n=kc(e,t||("string"==typeof url?r.url.replace(/[^\/]*?\//g,""):""));return Dc.add(n),null},Rc={script:e=>new Promise(((t,r)=>{const n=document.createElement("script");n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),n.remove(),t()},n.onerror=e=>r(e),document.body.append(n)})),css:e=>new Promise(((t,r)=>{const n=document.createElement("style");n.rel="stylesheet",n.src=e,n.onload=()=>{console.log(`${e} 加载完成`),t()},n.onerror=e=>r(e),document.body.append(n)}))}; /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -355,17 +354,17 @@ var Uc={zangodb:"https://cdn.jsdelivr.net/gh/erikolson186/zangodb/dist/zangodb.m * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const Mc=Object.entries({npm:/^npm?/i,gh:/gh?|github/i,wp:/wordpress|wp/i});function Fc(e,{version:t="",store:n="npm",path:r=""}={}){return`https://cdn.jsdelivr.net/${Mc.reduce(((e,[t,r])=>r.test(n)?t:e),"npm")}/${e}${t?`@${t}`:""}${r?`/${r}`:""}`} + */const Mc=Object.entries({npm:/^npm?/i,gh:/gh?|github/i,wp:/wordpress|wp/i});function zc(e,{version:t="",store:r="npm",path:n=""}={}){return`https://cdn.jsdelivr.net/${Mc.reduce(((e,[t,n])=>n.test(r)?t:e),"npm")}/${e}${t?`@${t}`:""}${n?`/${n}`:""}`} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */function zc(e){return Object.prototype.toString.call(e).match(/(?<=\[object\s+)\S+?(?=\])/)[0]} + */function Fc(e){return Object.prototype.toString.call(e).match(/(?<=\[object\s+)\S+?(?=\])/)[0]} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const Lc=/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;const $c={Object({url:e="",name:t,way:n="npm",path:r="",version:i="",type:o="script"}){if(!e){const o=function({name:e,way:t,path:n,version:r}){return Uc.hasOwnProperty(e)?Uc[e]:Fc(e,{version:r,store:t,path:n})}({name:t,way:n,path:r,version:i});if("string"!=typeof o)return Hc(o);e=o}return Rc[o](e)},String(e){return this.Object({[Lc.test(e)?"url":"name"]:e})},Array:e=>Promise.all(e.map((e=>Hc(e))))};async function Hc(e){return $c[zc(e)](e)} + */const Lc=/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;const $c={Object({url:e="",name:t,way:r="npm",path:n="",version:i="",type:o="script"}){if(!e){const o=function({name:e,way:t,path:r,version:n}){return Uc.hasOwnProperty(e)?Uc[e]:zc(e,{version:n,store:t,path:r})}({name:t,way:r,path:n,version:i});if("string"!=typeof o)return Hc(o);e=o}return Rc[o](e)},String(e){return this.Object({[Lc.test(e)?"url":"name"]:e})},Array:e=>Promise.all(e.map((e=>Hc(e))))};async function Hc(e){return $c[Fc(e)](e)} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -375,7 +374,7 @@ var Uc={zangodb:"https://cdn.jsdelivr.net/gh/erikolson186/zangodb/dist/zangodb.m * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */function Kc(e){const t=Bc.utils.book_new();return Object.entries(e).forEach((([e,n])=>{const r=function(e){return e.forEach((e=>{Object.entries(e).forEach((([t,n])=>{n instanceof Object&&(e[t]=JSON.stringify(n))}))})),Bc.utils.json_to_sheet(e)}(n);Bc.utils.book_append_sheet(t,r,e)})),t}function qc(e,t,n){const{bookType:r="xlsx",bookSST:i=!0,type:o="array"}=n||{};return function(e,t,n){const r=Bc.write(e,n);return new File([r],`${t}.${n.bookType}`)}(Kc(e),t,{bookType:r,bookSST:i,type:o})} + */function Kc(e){const t=Bc.utils.book_new();return Object.entries(e).forEach((([e,r])=>{const n=function(e){return e.forEach((e=>{Object.entries(e).forEach((([t,r])=>{r instanceof Object&&(e[t]=JSON.stringify(r))}))})),Bc.utils.json_to_sheet(e)}(r);Bc.utils.book_append_sheet(t,n,e)})),t}function qc(e,t,r){const{bookType:n="xlsx",bookSST:i=!0,type:o="array"}=r||{};return function(e,t,r){const n=Bc.write(e,r);return new File([n],`${t}.${r.bookType}`)}(Kc(e),t,{bookType:n,bookSST:i,type:o})} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -397,7 +396,7 @@ let Wc;function Yc(){return Hc("jszip").then((()=>{Wc=window.JSZip}))} * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -class Xc extends pc{constructor(e,t="00000"){super(new Set(e),e?.[0]?._spiderUUID||t),this.#linkTask()}#linkTask(){this._originData.forEach((e=>{e._belongTo=this,e.$on("destroy",(()=>this.$removeLink(e)))}))}$commit(e,...t){const n=[];this._originData.forEach((r=>n.push(r.$commit(e,...t))));const r=this.$EventHub.emit(e,...t);return"start"===e&&this._output?r[0]:n}$destroy(){const e=[...this._originData];return this.$EventHub.emit("destroy"),e}$removeLink(e){this._originData.delete(e)}get[Symbol.toStringTag](){return"TaskGroup"}} +function Xc(e=3,t=1e3){return r=>new Jo((n=>{const i=new Set;let o=0;const a=()=>{i.size&&(n.next([...i]),i.clear())},s=r.subscribe((r=>{switch(console.log(o),o&&(clearTimeout(o),o=0),i.size){case 0:return i.add(r);case e-1:return i.add(r),a();default:return o=setTimeout(a,t),i.add(r)}}),Oa,(()=>{a(),n.complete()}));return()=>{i.clear(),s.unsubscribe()}}))} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -408,7 +407,12 @@ class Xc extends pc{constructor(e,t="00000"){super(new Set(e),e?.[0]?._spiderUUI * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var Zc=Object.freeze({__proto__:null,Request:function(e={}){return Ec({init(){},name:"Request",main:Ic,options:e,operator(){const{delay:e=200,buffer:t=3,retry:n=3,handleError:r=null}=this.options;return i=>i.pipe(function(e,{retry:t=3,buffer:n=3,delay:r=1e3,retryDelay:i=300,handleError:o=function(e,t){throw new Error(e,t)}}={}){return Xo(Ru(1e3,void 0,n),Ha((e=>e.length)),qu(((e,t)=>Ka(t*r))),Ma((e=>Na(e))),Ku((n=>_a(n).pipe(Ma((t=>e(t))),Tc(t,i),Hu(((...e)=>(o instanceof Function?o(...e):o)||da))))))}((e=>this.TaskStarter(e)),{delay:e,buffer:t,retry:n,handleError:r||Cc}))}})},Download:function(e={}){return Ec({name:"Download",main:Vc,options:e})},ExcelHelper:function(e,t={}){return Ec({name:"ExcelHelper",init:Gc,options:t,main(t){const{fileName:n="result",XLSXOptions:r={}}=this.options;return e instanceof Function&&(t=e(t)),qc(t,`${n}-${(new Date).getTime()}`,r)}})},ZipFile:function(e={}){return e.zipFileName||(e.zipFileName=(new Date).getTime()),Ec({init:Yc,name:"zipFile",main(e){const{zipFileName:t}=this.options;return async function(e,t){const n=new Wc;e.forEach((e=>n.file(e.name,e)));const r=await n.generateAsync({type:"blob"});return r.name=`${t}-${Qc++}.zip`,r}(e.map((e=>kc(e,t))),t)},options:e,operator(){const{chunk:e=3}=this.options;return t=>t.pipe(Ru(5e3,void 0,e),Ha((e=>e.length)),Ku((e=>this.TaskStarter(new Xc(e),this.uuid))))}})}}); +var Zc=Object.freeze({__proto__:null,Request:function(e={}){return xc({init(){},name:"Request",main:Ic,options:e,operator(){const{delay:e=200,buffer:t=1,retry:r=3,handleError:n=null}=this.options;return i=>i.pipe(Tc((e=>this.TaskStarter(e)),{delay:e,buffer:t,retry:r,handleError:n||Cc}))}})},Download:function(e={}){return xc({name:"Download",main:Vc,options:e})},ExcelHelper:function(e,t={}){return xc({name:"ExcelHelper",init:Gc,options:t,main(t){const{fileName:r="result",XLSXOptions:n={}}=this.options;return e instanceof Function&&(t=e(t)),qc(t,`${r}-${(new Date).getTime()}`,n)}})},ZipFile:function(e={}){return e.zipFileName||(e.zipFileName=(new Date).getTime()),xc({init:Yc,name:"zipFile",main(e){const{zipFileName:t}=this.options;return async function(e,t){const r=new Wc;e.forEach((e=>r.file(e.name,e)));const n=await r.generateAsync({type:"blob"});return n.name=`${t}-${Qc++}.zip`,n} +/** + * @license + * Copyright 2021 KonghaYao 江夏尧 + * SPDX-License-Identifier: Apache-2.0 + */(kc(e,t),t)},options:e})},Combine:function(e,t=1e3,r){return xc({name:"Combine",main:r,operator(){return n=>n.pipe(Xc(e,t),Ha((e=>e.length)),Gu((e=>{const t=_a(new pc(e));return r instanceof Function?t.pipe(Gu((e=>this.TaskStarter(e)))):t})))}})},Break:function(){return xc({name:"Break",options:options,operator:()=>e=>e.pipe(Gu((e=>e instanceof pc?from(e.$destroy()):_a(e))))})}}); /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -424,13 +428,13 @@ var Zc=Object.freeze({__proto__:null,Request:function(e={}){return Ec({init(){}, * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -const el={RE:"",StringFunction(e,t,n,r){return this.RE.test(`${n}`)&&e.push(r),e},Array(e,t,n){const r=tl(Object.entries(n),this.RE),i=r.reduce(((e,[t,n])=>(e[parseInt(t)]=n,e)),[]);return r.length&&e.push([t,i]),e},Function(e,t,n){const r=tl(Object.entries(n),this.RE);return r.length&&e.push([t,Object.assign(n,Object.fromEntries(r))]),e},Object(e,t,n){const r=tl(Object.entries(n),this.RE);return r.length&&e.push([t,Object.fromEntries(r)]),e}};function tl(e,t,n=!1){return e.reduce(((e,r)=>{const[i,o]=r;if(t.test(i))return[...e,r];el.RE=t;const a=(s=o,Object.prototype.toString.call(s).match(/(?<=\[object\s+)\S+?(?=\])/)[0]); +const el={RE:"",StringFunction(e,t,r,n){return this.RE.test(`${r}`)&&e.push(n),e},Array(e,t,r){const n=tl(Object.entries(r),this.RE),i=n.reduce(((e,[t,r])=>(e[parseInt(t)]=r,e)),[]);return n.length&&e.push([t,i]),e},Function(e,t,r){const n=tl(Object.entries(r),this.RE);return n.length&&e.push([t,Object.assign(r,Object.fromEntries(n))]),e},Object(e,t,r){const n=tl(Object.entries(r),this.RE);return n.length&&e.push([t,Object.fromEntries(n)]),e}};function tl(e,t,r=!1){return e.reduce(((e,n)=>{const[i,o]=n;if(t.test(i))return[...e,n];el.RE=t;const a=(s=o,Object.prototype.toString.call(s).match(/(?<=\[object\s+)\S+?(?=\])/)[0]); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -var s;return el.hasOwnProperty(a)?el[a](e,i,o,r):n?[e,r]:e}),[])} +var s;return el.hasOwnProperty(a)?el[a](e,i,o,n):r?[e,n]:e}),[])} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -441,7 +445,7 @@ var s;return el.hasOwnProperty(a)?el[a](e,i,o,r):n?[e,r]:e}),[])} * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 */ -const nl=/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;const rl={Object({url:e="",name:t,way:n="npm",path:r="",version:i="",type:o="script"}){if(!e){const o=function({name:e,way:t,path:n,version:r}){return Uc.hasOwnProperty(e)?Uc[e]:Fc(e,{version:r,store:t,path:n})}({name:t,way:n,path:r,version:i});if("string"!=typeof o)return il(o);e=o}return Rc[o](e)},String(e){return this.Object({[nl.test(e)?"url":"name"]:e})},Array:e=>Promise.all(e.map((e=>il(e))))};async function il(e){return rl[zc(e)](e)} +const rl=/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;const nl={Object({url:e="",name:t,way:r="npm",path:n="",version:i="",type:o="script"}){if(!e){const o=function({name:e,way:t,path:r,version:n}){return Uc.hasOwnProperty(e)?Uc[e]:zc(e,{version:n,store:t,path:r})}({name:t,way:r,path:n,version:i});if("string"!=typeof o)return il(o);e=o}return Rc[o](e)},String(e){return this.Object({[rl.test(e)?"url":"name"]:e})},Array:e=>Promise.all(e.map((e=>il(e))))};async function il(e){return nl[Fc(e)](e)} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -457,12 +461,12 @@ const ol={excel:{url:"/fake/excel",type:"get",template:{"data|100":[{ID:"@increm * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */const al=pu((async function(e){window.Mock||(await il("mockjs"),console.warn("Mockjs 载入并代理 Ajax 中")),console.warn("mock 启动后台 ",e);const{url:t,type:n,template:r}=ol[e];return window.Mock.mock(t,n,r),!0})),sl=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","hash"],ul={strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}; + */const al=pu((async function(e){window.Mock||(await il("mockjs"),console.warn("Mockjs 载入并代理 Ajax 中")),console.warn("mock 启动后台 ",e);const{url:t,type:r,template:n}=ol[e];return window.Mock.mock(t,r,n),!0})),sl=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","hash"],ul={strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}; /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */function cl(e,t=!1){const n=ul[t?"strict":"loose"].exec(decodeURI(e)),r=sl.reduce(((e,t,r)=>(e[t]=n[r]||"",e)),{});var i;return r.queryParams=(i=r.query,String(i).split(/&|;/).reduce((function(e,t){try{t=decodeURIComponent(t.replace(/\+/g," "))}catch(e){}const[n,r]=t.split(/=/g);return e[n]=r,e}),{})),r.base=r.host?(r.protocol?r.protocol+"://"+r.host:r.host)+(r.port?":"+r.port:""):"",r} + */function cl(e,t=!1){const r=ul[t?"strict":"loose"].exec(decodeURI(e)),n=sl.reduce(((e,t,n)=>(e[t]=r[n]||"",e)),{});var i;return n.queryParams=(i=n.query,String(i).split(/&|;/).reduce((function(e,t){try{t=decodeURIComponent(t.replace(/\+/g," "))}catch(e){}const[r,n]=t.split(/=/g);return e[r]=n,e}),{})),n.base=n.host?(n.protocol?n.protocol+"://"+n.host:n.host)+(n.port?":"+n.port:""):"",n} /** * @license * Copyright 2021 KonghaYao 江夏尧 @@ -473,14 +477,14 @@ var ll=Object.freeze({__proto__:null,$antiDebugger:function(){Function.prototype * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */,$copy:function(e,t=!1){t&&([document,...document.querySelectorAll("*")].forEach((e=>{e.oncontextmenu="",e.oncopy="",e.oncut="",e.onselectstart=!0;const t=window.getEventListeners(e);["keydown","copy","cut"].forEach((n=>{t.hasOwnProperty(n)&&t[n].forEach((t=>e.removeEventListener(n,t.listener)))}))})),console.log("copy 方式清理完成")),window.copy&&"function copy(value) { [Command Line API] }"===window.copy.toString()||delete window.copy,window.copy(e),console.log("copy 完成,请您查看您的剪贴版")},$GlobalVars:function(){const e=Iu(Object.keys(window),Jc);return Vu(window,e)},$search:function(e,t){var n;if(!ku(t)&&("string"==typeof(n=t)||!us(n)&&os(n)&&"[object String]"==is(n))&&(t=new RegExp(t)),e instanceof Array)return tl(Object.entries({i:e}),t)[0][1];if(e instanceof Object)return Object.fromEntries(tl(Object.entries(e),t));throw new Error("不是对象,不能搜索")},$load:il,$Mock:al,parseURL:function(e,t=!1){return cl(e,t)}}); + */,$copy:function(e,t=!1){t&&([document,...document.querySelectorAll("*")].forEach((e=>{e.oncontextmenu="",e.oncopy="",e.oncut="",e.onselectstart=!0;const t=window.getEventListeners(e);["keydown","copy","cut"].forEach((r=>{t.hasOwnProperty(r)&&t[r].forEach((t=>e.removeEventListener(r,t.listener)))}))})),console.log("copy 方式清理完成")),window.copy&&"function copy(value) { [Command Line API] }"===window.copy.toString()||delete window.copy,window.copy(e),console.log("copy 完成,请您查看您的剪贴版")},$GlobalVars:function(){const e=Iu(Object.keys(window),Jc);return Vu(window,e)},$search:function(e,t){var r;if(!ku(t)&&("string"==typeof(r=t)||!us(r)&&os(r)&&"[object String]"==is(r))&&(t=new RegExp(t)),e instanceof Array)return tl(Object.entries({i:e}),t)[0][1];if(e instanceof Object)return Object.fromEntries(tl(Object.entries(e),t));throw new Error("不是对象,不能搜索")},$load:il,$Mock:al,parseURL:function(e,t=!1){return cl(e,t)}}); /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */class fl{constructor({forceRetry:e=!0,saveResult:t=!1,name:n=null,main:r,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:n,main:r,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=wc(this.main.toString()+e)}TaskStarter(e){return _a(e).pipe(oc((e=>_a(e).pipe(ja((e=>[e.$commit("start",this.uuid),e._originData])),oc((([e,t])=>{const n=this.main(e,t);return n instanceof Promise||n instanceof Jo?Na(n):_a(n)})),ja((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),Hu(((...t)=>{if(this.error instanceof Function){const n=this.error(e,...t);if(n)throw new Sc(n);return da}throw new Sc(t[0])})),uc((e=>this.complete&&this.complete(e))))}operator(e){return Xo(oc((e=>this.TaskStarter(e))))}}return Object.assign(class{constructor({logEvery:e=!1}={}){this.config={logEvery:e},this.views=new Pc(this.config)}crawl(...e){return jc.createFlow(e.flat()),this}pipeline(...e){return jc.pipeline(...e),this}start(){return jc.startFlow(),this}stop(){return jc.stopFlow(),this}},ll,{plugins:Zc,Plugin:function(e,t={}){if(e instanceof Function)return new fl(Object.assign(t,{main:e}));if(e instanceof Object)return new fl(e);throw new Sc("Plugin 必须是一个函数或者是 Plugin 描述对象")} + */class fl{constructor({forceRetry:e=!0,saveResult:t=!1,name:r=null,main:n,init:i=null,error:o=null,complete:a=null,options:s={},operator:u}){u&&(this.operator=u),Object.assign(this,{name:r,main:n,init:i,error:o,complete:a,options:s,saveResult:t,forceRetry:e})}initUUID(e){this.uuid=_c((this?.main||this.operator).toString()+e)}TaskStarter(e){return _a(e).pipe(ic((e=>_a(e).pipe(ja((e=>[e.$commit("start",this.uuid),e._originData])),ic((([e,t])=>{const r=this.main(e,t);return r instanceof Promise||r instanceof Jo?Na(r):_a(r)})),ja((t=>(e.$commit("success",t,this.uuid,this.saveResult),e)))))),$u(((...t)=>{if(this.error instanceof Function){const r=this.error(e,...t);if(r)throw new Pc(r);return da}throw new Pc(t[0])})),sc((e=>this.complete&&this.complete(e))))}operator(e){return Xo(ic((e=>this.TaskStarter(e))))}}return Object.assign(class{constructor({logEvery:e=!1}={}){this.config={logEvery:e},this.views=new jc(this.config)}crawl(...e){return Oc.createFlow(e.flat()),this}pipeline(...e){return Oc.pipeline(...e),this}start(){return Oc.startFlow(),this}stop(){return Oc.stopFlow(),this}},ll,{plugins:Zc,Plugin:function(e,t={}){if(e instanceof Function)return new fl(Object.assign(t,{main:e}));if(e instanceof Object)return new fl(e);throw new Pc("Plugin 必须是一个函数或者是 Plugin 描述对象")} /** * @license * Copyright 2021 KonghaYao 江夏尧 * SPDX-License-Identifier: Apache-2.0 - */,Task:pc,TaskGroup:hc,version:"3.1.8",buildDate:new Date(1628300553915)})})); + */,Task:fc,TaskGroup:pc,version:"3.2.2",buildDate:new Date(1628382223946)})})); diff --git a/package/plugins/Combine.js b/package/plugins/Combine.js index 877ffe3..4f3d177 100644 --- a/package/plugins/Combine.js +++ b/package/plugins/Combine.js @@ -10,17 +10,23 @@ import { of } from 'rxjs'; import { concatMap, filter } from 'rxjs/operators'; import { TaskGroup } from '../../src/TaskSystem/TaskGroup'; import { BufferCountIn } from './utils/bufferCountIn'; -export function Combine(number, waitTime = 1000, options = {}) { +export function Combine(number, waitTime = 1000, combineFunction = undefined) { return Plugin({ name: 'Combine', // 这个 name 是负责进行监控的标志符号 - options, // 接收所有的参数,提供给所有函数使用 + main: combineFunction, operator() { // 复写 operator return (source) => source.pipe( BufferCountIn(number, waitTime), filter((i) => i.length), // 必须要进行检测是否为空 - concatMap((tasks) => of(new TaskGroup(tasks))), + concatMap((tasks) => { + const cb = of(new TaskGroup(tasks)); + if (combineFunction instanceof Function) { + return cb.pipe(concatMap((task) => this.TaskStarter(task))); + } + return cb; + }), ); }, }); diff --git a/package/plugins/utils/bufferCountIn.js b/package/plugins/utils/bufferCountIn.js index 6276850..ca61845 100644 --- a/package/plugins/utils/bufferCountIn.js +++ b/package/plugins/utils/bufferCountIn.js @@ -15,7 +15,10 @@ export function BufferCountIn(countNumber = 3, maxWaitTime = 1000) { // 发送所有的数据,并将定时器删除 const sendAll = () => { - if (buffers.size) buffers.forEach((item) => subscriber.next(item)); + if (buffers.size) { + subscriber.next([...buffers]); + buffers.clear(); + } }; // 删除定时器标记, 没有时忽略 const deleteTimeout = () => { @@ -24,27 +27,31 @@ export function BufferCountIn(countNumber = 3, maxWaitTime = 1000) { TimeOut = 0; } }; + const UpdateTimeout = () => { + TimeOut = setTimeout(sendAll, maxWaitTime); + }; const subscription = observable.subscribe( (value) => { + console.log(TimeOut); // buffer.size 为 0 时,不设置定时,但是收集; - // 1 时,收集并设置定时器; + // 2 时,发送并重置定时器 + // 其他 时,收集并设置定时器; deleteTimeout(); switch (buffers.size) { case 0: return buffers.add(value); - case countNumber - 2: - setTimeout(sendAll, maxWaitTime); - return buffers.add(value); + case countNumber - 1: + buffers.add(value); + return sendAll(); default: - sendAll(); - return subscriber.next(value); + UpdateTimeout(); + return buffers.add(value); } }, noop, () => { sendAll(); - buffers.clear(); subscriber.complete(); }, ); diff --git a/test/Request.js b/test/Request.js index 93dd291..789c8e8 100644 --- a/test/Request.js +++ b/test/Request.js @@ -22,26 +22,32 @@ export async function main() { spider.pipeline( Request({ delay: 100, buffer: 2, retry: 3, handleError: null }), - Combine(3, 1000), - ExcelHelper( - (data) => { - return { - [new Date().getTime()]: data - .map((i) => i.data) - .flat() - .flat() - .flat(), - }; - }, - { - XLSXOptions: { - bookType: 'csv', // 可以指定为 csv 或者 xlsx - }, - }, - ), + Combine(3, 1000, (array) => { + return array.map((i) => i.data).flat(); + }), + // Combine(3, 1000), 如果没有处理函数,则下一个 plugin 将会收到一个数组 + Plugin((data) => { + console.log('this', data); + }), + // ExcelHelper( + // (data) => { + // return { + // [new Date().getTime()]: data + // .map((i) => i.data) + // .flat() + // .flat() + // .flat(), + // }; + // }, + // { + // XLSXOptions: { + // bookType: 'csv', // 可以指定为 csv 或者 xlsx + // }, + // }, + // ), // ZipFile({ chunk: 2 }), - Download(), + // Download(), ); spider.crawl(urls); spider.start(); diff --git a/test/text-bilibili.js b/test/text-bilibili.js index 368b315..c944702 100644 --- a/test/text-bilibili.js +++ b/test/text-bilibili.js @@ -1,4 +1,4 @@ -import('https://cdn.jsdelivr.net/npm/js-spider@3.2.2/dist/JSpider.esm.min.js').then(async (res) => { +import('https://cdn.jsdelivr.net/npm/js-spider@3.2.3/dist/JSpider.esm.min.js').then(async (res) => { let JSpider = res.default; let { Plugin, @@ -33,9 +33,9 @@ import('https://cdn.jsdelivr.net/npm/js-spider@3.2.2/dist/JSpider.esm.min.js').t Request({ buffer: 1, }), - Combine(50, 5000), - Plugin((data) => { - return data + Combine(50, 1000, (dataArray) => { + return dataArray + .flat() .map((i) => { i.data.result.forEach((item) => { ['hit_columns', 'new_rec_tags'].forEach((ii) => (item[ii] = ''));