UNPKG

190 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var niceErrors = {
6 0: "Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'",
7 1: function _(annotationType, key) {
8 return "Cannot apply '" + annotationType + "' to '" + key.toString() + "': Field not found.";
9 },
10 /*
11 2(prop) {
12 return `invalid decorator for '${prop.toString()}'`
13 },
14 3(prop) {
15 return `Cannot decorate '${prop.toString()}': action can only be used on properties with a function value.`
16 },
17 4(prop) {
18 return `Cannot decorate '${prop.toString()}': computed can only be used on getter properties.`
19 },
20 */
21 5: "'keys()' can only be used on observable objects, arrays, sets and maps",
22 6: "'values()' can only be used on observable objects, arrays, sets and maps",
23 7: "'entries()' can only be used on observable objects, arrays and maps",
24 8: "'set()' can only be used on observable objects, arrays and maps",
25 9: "'remove()' can only be used on observable objects, arrays and maps",
26 10: "'has()' can only be used on observable objects, arrays and maps",
27 11: "'get()' can only be used on observable objects, arrays and maps",
28 12: "Invalid annotation",
29 13: "Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)",
30 14: "Intercept handlers should return nothing or a change object",
31 15: "Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)",
32 16: "Modification exception: the internal structure of an observable array was changed.",
33 17: function _(index, length) {
34 return "[mobx.array] Index out of bounds, " + index + " is larger than " + length;
35 },
36 18: "mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js",
37 19: function _(other) {
38 return "Cannot initialize from classes that inherit from Map: " + other.constructor.name;
39 },
40 20: function _(other) {
41 return "Cannot initialize map from " + other;
42 },
43 21: function _(dataStructure) {
44 return "Cannot convert to map from '" + dataStructure + "'";
45 },
46 22: "mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js",
47 23: "It is not possible to get index atoms from arrays",
48 24: function _(thing) {
49 return "Cannot obtain administration from " + thing;
50 },
51 25: function _(property, name) {
52 return "the entry '" + property + "' does not exist in the observable map '" + name + "'";
53 },
54 26: "please specify a property",
55 27: function _(property, name) {
56 return "no observable property '" + property.toString() + "' found on the observable object '" + name + "'";
57 },
58 28: function _(thing) {
59 return "Cannot obtain atom from " + thing;
60 },
61 29: "Expecting some object",
62 30: "invalid action stack. did you forget to finish an action?",
63 31: "missing option for computed: get",
64 32: function _(name, derivation) {
65 return "Cycle detected in computation " + name + ": " + derivation;
66 },
67 33: function _(name) {
68 return "The setter of computed value '" + name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?";
69 },
70 34: function _(name) {
71 return "[ComputedValue '" + name + "'] It is not possible to assign a new value to a computed value.";
72 },
73 35: "There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",
74 36: "isolateGlobalState should be called before MobX is running any reactions",
75 37: function _(method) {
76 return "[mobx] `observableArray." + method + "()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice()." + method + "()` instead";
77 },
78 38: "'ownKeys()' can only be used on observable objects",
79 39: "'defineProperty()' can only be used on observable objects"
80};
81var errors = niceErrors ;
82function die(error) {
83 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
84 args[_key - 1] = arguments[_key];
85 }
86 {
87 var e = typeof error === "string" ? error : errors[error];
88 if (typeof e === "function") e = e.apply(null, args);
89 throw new Error("[MobX] " + e);
90 }
91}
92
93var mockGlobal = {};
94function getGlobal() {
95 if (typeof globalThis !== "undefined") {
96 return globalThis;
97 }
98 if (typeof window !== "undefined") {
99 return window;
100 }
101 if (typeof global !== "undefined") {
102 return global;
103 }
104 if (typeof self !== "undefined") {
105 return self;
106 }
107 return mockGlobal;
108}
109
110// We shorten anything used > 5 times
111var assign = Object.assign;
112var getDescriptor = Object.getOwnPropertyDescriptor;
113var defineProperty = Object.defineProperty;
114var objectPrototype = Object.prototype;
115var EMPTY_ARRAY = [];
116Object.freeze(EMPTY_ARRAY);
117var EMPTY_OBJECT = {};
118Object.freeze(EMPTY_OBJECT);
119var hasProxy = typeof Proxy !== "undefined";
120var plainObjectString = /*#__PURE__*/Object.toString();
121function assertProxies() {
122 if (!hasProxy) {
123 die( "`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`" );
124 }
125}
126function warnAboutProxyRequirement(msg) {
127 if ( globalState.verifyProxies) {
128 die("MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to " + msg);
129 }
130}
131function getNextId() {
132 return ++globalState.mobxGuid;
133}
134/**
135 * Makes sure that the provided function is invoked at most once.
136 */
137function once(func) {
138 var invoked = false;
139 return function () {
140 if (invoked) {
141 return;
142 }
143 invoked = true;
144 return func.apply(this, arguments);
145 };
146}
147var noop = function noop() {};
148function isFunction(fn) {
149 return typeof fn === "function";
150}
151function isStringish(value) {
152 var t = typeof value;
153 switch (t) {
154 case "string":
155 case "symbol":
156 case "number":
157 return true;
158 }
159 return false;
160}
161function isObject(value) {
162 return value !== null && typeof value === "object";
163}
164function isPlainObject(value) {
165 if (!isObject(value)) {
166 return false;
167 }
168 var proto = Object.getPrototypeOf(value);
169 if (proto == null) {
170 return true;
171 }
172 var protoConstructor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
173 return typeof protoConstructor === "function" && protoConstructor.toString() === plainObjectString;
174}
175// https://stackoverflow.com/a/37865170
176function isGenerator(obj) {
177 var constructor = obj == null ? void 0 : obj.constructor;
178 if (!constructor) {
179 return false;
180 }
181 if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) {
182 return true;
183 }
184 return false;
185}
186function addHiddenProp(object, propName, value) {
187 defineProperty(object, propName, {
188 enumerable: false,
189 writable: true,
190 configurable: true,
191 value: value
192 });
193}
194function addHiddenFinalProp(object, propName, value) {
195 defineProperty(object, propName, {
196 enumerable: false,
197 writable: false,
198 configurable: true,
199 value: value
200 });
201}
202function createInstanceofPredicate(name, theClass) {
203 var propName = "isMobX" + name;
204 theClass.prototype[propName] = true;
205 return function (x) {
206 return isObject(x) && x[propName] === true;
207 };
208}
209function isES6Map(thing) {
210 return thing instanceof Map;
211}
212function isES6Set(thing) {
213 return thing instanceof Set;
214}
215var hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefined";
216/**
217 * Returns the following: own enumerable keys and symbols.
218 */
219function getPlainObjectKeys(object) {
220 var keys = Object.keys(object);
221 // Not supported in IE, so there are not going to be symbol props anyway...
222 if (!hasGetOwnPropertySymbols) {
223 return keys;
224 }
225 var symbols = Object.getOwnPropertySymbols(object);
226 if (!symbols.length) {
227 return keys;
228 }
229 return [].concat(keys, symbols.filter(function (s) {
230 return objectPrototype.propertyIsEnumerable.call(object, s);
231 }));
232}
233// From Immer utils
234// Returns all own keys, including non-enumerable and symbolic
235var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {
236 return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));
237} : /* istanbul ignore next */Object.getOwnPropertyNames;
238function stringifyKey(key) {
239 if (typeof key === "string") {
240 return key;
241 }
242 if (typeof key === "symbol") {
243 return key.toString();
244 }
245 return new String(key).toString();
246}
247function toPrimitive(value) {
248 return value === null ? null : typeof value === "object" ? "" + value : value;
249}
250function hasProp(target, prop) {
251 return objectPrototype.hasOwnProperty.call(target, prop);
252}
253// From Immer utils
254var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {
255 // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274
256 var res = {};
257 // Note: without polyfill for ownKeys, symbols won't be picked up
258 ownKeys(target).forEach(function (key) {
259 res[key] = getDescriptor(target, key);
260 });
261 return res;
262};
263
264function _defineProperties(target, props) {
265 for (var i = 0; i < props.length; i++) {
266 var descriptor = props[i];
267 descriptor.enumerable = descriptor.enumerable || false;
268 descriptor.configurable = true;
269 if ("value" in descriptor) descriptor.writable = true;
270 Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
271 }
272}
273function _createClass(Constructor, protoProps, staticProps) {
274 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
275 if (staticProps) _defineProperties(Constructor, staticProps);
276 Object.defineProperty(Constructor, "prototype", {
277 writable: false
278 });
279 return Constructor;
280}
281function _extends() {
282 _extends = Object.assign ? Object.assign.bind() : function (target) {
283 for (var i = 1; i < arguments.length; i++) {
284 var source = arguments[i];
285 for (var key in source) {
286 if (Object.prototype.hasOwnProperty.call(source, key)) {
287 target[key] = source[key];
288 }
289 }
290 }
291 return target;
292 };
293 return _extends.apply(this, arguments);
294}
295function _inheritsLoose(subClass, superClass) {
296 subClass.prototype = Object.create(superClass.prototype);
297 subClass.prototype.constructor = subClass;
298 _setPrototypeOf(subClass, superClass);
299}
300function _setPrototypeOf(o, p) {
301 _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
302 o.__proto__ = p;
303 return o;
304 };
305 return _setPrototypeOf(o, p);
306}
307function _assertThisInitialized(self) {
308 if (self === void 0) {
309 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
310 }
311 return self;
312}
313function _unsupportedIterableToArray(o, minLen) {
314 if (!o) return;
315 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
316 var n = Object.prototype.toString.call(o).slice(8, -1);
317 if (n === "Object" && o.constructor) n = o.constructor.name;
318 if (n === "Map" || n === "Set") return Array.from(o);
319 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
320}
321function _arrayLikeToArray(arr, len) {
322 if (len == null || len > arr.length) len = arr.length;
323 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
324 return arr2;
325}
326function _createForOfIteratorHelperLoose(o, allowArrayLike) {
327 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
328 if (it) return (it = it.call(o)).next.bind(it);
329 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
330 if (it) o = it;
331 var i = 0;
332 return function () {
333 if (i >= o.length) return {
334 done: true
335 };
336 return {
337 done: false,
338 value: o[i++]
339 };
340 };
341 }
342 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
343}
344function _toPrimitive(input, hint) {
345 if (typeof input !== "object" || input === null) return input;
346 var prim = input[Symbol.toPrimitive];
347 if (prim !== undefined) {
348 var res = prim.call(input, hint || "default");
349 if (typeof res !== "object") return res;
350 throw new TypeError("@@toPrimitive must return a primitive value.");
351 }
352 return (hint === "string" ? String : Number)(input);
353}
354function _toPropertyKey(arg) {
355 var key = _toPrimitive(arg, "string");
356 return typeof key === "symbol" ? key : String(key);
357}
358
359var storedAnnotationsSymbol = /*#__PURE__*/Symbol("mobx-stored-annotations");
360/**
361 * Creates a function that acts as
362 * - decorator
363 * - annotation object
364 */
365function createDecoratorAnnotation(annotation) {
366 function decorator(target, property) {
367 storeAnnotation(target, property, annotation);
368 }
369 return Object.assign(decorator, annotation);
370}
371/**
372 * Stores annotation to prototype,
373 * so it can be inspected later by `makeObservable` called from constructor
374 */
375function storeAnnotation(prototype, key, annotation) {
376 if (!hasProp(prototype, storedAnnotationsSymbol)) {
377 addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));
378 }
379 // @override must override something
380 if ( isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {
381 var fieldName = prototype.constructor.name + ".prototype." + key.toString();
382 die("'" + fieldName + "' is decorated with 'override', " + "but no such decorated member was found on prototype.");
383 }
384 // Cannot re-decorate
385 assertNotDecorated(prototype, annotation, key);
386 // Ignore override
387 if (!isOverride(annotation)) {
388 prototype[storedAnnotationsSymbol][key] = annotation;
389 }
390}
391function assertNotDecorated(prototype, annotation, key) {
392 if ( !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {
393 var fieldName = prototype.constructor.name + ".prototype." + key.toString();
394 var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;
395 var requestedAnnotationType = annotation.annotationType_;
396 die("Cannot apply '@" + requestedAnnotationType + "' to '" + fieldName + "':" + ("\nThe field is already decorated with '@" + currentAnnotationType + "'.") + "\nRe-decorating fields is not allowed." + "\nUse '@override' decorator for methods overridden by subclass.");
397 }
398}
399/**
400 * Collects annotations from prototypes and stores them on target (instance)
401 */
402function collectStoredAnnotations(target) {
403 if (!hasProp(target, storedAnnotationsSymbol)) {
404 if ( !target[storedAnnotationsSymbol]) {
405 die("No annotations were passed to makeObservable, but no decorated members have been found either");
406 }
407 // We need a copy as we will remove annotation from the list once it's applied.
408 addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));
409 }
410 return target[storedAnnotationsSymbol];
411}
412
413var $mobx = /*#__PURE__*/Symbol("mobx administration");
414var Atom = /*#__PURE__*/function () {
415 // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed
416
417 /**
418 * Create a new atom. For debugging purposes it is recommended to give it a name.
419 * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.
420 */
421 function Atom(name_) {
422 if (name_ === void 0) {
423 name_ = "Atom@" + getNextId() ;
424 }
425 this.name_ = void 0;
426 this.isPendingUnobservation_ = false;
427 this.isBeingObserved_ = false;
428 this.observers_ = new Set();
429 this.diffValue_ = 0;
430 this.lastAccessedBy_ = 0;
431 this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;
432 this.onBOL = void 0;
433 this.onBUOL = void 0;
434 this.name_ = name_;
435 }
436 // onBecomeObservedListeners
437 var _proto = Atom.prototype;
438 _proto.onBO = function onBO() {
439 if (this.onBOL) {
440 this.onBOL.forEach(function (listener) {
441 return listener();
442 });
443 }
444 };
445 _proto.onBUO = function onBUO() {
446 if (this.onBUOL) {
447 this.onBUOL.forEach(function (listener) {
448 return listener();
449 });
450 }
451 }
452 /**
453 * Invoke this method to notify mobx that your atom has been used somehow.
454 * Returns true if there is currently a reactive context.
455 */;
456 _proto.reportObserved = function reportObserved$1() {
457 return reportObserved(this);
458 }
459 /**
460 * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.
461 */;
462 _proto.reportChanged = function reportChanged() {
463 startBatch();
464 propagateChanged(this);
465 // We could update state version only at the end of batch,
466 // but we would still have to switch some global flag here to signal a change.
467 globalState.stateVersion = globalState.stateVersion < Number.MAX_SAFE_INTEGER ? globalState.stateVersion + 1 : Number.MIN_SAFE_INTEGER;
468 endBatch();
469 };
470 _proto.toString = function toString() {
471 return this.name_;
472 };
473 return Atom;
474}();
475var isAtom = /*#__PURE__*/createInstanceofPredicate("Atom", Atom);
476function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {
477 if (onBecomeObservedHandler === void 0) {
478 onBecomeObservedHandler = noop;
479 }
480 if (onBecomeUnobservedHandler === void 0) {
481 onBecomeUnobservedHandler = noop;
482 }
483 var atom = new Atom(name);
484 // default `noop` listener will not initialize the hook Set
485 if (onBecomeObservedHandler !== noop) {
486 onBecomeObserved(atom, onBecomeObservedHandler);
487 }
488 if (onBecomeUnobservedHandler !== noop) {
489 onBecomeUnobserved(atom, onBecomeUnobservedHandler);
490 }
491 return atom;
492}
493
494function identityComparer(a, b) {
495 return a === b;
496}
497function structuralComparer(a, b) {
498 return deepEqual(a, b);
499}
500function shallowComparer(a, b) {
501 return deepEqual(a, b, 1);
502}
503function defaultComparer(a, b) {
504 if (Object.is) {
505 return Object.is(a, b);
506 }
507 return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;
508}
509var comparer = {
510 identity: identityComparer,
511 structural: structuralComparer,
512 "default": defaultComparer,
513 shallow: shallowComparer
514};
515
516function deepEnhancer(v, _, name) {
517 // it is an observable already, done
518 if (isObservable(v)) {
519 return v;
520 }
521 // something that can be converted and mutated?
522 if (Array.isArray(v)) {
523 return observable.array(v, {
524 name: name
525 });
526 }
527 if (isPlainObject(v)) {
528 return observable.object(v, undefined, {
529 name: name
530 });
531 }
532 if (isES6Map(v)) {
533 return observable.map(v, {
534 name: name
535 });
536 }
537 if (isES6Set(v)) {
538 return observable.set(v, {
539 name: name
540 });
541 }
542 if (typeof v === "function" && !isAction(v) && !isFlow(v)) {
543 if (isGenerator(v)) {
544 return flow(v);
545 } else {
546 return autoAction(name, v);
547 }
548 }
549 return v;
550}
551function shallowEnhancer(v, _, name) {
552 if (v === undefined || v === null) {
553 return v;
554 }
555 if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {
556 return v;
557 }
558 if (Array.isArray(v)) {
559 return observable.array(v, {
560 name: name,
561 deep: false
562 });
563 }
564 if (isPlainObject(v)) {
565 return observable.object(v, undefined, {
566 name: name,
567 deep: false
568 });
569 }
570 if (isES6Map(v)) {
571 return observable.map(v, {
572 name: name,
573 deep: false
574 });
575 }
576 if (isES6Set(v)) {
577 return observable.set(v, {
578 name: name,
579 deep: false
580 });
581 }
582 {
583 die("The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets");
584 }
585}
586function referenceEnhancer(newValue) {
587 // never turn into an observable
588 return newValue;
589}
590function refStructEnhancer(v, oldValue) {
591 if ( isObservable(v)) {
592 die("observable.struct should not be used with observable values");
593 }
594 if (deepEqual(v, oldValue)) {
595 return oldValue;
596 }
597 return v;
598}
599
600var OVERRIDE = "override";
601var override = /*#__PURE__*/createDecoratorAnnotation({
602 annotationType_: OVERRIDE,
603 make_: make_,
604 extend_: extend_
605});
606function isOverride(annotation) {
607 return annotation.annotationType_ === OVERRIDE;
608}
609function make_(adm, key) {
610 // Must not be plain object
611 if ( adm.isPlainObject_) {
612 die("Cannot apply '" + this.annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + this.annotationType_ + "' cannot be used on plain objects."));
613 }
614 // Must override something
615 if ( !hasProp(adm.appliedAnnotations_, key)) {
616 die("'" + adm.name_ + "." + key.toString() + "' is annotated with '" + this.annotationType_ + "', " + "but no such annotated member was found on prototype.");
617 }
618 return 0 /* Cancel */;
619}
620
621function extend_(adm, key, descriptor, proxyTrap) {
622 die("'" + this.annotationType_ + "' can only be used with 'makeObservable'");
623}
624
625function createActionAnnotation(name, options) {
626 return {
627 annotationType_: name,
628 options_: options,
629 make_: make_$1,
630 extend_: extend_$1
631 };
632}
633function make_$1(adm, key, descriptor, source) {
634 var _this$options_;
635 // bound
636 if ((_this$options_ = this.options_) != null && _this$options_.bound) {
637 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 1 /* Break */;
638 }
639 // own
640 if (source === adm.target_) {
641 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 2 /* Continue */;
642 }
643 // prototype
644 if (isAction(descriptor.value)) {
645 // A prototype could have been annotated already by other constructor,
646 // rest of the proto chain must be annotated already
647 return 1 /* Break */;
648 }
649
650 var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);
651 defineProperty(source, key, actionDescriptor);
652 return 2 /* Continue */;
653}
654
655function extend_$1(adm, key, descriptor, proxyTrap) {
656 var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);
657 return adm.defineProperty_(key, actionDescriptor, proxyTrap);
658}
659function assertActionDescriptor(adm, _ref, key, _ref2) {
660 var annotationType_ = _ref.annotationType_;
661 var value = _ref2.value;
662 if ( !isFunction(value)) {
663 die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a function value."));
664 }
665}
666function createActionDescriptor(adm, annotation, key, descriptor,
667// provides ability to disable safeDescriptors for prototypes
668safeDescriptors) {
669 var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;
670 if (safeDescriptors === void 0) {
671 safeDescriptors = globalState.safeDescriptors;
672 }
673 assertActionDescriptor(adm, annotation, key, descriptor);
674 var value = descriptor.value;
675 if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {
676 var _adm$proxy_;
677 value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);
678 }
679 return {
680 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,
681 // https://github.com/mobxjs/mobx/discussions/3140
682 (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),
683 // Non-configurable for classes
684 // prevents accidental field redefinition in subclass
685 configurable: safeDescriptors ? adm.isPlainObject_ : true,
686 // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058
687 enumerable: false,
688 // Non-obsevable, therefore non-writable
689 // Also prevents rewriting in subclass constructor
690 writable: safeDescriptors ? false : true
691 };
692}
693
694function createFlowAnnotation(name, options) {
695 return {
696 annotationType_: name,
697 options_: options,
698 make_: make_$2,
699 extend_: extend_$2
700 };
701}
702function make_$2(adm, key, descriptor, source) {
703 var _this$options_;
704 // own
705 if (source === adm.target_) {
706 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 2 /* Continue */;
707 }
708 // prototype
709 // bound - must annotate protos to support super.flow()
710 if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {
711 if (this.extend_(adm, key, descriptor, false) === null) {
712 return 0 /* Cancel */;
713 }
714 }
715
716 if (isFlow(descriptor.value)) {
717 // A prototype could have been annotated already by other constructor,
718 // rest of the proto chain must be annotated already
719 return 1 /* Break */;
720 }
721
722 var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);
723 defineProperty(source, key, flowDescriptor);
724 return 2 /* Continue */;
725}
726
727function extend_$2(adm, key, descriptor, proxyTrap) {
728 var _this$options_2;
729 var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);
730 return adm.defineProperty_(key, flowDescriptor, proxyTrap);
731}
732function assertFlowDescriptor(adm, _ref, key, _ref2) {
733 var annotationType_ = _ref.annotationType_;
734 var value = _ref2.value;
735 if ( !isFunction(value)) {
736 die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a generator function value."));
737 }
738}
739function createFlowDescriptor(adm, annotation, key, descriptor, bound,
740// provides ability to disable safeDescriptors for prototypes
741safeDescriptors) {
742 if (safeDescriptors === void 0) {
743 safeDescriptors = globalState.safeDescriptors;
744 }
745 assertFlowDescriptor(adm, annotation, key, descriptor);
746 var value = descriptor.value;
747 // In case of flow.bound, the descriptor can be from already annotated prototype
748 if (!isFlow(value)) {
749 value = flow(value);
750 }
751 if (bound) {
752 var _adm$proxy_;
753 // We do not keep original function around, so we bind the existing flow
754 value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);
755 // This is normally set by `flow`, but `bind` returns new function...
756 value.isMobXFlow = true;
757 }
758 return {
759 value: value,
760 // Non-configurable for classes
761 // prevents accidental field redefinition in subclass
762 configurable: safeDescriptors ? adm.isPlainObject_ : true,
763 // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058
764 enumerable: false,
765 // Non-obsevable, therefore non-writable
766 // Also prevents rewriting in subclass constructor
767 writable: safeDescriptors ? false : true
768 };
769}
770
771function createComputedAnnotation(name, options) {
772 return {
773 annotationType_: name,
774 options_: options,
775 make_: make_$3,
776 extend_: extend_$3
777 };
778}
779function make_$3(adm, key, descriptor) {
780 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 1 /* Break */;
781}
782
783function extend_$3(adm, key, descriptor, proxyTrap) {
784 assertComputedDescriptor(adm, this, key, descriptor);
785 return adm.defineComputedProperty_(key, _extends({}, this.options_, {
786 get: descriptor.get,
787 set: descriptor.set
788 }), proxyTrap);
789}
790function assertComputedDescriptor(adm, _ref, key, _ref2) {
791 var annotationType_ = _ref.annotationType_;
792 var get = _ref2.get;
793 if ( !get) {
794 die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on getter(+setter) properties."));
795 }
796}
797
798function createObservableAnnotation(name, options) {
799 return {
800 annotationType_: name,
801 options_: options,
802 make_: make_$4,
803 extend_: extend_$4
804 };
805}
806function make_$4(adm, key, descriptor) {
807 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 1 /* Break */;
808}
809
810function extend_$4(adm, key, descriptor, proxyTrap) {
811 var _this$options_$enhanc, _this$options_;
812 assertObservableDescriptor(adm, this, key, descriptor);
813 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);
814}
815function assertObservableDescriptor(adm, _ref, key, descriptor) {
816 var annotationType_ = _ref.annotationType_;
817 if ( !("value" in descriptor)) {
818 die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' cannot be used on getter/setter properties"));
819 }
820}
821
822var AUTO = "true";
823var autoAnnotation = /*#__PURE__*/createAutoAnnotation();
824function createAutoAnnotation(options) {
825 return {
826 annotationType_: AUTO,
827 options_: options,
828 make_: make_$5,
829 extend_: extend_$5
830 };
831}
832function make_$5(adm, key, descriptor, source) {
833 var _this$options_3, _this$options_4;
834 // getter -> computed
835 if (descriptor.get) {
836 return computed.make_(adm, key, descriptor, source);
837 }
838 // lone setter -> action setter
839 if (descriptor.set) {
840 // TODO make action applicable to setter and delegate to action.make_
841 var set = createAction(key.toString(), descriptor.set);
842 // own
843 if (source === adm.target_) {
844 return adm.defineProperty_(key, {
845 configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,
846 set: set
847 }) === null ? 0 /* Cancel */ : 2 /* Continue */;
848 }
849 // proto
850 defineProperty(source, key, {
851 configurable: true,
852 set: set
853 });
854 return 2 /* Continue */;
855 }
856 // function on proto -> autoAction/flow
857 if (source !== adm.target_ && typeof descriptor.value === "function") {
858 var _this$options_2;
859 if (isGenerator(descriptor.value)) {
860 var _this$options_;
861 var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;
862 return flowAnnotation.make_(adm, key, descriptor, source);
863 }
864 var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;
865 return actionAnnotation.make_(adm, key, descriptor, source);
866 }
867 // other -> observable
868 // Copy props from proto as well, see test:
869 // "decorate should work with Object.create"
870 var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable;
871 // if function respect autoBind option
872 if (typeof descriptor.value === "function" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {
873 var _adm$proxy_;
874 descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);
875 }
876 return observableAnnotation.make_(adm, key, descriptor, source);
877}
878function extend_$5(adm, key, descriptor, proxyTrap) {
879 var _this$options_5, _this$options_6;
880 // getter -> computed
881 if (descriptor.get) {
882 return computed.extend_(adm, key, descriptor, proxyTrap);
883 }
884 // lone setter -> action setter
885 if (descriptor.set) {
886 // TODO make action applicable to setter and delegate to action.extend_
887 return adm.defineProperty_(key, {
888 configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,
889 set: createAction(key.toString(), descriptor.set)
890 }, proxyTrap);
891 }
892 // other -> observable
893 // if function respect autoBind option
894 if (typeof descriptor.value === "function" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {
895 var _adm$proxy_2;
896 descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);
897 }
898 var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;
899 return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);
900}
901
902var OBSERVABLE = "observable";
903var OBSERVABLE_REF = "observable.ref";
904var OBSERVABLE_SHALLOW = "observable.shallow";
905var OBSERVABLE_STRUCT = "observable.struct";
906// Predefined bags of create observable options, to avoid allocating temporarily option objects
907// in the majority of cases
908var defaultCreateObservableOptions = {
909 deep: true,
910 name: undefined,
911 defaultDecorator: undefined,
912 proxy: true
913};
914Object.freeze(defaultCreateObservableOptions);
915function asCreateObservableOptions(thing) {
916 return thing || defaultCreateObservableOptions;
917}
918var observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);
919var observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {
920 enhancer: referenceEnhancer
921});
922var observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {
923 enhancer: shallowEnhancer
924});
925var observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {
926 enhancer: refStructEnhancer
927});
928var observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);
929function getEnhancerFromOptions(options) {
930 return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);
931}
932function getAnnotationFromOptions(options) {
933 var _options$defaultDecor;
934 return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;
935}
936function getEnhancerFromAnnotation(annotation) {
937 var _annotation$options_$, _annotation$options_;
938 return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;
939}
940/**
941 * Turns an object, array or function into a reactive structure.
942 * @param v the value which should become observable.
943 */
944function createObservable(v, arg2, arg3) {
945 // @observable someProp;
946 if (isStringish(arg2)) {
947 storeAnnotation(v, arg2, observableAnnotation);
948 return;
949 }
950 // already observable - ignore
951 if (isObservable(v)) {
952 return v;
953 }
954 // plain object
955 if (isPlainObject(v)) {
956 return observable.object(v, arg2, arg3);
957 }
958 // Array
959 if (Array.isArray(v)) {
960 return observable.array(v, arg2);
961 }
962 // Map
963 if (isES6Map(v)) {
964 return observable.map(v, arg2);
965 }
966 // Set
967 if (isES6Set(v)) {
968 return observable.set(v, arg2);
969 }
970 // other object - ignore
971 if (typeof v === "object" && v !== null) {
972 return v;
973 }
974 // anything else
975 return observable.box(v, arg2);
976}
977assign(createObservable, observableDecoratorAnnotation);
978var observableFactories = {
979 box: function box(value, options) {
980 var o = asCreateObservableOptions(options);
981 return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);
982 },
983 array: function array(initialValues, options) {
984 var o = asCreateObservableOptions(options);
985 return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);
986 },
987 map: function map(initialValues, options) {
988 var o = asCreateObservableOptions(options);
989 return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);
990 },
991 set: function set(initialValues, options) {
992 var o = asCreateObservableOptions(options);
993 return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);
994 },
995 object: function object(props, decorators, options) {
996 return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);
997 },
998 ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),
999 shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),
1000 deep: observableDecoratorAnnotation,
1001 struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)
1002};
1003// eslint-disable-next-line
1004var observable = /*#__PURE__*/assign(createObservable, observableFactories);
1005
1006var COMPUTED = "computed";
1007var COMPUTED_STRUCT = "computed.struct";
1008var computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);
1009var computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {
1010 equals: comparer.structural
1011});
1012/**
1013 * Decorator for class properties: @computed get value() { return expr; }.
1014 * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;
1015 */
1016var computed = function computed(arg1, arg2) {
1017 if (isStringish(arg2)) {
1018 // @computed
1019 return storeAnnotation(arg1, arg2, computedAnnotation);
1020 }
1021 if (isPlainObject(arg1)) {
1022 // @computed({ options })
1023 return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));
1024 }
1025 // computed(expr, options?)
1026 {
1027 if (!isFunction(arg1)) {
1028 die("First argument to `computed` should be an expression.");
1029 }
1030 if (isFunction(arg2)) {
1031 die("A setter as second argument is no longer supported, use `{ set: fn }` option instead");
1032 }
1033 }
1034 var opts = isPlainObject(arg2) ? arg2 : {};
1035 opts.get = arg1;
1036 opts.name || (opts.name = arg1.name || ""); /* for generated name */
1037 return new ComputedValue(opts);
1038};
1039Object.assign(computed, computedAnnotation);
1040computed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);
1041
1042var _getDescriptor$config, _getDescriptor;
1043// we don't use globalState for these in order to avoid possible issues with multiple
1044// mobx versions
1045var currentActionId = 0;
1046var nextActionId = 1;
1047var isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, "name")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false;
1048// we can safely recycle this object
1049var tmpNameDescriptor = {
1050 value: "action",
1051 configurable: true,
1052 writable: false,
1053 enumerable: false
1054};
1055function createAction(actionName, fn, autoAction, ref) {
1056 if (autoAction === void 0) {
1057 autoAction = false;
1058 }
1059 {
1060 if (!isFunction(fn)) {
1061 die("`action` can only be invoked on functions");
1062 }
1063 if (typeof actionName !== "string" || !actionName) {
1064 die("actions should have valid names, got: '" + actionName + "'");
1065 }
1066 }
1067 function res() {
1068 return executeAction(actionName, autoAction, fn, ref || this, arguments);
1069 }
1070 res.isMobxAction = true;
1071 if (isFunctionNameConfigurable) {
1072 tmpNameDescriptor.value = actionName;
1073 defineProperty(res, "name", tmpNameDescriptor);
1074 }
1075 return res;
1076}
1077function executeAction(actionName, canRunAsDerivation, fn, scope, args) {
1078 var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);
1079 try {
1080 return fn.apply(scope, args);
1081 } catch (err) {
1082 runInfo.error_ = err;
1083 throw err;
1084 } finally {
1085 _endAction(runInfo);
1086 }
1087}
1088function _startAction(actionName, canRunAsDerivation,
1089// true for autoAction
1090scope, args) {
1091 var notifySpy_ = isSpyEnabled() && !!actionName;
1092 var startTime_ = 0;
1093 if ( notifySpy_) {
1094 startTime_ = Date.now();
1095 var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;
1096 spyReportStart({
1097 type: ACTION,
1098 name: actionName,
1099 object: scope,
1100 arguments: flattenedArgs
1101 });
1102 }
1103 var prevDerivation_ = globalState.trackingDerivation;
1104 var runAsAction = !canRunAsDerivation || !prevDerivation_;
1105 startBatch();
1106 var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow
1107 if (runAsAction) {
1108 untrackedStart();
1109 prevAllowStateChanges_ = allowStateChangesStart(true);
1110 }
1111 var prevAllowStateReads_ = allowStateReadsStart(true);
1112 var runInfo = {
1113 runAsAction_: runAsAction,
1114 prevDerivation_: prevDerivation_,
1115 prevAllowStateChanges_: prevAllowStateChanges_,
1116 prevAllowStateReads_: prevAllowStateReads_,
1117 notifySpy_: notifySpy_,
1118 startTime_: startTime_,
1119 actionId_: nextActionId++,
1120 parentActionId_: currentActionId
1121 };
1122 currentActionId = runInfo.actionId_;
1123 return runInfo;
1124}
1125function _endAction(runInfo) {
1126 if (currentActionId !== runInfo.actionId_) {
1127 die(30);
1128 }
1129 currentActionId = runInfo.parentActionId_;
1130 if (runInfo.error_ !== undefined) {
1131 globalState.suppressReactionErrors = true;
1132 }
1133 allowStateChangesEnd(runInfo.prevAllowStateChanges_);
1134 allowStateReadsEnd(runInfo.prevAllowStateReads_);
1135 endBatch();
1136 if (runInfo.runAsAction_) {
1137 untrackedEnd(runInfo.prevDerivation_);
1138 }
1139 if ( runInfo.notifySpy_) {
1140 spyReportEnd({
1141 time: Date.now() - runInfo.startTime_
1142 });
1143 }
1144 globalState.suppressReactionErrors = false;
1145}
1146function allowStateChanges(allowStateChanges, func) {
1147 var prev = allowStateChangesStart(allowStateChanges);
1148 try {
1149 return func();
1150 } finally {
1151 allowStateChangesEnd(prev);
1152 }
1153}
1154function allowStateChangesStart(allowStateChanges) {
1155 var prev = globalState.allowStateChanges;
1156 globalState.allowStateChanges = allowStateChanges;
1157 return prev;
1158}
1159function allowStateChangesEnd(prev) {
1160 globalState.allowStateChanges = prev;
1161}
1162
1163var _Symbol$toPrimitive;
1164var CREATE = "create";
1165_Symbol$toPrimitive = Symbol.toPrimitive;
1166var ObservableValue = /*#__PURE__*/function (_Atom) {
1167 _inheritsLoose(ObservableValue, _Atom);
1168 function ObservableValue(value, enhancer, name_, notifySpy, equals) {
1169 var _this;
1170 if (name_ === void 0) {
1171 name_ = "ObservableValue@" + getNextId() ;
1172 }
1173 if (notifySpy === void 0) {
1174 notifySpy = true;
1175 }
1176 if (equals === void 0) {
1177 equals = comparer["default"];
1178 }
1179 _this = _Atom.call(this, name_) || this;
1180 _this.enhancer = void 0;
1181 _this.name_ = void 0;
1182 _this.equals = void 0;
1183 _this.hasUnreportedChange_ = false;
1184 _this.interceptors_ = void 0;
1185 _this.changeListeners_ = void 0;
1186 _this.value_ = void 0;
1187 _this.dehancer = void 0;
1188 _this.enhancer = enhancer;
1189 _this.name_ = name_;
1190 _this.equals = equals;
1191 _this.value_ = enhancer(value, undefined, name_);
1192 if ( notifySpy && isSpyEnabled()) {
1193 // only notify spy if this is a stand-alone observable
1194 spyReport({
1195 type: CREATE,
1196 object: _assertThisInitialized(_this),
1197 observableKind: "value",
1198 debugObjectName: _this.name_,
1199 newValue: "" + _this.value_
1200 });
1201 }
1202 return _this;
1203 }
1204 var _proto = ObservableValue.prototype;
1205 _proto.dehanceValue = function dehanceValue(value) {
1206 if (this.dehancer !== undefined) {
1207 return this.dehancer(value);
1208 }
1209 return value;
1210 };
1211 _proto.set = function set(newValue) {
1212 var oldValue = this.value_;
1213 newValue = this.prepareNewValue_(newValue);
1214 if (newValue !== globalState.UNCHANGED) {
1215 var notifySpy = isSpyEnabled();
1216 if ( notifySpy) {
1217 spyReportStart({
1218 type: UPDATE,
1219 object: this,
1220 observableKind: "value",
1221 debugObjectName: this.name_,
1222 newValue: newValue,
1223 oldValue: oldValue
1224 });
1225 }
1226 this.setNewValue_(newValue);
1227 if ( notifySpy) {
1228 spyReportEnd();
1229 }
1230 }
1231 };
1232 _proto.prepareNewValue_ = function prepareNewValue_(newValue) {
1233 checkIfStateModificationsAreAllowed(this);
1234 if (hasInterceptors(this)) {
1235 var change = interceptChange(this, {
1236 object: this,
1237 type: UPDATE,
1238 newValue: newValue
1239 });
1240 if (!change) {
1241 return globalState.UNCHANGED;
1242 }
1243 newValue = change.newValue;
1244 }
1245 // apply modifier
1246 newValue = this.enhancer(newValue, this.value_, this.name_);
1247 return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;
1248 };
1249 _proto.setNewValue_ = function setNewValue_(newValue) {
1250 var oldValue = this.value_;
1251 this.value_ = newValue;
1252 this.reportChanged();
1253 if (hasListeners(this)) {
1254 notifyListeners(this, {
1255 type: UPDATE,
1256 object: this,
1257 newValue: newValue,
1258 oldValue: oldValue
1259 });
1260 }
1261 };
1262 _proto.get = function get() {
1263 this.reportObserved();
1264 return this.dehanceValue(this.value_);
1265 };
1266 _proto.intercept_ = function intercept_(handler) {
1267 return registerInterceptor(this, handler);
1268 };
1269 _proto.observe_ = function observe_(listener, fireImmediately) {
1270 if (fireImmediately) {
1271 listener({
1272 observableKind: "value",
1273 debugObjectName: this.name_,
1274 object: this,
1275 type: UPDATE,
1276 newValue: this.value_,
1277 oldValue: undefined
1278 });
1279 }
1280 return registerListener(this, listener);
1281 };
1282 _proto.raw = function raw() {
1283 // used by MST ot get undehanced value
1284 return this.value_;
1285 };
1286 _proto.toJSON = function toJSON() {
1287 return this.get();
1288 };
1289 _proto.toString = function toString() {
1290 return this.name_ + "[" + this.value_ + "]";
1291 };
1292 _proto.valueOf = function valueOf() {
1293 return toPrimitive(this.get());
1294 };
1295 _proto[_Symbol$toPrimitive] = function () {
1296 return this.valueOf();
1297 };
1298 return ObservableValue;
1299}(Atom);
1300var isObservableValue = /*#__PURE__*/createInstanceofPredicate("ObservableValue", ObservableValue);
1301
1302var _Symbol$toPrimitive$1;
1303/**
1304 * A node in the state dependency root that observes other nodes, and can be observed itself.
1305 *
1306 * ComputedValue will remember the result of the computation for the duration of the batch, or
1307 * while being observed.
1308 *
1309 * During this time it will recompute only when one of its direct dependencies changed,
1310 * but only when it is being accessed with `ComputedValue.get()`.
1311 *
1312 * Implementation description:
1313 * 1. First time it's being accessed it will compute and remember result
1314 * give back remembered result until 2. happens
1315 * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.
1316 * 3. When it's being accessed, recompute if any shallow dependency changed.
1317 * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.
1318 * go to step 2. either way
1319 *
1320 * If at any point it's outside batch and it isn't observed: reset everything and go to 1.
1321 */
1322_Symbol$toPrimitive$1 = Symbol.toPrimitive;
1323var ComputedValue = /*#__PURE__*/function () {
1324 // nodes we are looking at. Our value depends on these nodes
1325 // during tracking it's an array with new observed observers
1326
1327 // to check for cycles
1328
1329 // N.B: unminified as it is used by MST
1330
1331 /**
1332 * Create a new computed value based on a function expression.
1333 *
1334 * The `name` property is for debug purposes only.
1335 *
1336 * The `equals` property specifies the comparer function to use to determine if a newly produced
1337 * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`
1338 * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.
1339 * Structural comparison can be convenient if you always produce a new aggregated object and
1340 * don't want to notify observers if it is structurally the same.
1341 * This is useful for working with vectors, mouse coordinates etc.
1342 */
1343 function ComputedValue(options) {
1344 this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;
1345 this.observing_ = [];
1346 this.newObserving_ = null;
1347 this.isBeingObserved_ = false;
1348 this.isPendingUnobservation_ = false;
1349 this.observers_ = new Set();
1350 this.diffValue_ = 0;
1351 this.runId_ = 0;
1352 this.lastAccessedBy_ = 0;
1353 this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;
1354 this.unboundDepsCount_ = 0;
1355 this.value_ = new CaughtException(null);
1356 this.name_ = void 0;
1357 this.triggeredBy_ = void 0;
1358 this.isComputing_ = false;
1359 this.isRunningSetter_ = false;
1360 this.derivation = void 0;
1361 this.setter_ = void 0;
1362 this.isTracing_ = TraceMode.NONE;
1363 this.scope_ = void 0;
1364 this.equals_ = void 0;
1365 this.requiresReaction_ = void 0;
1366 this.keepAlive_ = void 0;
1367 this.onBOL = void 0;
1368 this.onBUOL = void 0;
1369 if (!options.get) {
1370 die(31);
1371 }
1372 this.derivation = options.get;
1373 this.name_ = options.name || ( "ComputedValue@" + getNextId() );
1374 if (options.set) {
1375 this.setter_ = createAction( this.name_ + "-setter" , options.set);
1376 }
1377 this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer["default"]);
1378 this.scope_ = options.context;
1379 this.requiresReaction_ = options.requiresReaction;
1380 this.keepAlive_ = !!options.keepAlive;
1381 }
1382 var _proto = ComputedValue.prototype;
1383 _proto.onBecomeStale_ = function onBecomeStale_() {
1384 propagateMaybeChanged(this);
1385 };
1386 _proto.onBO = function onBO() {
1387 if (this.onBOL) {
1388 this.onBOL.forEach(function (listener) {
1389 return listener();
1390 });
1391 }
1392 };
1393 _proto.onBUO = function onBUO() {
1394 if (this.onBUOL) {
1395 this.onBUOL.forEach(function (listener) {
1396 return listener();
1397 });
1398 }
1399 }
1400 /**
1401 * Returns the current value of this computed value.
1402 * Will evaluate its computation first if needed.
1403 */;
1404 _proto.get = function get() {
1405 if (this.isComputing_) {
1406 die(32, this.name_, this.derivation);
1407 }
1408 if (globalState.inBatch === 0 &&
1409 // !globalState.trackingDerivatpion &&
1410 this.observers_.size === 0 && !this.keepAlive_) {
1411 if (shouldCompute(this)) {
1412 this.warnAboutUntrackedRead_();
1413 startBatch(); // See perf test 'computed memoization'
1414 this.value_ = this.computeValue_(false);
1415 endBatch();
1416 }
1417 } else {
1418 reportObserved(this);
1419 if (shouldCompute(this)) {
1420 var prevTrackingContext = globalState.trackingContext;
1421 if (this.keepAlive_ && !prevTrackingContext) {
1422 globalState.trackingContext = this;
1423 }
1424 if (this.trackAndCompute()) {
1425 propagateChangeConfirmed(this);
1426 }
1427 globalState.trackingContext = prevTrackingContext;
1428 }
1429 }
1430 var result = this.value_;
1431 if (isCaughtException(result)) {
1432 throw result.cause;
1433 }
1434 return result;
1435 };
1436 _proto.set = function set(value) {
1437 if (this.setter_) {
1438 if (this.isRunningSetter_) {
1439 die(33, this.name_);
1440 }
1441 this.isRunningSetter_ = true;
1442 try {
1443 this.setter_.call(this.scope_, value);
1444 } finally {
1445 this.isRunningSetter_ = false;
1446 }
1447 } else {
1448 die(34, this.name_);
1449 }
1450 };
1451 _proto.trackAndCompute = function trackAndCompute() {
1452 // N.B: unminified as it is used by MST
1453 var oldValue = this.value_;
1454 var wasSuspended = /* see #1208 */this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;
1455 var newValue = this.computeValue_(true);
1456 var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);
1457 if (changed) {
1458 this.value_ = newValue;
1459 if ( isSpyEnabled()) {
1460 spyReport({
1461 observableKind: "computed",
1462 debugObjectName: this.name_,
1463 object: this.scope_,
1464 type: "update",
1465 oldValue: oldValue,
1466 newValue: newValue
1467 });
1468 }
1469 }
1470 return changed;
1471 };
1472 _proto.computeValue_ = function computeValue_(track) {
1473 this.isComputing_ = true;
1474 // don't allow state changes during computation
1475 var prev = allowStateChangesStart(false);
1476 var res;
1477 if (track) {
1478 res = trackDerivedFunction(this, this.derivation, this.scope_);
1479 } else {
1480 if (globalState.disableErrorBoundaries === true) {
1481 res = this.derivation.call(this.scope_);
1482 } else {
1483 try {
1484 res = this.derivation.call(this.scope_);
1485 } catch (e) {
1486 res = new CaughtException(e);
1487 }
1488 }
1489 }
1490 allowStateChangesEnd(prev);
1491 this.isComputing_ = false;
1492 return res;
1493 };
1494 _proto.suspend_ = function suspend_() {
1495 if (!this.keepAlive_) {
1496 clearObserving(this);
1497 this.value_ = undefined; // don't hold on to computed value!
1498 if ( this.isTracing_ !== TraceMode.NONE) {
1499 console.log("[mobx.trace] Computed value '" + this.name_ + "' was suspended and it will recompute on the next access.");
1500 }
1501 }
1502 };
1503 _proto.observe_ = function observe_(listener, fireImmediately) {
1504 var _this = this;
1505 var firstTime = true;
1506 var prevValue = undefined;
1507 return autorun(function () {
1508 // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place
1509 var newValue = _this.get();
1510 if (!firstTime || fireImmediately) {
1511 var prevU = untrackedStart();
1512 listener({
1513 observableKind: "computed",
1514 debugObjectName: _this.name_,
1515 type: UPDATE,
1516 object: _this,
1517 newValue: newValue,
1518 oldValue: prevValue
1519 });
1520 untrackedEnd(prevU);
1521 }
1522 firstTime = false;
1523 prevValue = newValue;
1524 });
1525 };
1526 _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {
1527 if (this.isTracing_ !== TraceMode.NONE) {
1528 console.log("[mobx.trace] Computed value '" + this.name_ + "' is being read outside a reactive context. Doing a full recompute.");
1529 }
1530 if (typeof this.requiresReaction_ === "boolean" ? this.requiresReaction_ : globalState.computedRequiresReaction) {
1531 console.warn("[mobx] Computed value '" + this.name_ + "' is being read outside a reactive context. Doing a full recompute.");
1532 }
1533 };
1534 _proto.toString = function toString() {
1535 return this.name_ + "[" + this.derivation.toString() + "]";
1536 };
1537 _proto.valueOf = function valueOf() {
1538 return toPrimitive(this.get());
1539 };
1540 _proto[_Symbol$toPrimitive$1] = function () {
1541 return this.valueOf();
1542 };
1543 return ComputedValue;
1544}();
1545var isComputedValue = /*#__PURE__*/createInstanceofPredicate("ComputedValue", ComputedValue);
1546
1547var IDerivationState_;
1548(function (IDerivationState_) {
1549 // before being run or (outside batch and not being observed)
1550 // at this point derivation is not holding any data about dependency tree
1551 IDerivationState_[IDerivationState_["NOT_TRACKING_"] = -1] = "NOT_TRACKING_";
1552 // no shallow dependency changed since last computation
1553 // won't recalculate derivation
1554 // this is what makes mobx fast
1555 IDerivationState_[IDerivationState_["UP_TO_DATE_"] = 0] = "UP_TO_DATE_";
1556 // some deep dependency changed, but don't know if shallow dependency changed
1557 // will require to check first if UP_TO_DATE or POSSIBLY_STALE
1558 // currently only ComputedValue will propagate POSSIBLY_STALE
1559 //
1560 // having this state is second big optimization:
1561 // don't have to recompute on every dependency change, but only when it's needed
1562 IDerivationState_[IDerivationState_["POSSIBLY_STALE_"] = 1] = "POSSIBLY_STALE_";
1563 // A shallow dependency has changed since last computation and the derivation
1564 // will need to recompute when it's needed next.
1565 IDerivationState_[IDerivationState_["STALE_"] = 2] = "STALE_";
1566})(IDerivationState_ || (IDerivationState_ = {}));
1567var TraceMode;
1568(function (TraceMode) {
1569 TraceMode[TraceMode["NONE"] = 0] = "NONE";
1570 TraceMode[TraceMode["LOG"] = 1] = "LOG";
1571 TraceMode[TraceMode["BREAK"] = 2] = "BREAK";
1572})(TraceMode || (TraceMode = {}));
1573var CaughtException = function CaughtException(cause) {
1574 this.cause = void 0;
1575 this.cause = cause;
1576 // Empty
1577};
1578
1579function isCaughtException(e) {
1580 return e instanceof CaughtException;
1581}
1582/**
1583 * Finds out whether any dependency of the derivation has actually changed.
1584 * If dependenciesState is 1 then it will recalculate dependencies,
1585 * if any dependency changed it will propagate it by changing dependenciesState to 2.
1586 *
1587 * By iterating over the dependencies in the same order that they were reported and
1588 * stopping on the first change, all the recalculations are only called for ComputedValues
1589 * that will be tracked by derivation. That is because we assume that if the first x
1590 * dependencies of the derivation doesn't change then the derivation should run the same way
1591 * up until accessing x-th dependency.
1592 */
1593function shouldCompute(derivation) {
1594 switch (derivation.dependenciesState_) {
1595 case IDerivationState_.UP_TO_DATE_:
1596 return false;
1597 case IDerivationState_.NOT_TRACKING_:
1598 case IDerivationState_.STALE_:
1599 return true;
1600 case IDerivationState_.POSSIBLY_STALE_:
1601 {
1602 // state propagation can occur outside of action/reactive context #2195
1603 var prevAllowStateReads = allowStateReadsStart(true);
1604 var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.
1605 var obs = derivation.observing_,
1606 l = obs.length;
1607 for (var i = 0; i < l; i++) {
1608 var obj = obs[i];
1609 if (isComputedValue(obj)) {
1610 if (globalState.disableErrorBoundaries) {
1611 obj.get();
1612 } else {
1613 try {
1614 obj.get();
1615 } catch (e) {
1616 // we are not interested in the value *or* exception at this moment, but if there is one, notify all
1617 untrackedEnd(prevUntracked);
1618 allowStateReadsEnd(prevAllowStateReads);
1619 return true;
1620 }
1621 }
1622 // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.
1623 // and `derivation` is an observer of `obj`
1624 // invariantShouldCompute(derivation)
1625 if (derivation.dependenciesState_ === IDerivationState_.STALE_) {
1626 untrackedEnd(prevUntracked);
1627 allowStateReadsEnd(prevAllowStateReads);
1628 return true;
1629 }
1630 }
1631 }
1632 changeDependenciesStateTo0(derivation);
1633 untrackedEnd(prevUntracked);
1634 allowStateReadsEnd(prevAllowStateReads);
1635 return false;
1636 }
1637 }
1638}
1639function isComputingDerivation() {
1640 return globalState.trackingDerivation !== null; // filter out actions inside computations
1641}
1642
1643function checkIfStateModificationsAreAllowed(atom) {
1644 var hasObservers = atom.observers_.size > 0;
1645 // Should not be possible to change observed state outside strict mode, except during initialization, see #563
1646 if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === "always")) {
1647 console.warn("[MobX] " + (globalState.enforceActions ? "Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: " : "Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: ") + atom.name_);
1648 }
1649}
1650function checkIfStateReadsAreAllowed(observable) {
1651 if ( !globalState.allowStateReads && globalState.observableRequiresReaction) {
1652 console.warn("[mobx] Observable '" + observable.name_ + "' being read outside a reactive context.");
1653 }
1654}
1655/**
1656 * Executes the provided function `f` and tracks which observables are being accessed.
1657 * The tracking information is stored on the `derivation` object and the derivation is registered
1658 * as observer of any of the accessed observables.
1659 */
1660function trackDerivedFunction(derivation, f, context) {
1661 var prevAllowStateReads = allowStateReadsStart(true);
1662 // pre allocate array allocation + room for variation in deps
1663 // array will be trimmed by bindDependencies
1664 changeDependenciesStateTo0(derivation);
1665 derivation.newObserving_ = new Array(derivation.observing_.length + 100);
1666 derivation.unboundDepsCount_ = 0;
1667 derivation.runId_ = ++globalState.runId;
1668 var prevTracking = globalState.trackingDerivation;
1669 globalState.trackingDerivation = derivation;
1670 globalState.inBatch++;
1671 var result;
1672 if (globalState.disableErrorBoundaries === true) {
1673 result = f.call(context);
1674 } else {
1675 try {
1676 result = f.call(context);
1677 } catch (e) {
1678 result = new CaughtException(e);
1679 }
1680 }
1681 globalState.inBatch--;
1682 globalState.trackingDerivation = prevTracking;
1683 bindDependencies(derivation);
1684 warnAboutDerivationWithoutDependencies(derivation);
1685 allowStateReadsEnd(prevAllowStateReads);
1686 return result;
1687}
1688function warnAboutDerivationWithoutDependencies(derivation) {
1689 if (derivation.observing_.length !== 0) {
1690 return;
1691 }
1692 if (typeof derivation.requiresObservable_ === "boolean" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {
1693 console.warn("[mobx] Derivation '" + derivation.name_ + "' is created/updated without reading any observable value.");
1694 }
1695}
1696/**
1697 * diffs newObserving with observing.
1698 * update observing to be newObserving with unique observables
1699 * notify observers that become observed/unobserved
1700 */
1701function bindDependencies(derivation) {
1702 // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1");
1703 var prevObserving = derivation.observing_;
1704 var observing = derivation.observing_ = derivation.newObserving_;
1705 var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_;
1706 // Go through all new observables and check diffValue: (this list can contain duplicates):
1707 // 0: first occurrence, change to 1 and keep it
1708 // 1: extra occurrence, drop it
1709 var i0 = 0,
1710 l = derivation.unboundDepsCount_;
1711 for (var i = 0; i < l; i++) {
1712 var dep = observing[i];
1713 if (dep.diffValue_ === 0) {
1714 dep.diffValue_ = 1;
1715 if (i0 !== i) {
1716 observing[i0] = dep;
1717 }
1718 i0++;
1719 }
1720 // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,
1721 // not hitting the condition
1722 if (dep.dependenciesState_ > lowestNewObservingDerivationState) {
1723 lowestNewObservingDerivationState = dep.dependenciesState_;
1724 }
1725 }
1726 observing.length = i0;
1727 derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)
1728 // Go through all old observables and check diffValue: (it is unique after last bindDependencies)
1729 // 0: it's not in new observables, unobserve it
1730 // 1: it keeps being observed, don't want to notify it. change to 0
1731 l = prevObserving.length;
1732 while (l--) {
1733 var _dep = prevObserving[l];
1734 if (_dep.diffValue_ === 0) {
1735 removeObserver(_dep, derivation);
1736 }
1737 _dep.diffValue_ = 0;
1738 }
1739 // Go through all new observables and check diffValue: (now it should be unique)
1740 // 0: it was set to 0 in last loop. don't need to do anything.
1741 // 1: it wasn't observed, let's observe it. set back to 0
1742 while (i0--) {
1743 var _dep2 = observing[i0];
1744 if (_dep2.diffValue_ === 1) {
1745 _dep2.diffValue_ = 0;
1746 addObserver(_dep2, derivation);
1747 }
1748 }
1749 // Some new observed derivations may become stale during this derivation computation
1750 // so they have had no chance to propagate staleness (#916)
1751 if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {
1752 derivation.dependenciesState_ = lowestNewObservingDerivationState;
1753 derivation.onBecomeStale_();
1754 }
1755}
1756function clearObserving(derivation) {
1757 // invariant(globalState.inBatch > 0, "INTERNAL ERROR clearObserving should be called only inside batch");
1758 var obs = derivation.observing_;
1759 derivation.observing_ = [];
1760 var i = obs.length;
1761 while (i--) {
1762 removeObserver(obs[i], derivation);
1763 }
1764 derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;
1765}
1766function untracked(action) {
1767 var prev = untrackedStart();
1768 try {
1769 return action();
1770 } finally {
1771 untrackedEnd(prev);
1772 }
1773}
1774function untrackedStart() {
1775 var prev = globalState.trackingDerivation;
1776 globalState.trackingDerivation = null;
1777 return prev;
1778}
1779function untrackedEnd(prev) {
1780 globalState.trackingDerivation = prev;
1781}
1782function allowStateReadsStart(allowStateReads) {
1783 var prev = globalState.allowStateReads;
1784 globalState.allowStateReads = allowStateReads;
1785 return prev;
1786}
1787function allowStateReadsEnd(prev) {
1788 globalState.allowStateReads = prev;
1789}
1790/**
1791 * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0
1792 *
1793 */
1794function changeDependenciesStateTo0(derivation) {
1795 if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {
1796 return;
1797 }
1798 derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;
1799 var obs = derivation.observing_;
1800 var i = obs.length;
1801 while (i--) {
1802 obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;
1803 }
1804}
1805
1806/**
1807 * These values will persist if global state is reset
1808 */
1809var persistentKeys = ["mobxGuid", "spyListeners", "enforceActions", "computedRequiresReaction", "reactionRequiresObservable", "observableRequiresReaction", "allowStateReads", "disableErrorBoundaries", "runId", "UNCHANGED", "useProxies"];
1810var MobXGlobals = function MobXGlobals() {
1811 this.version = 6;
1812 this.UNCHANGED = {};
1813 this.trackingDerivation = null;
1814 this.trackingContext = null;
1815 this.runId = 0;
1816 this.mobxGuid = 0;
1817 this.inBatch = 0;
1818 this.pendingUnobservations = [];
1819 this.pendingReactions = [];
1820 this.isRunningReactions = false;
1821 this.allowStateChanges = false;
1822 this.allowStateReads = true;
1823 this.enforceActions = true;
1824 this.spyListeners = [];
1825 this.globalReactionErrorHandlers = [];
1826 this.computedRequiresReaction = false;
1827 this.reactionRequiresObservable = false;
1828 this.observableRequiresReaction = false;
1829 this.disableErrorBoundaries = false;
1830 this.suppressReactionErrors = false;
1831 this.useProxies = true;
1832 this.verifyProxies = false;
1833 this.safeDescriptors = true;
1834 this.stateVersion = Number.MIN_SAFE_INTEGER;
1835};
1836var canMergeGlobalState = true;
1837var isolateCalled = false;
1838var globalState = /*#__PURE__*/function () {
1839 var global = /*#__PURE__*/getGlobal();
1840 if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {
1841 canMergeGlobalState = false;
1842 }
1843 if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {
1844 canMergeGlobalState = false;
1845 }
1846 if (!canMergeGlobalState) {
1847 // Because this is a IIFE we need to let isolateCalled a chance to change
1848 // so we run it after the event loop completed at least 1 iteration
1849 setTimeout(function () {
1850 if (!isolateCalled) {
1851 die(35);
1852 }
1853 }, 1);
1854 return new MobXGlobals();
1855 } else if (global.__mobxGlobals) {
1856 global.__mobxInstanceCount += 1;
1857 if (!global.__mobxGlobals.UNCHANGED) {
1858 global.__mobxGlobals.UNCHANGED = {};
1859 } // make merge backward compatible
1860 return global.__mobxGlobals;
1861 } else {
1862 global.__mobxInstanceCount = 1;
1863 return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();
1864 }
1865}();
1866function isolateGlobalState() {
1867 if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {
1868 die(36);
1869 }
1870 isolateCalled = true;
1871 if (canMergeGlobalState) {
1872 var global = getGlobal();
1873 if (--global.__mobxInstanceCount === 0) {
1874 global.__mobxGlobals = undefined;
1875 }
1876 globalState = new MobXGlobals();
1877 }
1878}
1879function getGlobalState() {
1880 return globalState;
1881}
1882/**
1883 * For testing purposes only; this will break the internal state of existing observables,
1884 * but can be used to get back at a stable state after throwing errors
1885 */
1886function resetGlobalState() {
1887 var defaultGlobals = new MobXGlobals();
1888 for (var key in defaultGlobals) {
1889 if (persistentKeys.indexOf(key) === -1) {
1890 globalState[key] = defaultGlobals[key];
1891 }
1892 }
1893 globalState.allowStateChanges = !globalState.enforceActions;
1894}
1895
1896function hasObservers(observable) {
1897 return observable.observers_ && observable.observers_.size > 0;
1898}
1899function getObservers(observable) {
1900 return observable.observers_;
1901}
1902// function invariantObservers(observable: IObservable) {
1903// const list = observable.observers
1904// const map = observable.observersIndexes
1905// const l = list.length
1906// for (let i = 0; i < l; i++) {
1907// const id = list[i].__mapid
1908// if (i) {
1909// invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list") // for performance
1910// } else {
1911// invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldn't be held in map.") // for performance
1912// }
1913// }
1914// invariant(
1915// list.length === 0 || Object.keys(map).length === list.length - 1,
1916// "INTERNAL ERROR there is no junk in map"
1917// )
1918// }
1919function addObserver(observable, node) {
1920 // invariant(node.dependenciesState !== -1, "INTERNAL ERROR, can add only dependenciesState !== -1");
1921 // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR add already added node");
1922 // invariantObservers(observable);
1923 observable.observers_.add(node);
1924 if (observable.lowestObserverState_ > node.dependenciesState_) {
1925 observable.lowestObserverState_ = node.dependenciesState_;
1926 }
1927 // invariantObservers(observable);
1928 // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR didn't add node");
1929}
1930
1931function removeObserver(observable, node) {
1932 // invariant(globalState.inBatch > 0, "INTERNAL ERROR, remove should be called only inside batch");
1933 // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR remove already removed node");
1934 // invariantObservers(observable);
1935 observable.observers_["delete"](node);
1936 if (observable.observers_.size === 0) {
1937 // deleting last observer
1938 queueForUnobservation(observable);
1939 }
1940 // invariantObservers(observable);
1941 // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR remove already removed node2");
1942}
1943
1944function queueForUnobservation(observable) {
1945 if (observable.isPendingUnobservation_ === false) {
1946 // invariant(observable._observers.length === 0, "INTERNAL ERROR, should only queue for unobservation unobserved observables");
1947 observable.isPendingUnobservation_ = true;
1948 globalState.pendingUnobservations.push(observable);
1949 }
1950}
1951/**
1952 * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.
1953 * During a batch `onBecomeUnobserved` will be called at most once per observable.
1954 * Avoids unnecessary recalculations.
1955 */
1956function startBatch() {
1957 globalState.inBatch++;
1958}
1959function endBatch() {
1960 if (--globalState.inBatch === 0) {
1961 runReactions();
1962 // the batch is actually about to finish, all unobserving should happen here.
1963 var list = globalState.pendingUnobservations;
1964 for (var i = 0; i < list.length; i++) {
1965 var observable = list[i];
1966 observable.isPendingUnobservation_ = false;
1967 if (observable.observers_.size === 0) {
1968 if (observable.isBeingObserved_) {
1969 // if this observable had reactive observers, trigger the hooks
1970 observable.isBeingObserved_ = false;
1971 observable.onBUO();
1972 }
1973 if (observable instanceof ComputedValue) {
1974 // computed values are automatically teared down when the last observer leaves
1975 // this process happens recursively, this computed might be the last observabe of another, etc..
1976 observable.suspend_();
1977 }
1978 }
1979 }
1980 globalState.pendingUnobservations = [];
1981 }
1982}
1983function reportObserved(observable) {
1984 checkIfStateReadsAreAllowed(observable);
1985 var derivation = globalState.trackingDerivation;
1986 if (derivation !== null) {
1987 /**
1988 * Simple optimization, give each derivation run an unique id (runId)
1989 * Check if last time this observable was accessed the same runId is used
1990 * if this is the case, the relation is already known
1991 */
1992 if (derivation.runId_ !== observable.lastAccessedBy_) {
1993 observable.lastAccessedBy_ = derivation.runId_;
1994 // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...
1995 derivation.newObserving_[derivation.unboundDepsCount_++] = observable;
1996 if (!observable.isBeingObserved_ && globalState.trackingContext) {
1997 observable.isBeingObserved_ = true;
1998 observable.onBO();
1999 }
2000 }
2001 return observable.isBeingObserved_;
2002 } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {
2003 queueForUnobservation(observable);
2004 }
2005 return false;
2006}
2007// function invariantLOS(observable: IObservable, msg: string) {
2008// // it's expensive so better not run it in produciton. but temporarily helpful for testing
2009// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)
2010// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`
2011// throw new Error(
2012// "lowestObserverState is wrong for " +
2013// msg +
2014// " because " +
2015// min +
2016// " < " +
2017// observable.lowestObserverState
2018// )
2019// }
2020/**
2021 * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly
2022 * It will propagate changes to observers from previous run
2023 * It's hard or maybe impossible (with reasonable perf) to get it right with current approach
2024 * Hopefully self reruning autoruns aren't a feature people should depend on
2025 * Also most basic use cases should be ok
2026 */
2027// Called by Atom when its value changes
2028function propagateChanged(observable) {
2029 // invariantLOS(observable, "changed start");
2030 if (observable.lowestObserverState_ === IDerivationState_.STALE_) {
2031 return;
2032 }
2033 observable.lowestObserverState_ = IDerivationState_.STALE_;
2034 // Ideally we use for..of here, but the downcompiled version is really slow...
2035 observable.observers_.forEach(function (d) {
2036 if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {
2037 if ( d.isTracing_ !== TraceMode.NONE) {
2038 logTraceInfo(d, observable);
2039 }
2040 d.onBecomeStale_();
2041 }
2042 d.dependenciesState_ = IDerivationState_.STALE_;
2043 });
2044 // invariantLOS(observable, "changed end");
2045}
2046// Called by ComputedValue when it recalculate and its value changed
2047function propagateChangeConfirmed(observable) {
2048 // invariantLOS(observable, "confirmed start");
2049 if (observable.lowestObserverState_ === IDerivationState_.STALE_) {
2050 return;
2051 }
2052 observable.lowestObserverState_ = IDerivationState_.STALE_;
2053 observable.observers_.forEach(function (d) {
2054 if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {
2055 d.dependenciesState_ = IDerivationState_.STALE_;
2056 if ( d.isTracing_ !== TraceMode.NONE) {
2057 logTraceInfo(d, observable);
2058 }
2059 } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.
2060 ) {
2061 observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;
2062 }
2063 });
2064 // invariantLOS(observable, "confirmed end");
2065}
2066// Used by computed when its dependency changed, but we don't wan't to immediately recompute.
2067function propagateMaybeChanged(observable) {
2068 // invariantLOS(observable, "maybe start");
2069 if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {
2070 return;
2071 }
2072 observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;
2073 observable.observers_.forEach(function (d) {
2074 if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {
2075 d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;
2076 d.onBecomeStale_();
2077 }
2078 });
2079 // invariantLOS(observable, "maybe end");
2080}
2081
2082function logTraceInfo(derivation, observable) {
2083 console.log("[mobx.trace] '" + derivation.name_ + "' is invalidated due to a change in: '" + observable.name_ + "'");
2084 if (derivation.isTracing_ === TraceMode.BREAK) {
2085 var lines = [];
2086 printDepTree(getDependencyTree(derivation), lines, 1);
2087 // prettier-ignore
2088 new Function("debugger;\n/*\nTracing '" + derivation.name_ + "'\n\nYou are entering this break point because derivation '" + derivation.name_ + "' is being traced and '" + observable.name_ + "' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\//g, "/") : "") + "\n\nThe dependencies for this derivation are:\n\n" + lines.join("\n") + "\n*/\n ")();
2089 }
2090}
2091function printDepTree(tree, lines, depth) {
2092 if (lines.length >= 1000) {
2093 lines.push("(and many more)");
2094 return;
2095 }
2096 lines.push("" + "\t".repeat(depth - 1) + tree.name);
2097 if (tree.dependencies) {
2098 tree.dependencies.forEach(function (child) {
2099 return printDepTree(child, lines, depth + 1);
2100 });
2101 }
2102}
2103
2104var Reaction = /*#__PURE__*/function () {
2105 // nodes we are looking at. Our value depends on these nodes
2106
2107 function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {
2108 if (name_ === void 0) {
2109 name_ = "Reaction@" + getNextId() ;
2110 }
2111 this.name_ = void 0;
2112 this.onInvalidate_ = void 0;
2113 this.errorHandler_ = void 0;
2114 this.requiresObservable_ = void 0;
2115 this.observing_ = [];
2116 this.newObserving_ = [];
2117 this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;
2118 this.diffValue_ = 0;
2119 this.runId_ = 0;
2120 this.unboundDepsCount_ = 0;
2121 this.isDisposed_ = false;
2122 this.isScheduled_ = false;
2123 this.isTrackPending_ = false;
2124 this.isRunning_ = false;
2125 this.isTracing_ = TraceMode.NONE;
2126 this.name_ = name_;
2127 this.onInvalidate_ = onInvalidate_;
2128 this.errorHandler_ = errorHandler_;
2129 this.requiresObservable_ = requiresObservable_;
2130 }
2131 var _proto = Reaction.prototype;
2132 _proto.onBecomeStale_ = function onBecomeStale_() {
2133 this.schedule_();
2134 };
2135 _proto.schedule_ = function schedule_() {
2136 if (!this.isScheduled_) {
2137 this.isScheduled_ = true;
2138 globalState.pendingReactions.push(this);
2139 runReactions();
2140 }
2141 };
2142 _proto.isScheduled = function isScheduled() {
2143 return this.isScheduled_;
2144 }
2145 /**
2146 * internal, use schedule() if you intend to kick off a reaction
2147 */;
2148 _proto.runReaction_ = function runReaction_() {
2149 if (!this.isDisposed_) {
2150 startBatch();
2151 this.isScheduled_ = false;
2152 var prev = globalState.trackingContext;
2153 globalState.trackingContext = this;
2154 if (shouldCompute(this)) {
2155 this.isTrackPending_ = true;
2156 try {
2157 this.onInvalidate_();
2158 if ("development" !== "production" && this.isTrackPending_ && isSpyEnabled()) {
2159 // onInvalidate didn't trigger track right away..
2160 spyReport({
2161 name: this.name_,
2162 type: "scheduled-reaction"
2163 });
2164 }
2165 } catch (e) {
2166 this.reportExceptionInDerivation_(e);
2167 }
2168 }
2169 globalState.trackingContext = prev;
2170 endBatch();
2171 }
2172 };
2173 _proto.track = function track(fn) {
2174 if (this.isDisposed_) {
2175 return;
2176 // console.warn("Reaction already disposed") // Note: Not a warning / error in mobx 4 either
2177 }
2178
2179 startBatch();
2180 var notify = isSpyEnabled();
2181 var startTime;
2182 if ( notify) {
2183 startTime = Date.now();
2184 spyReportStart({
2185 name: this.name_,
2186 type: "reaction"
2187 });
2188 }
2189 this.isRunning_ = true;
2190 var prevReaction = globalState.trackingContext; // reactions could create reactions...
2191 globalState.trackingContext = this;
2192 var result = trackDerivedFunction(this, fn, undefined);
2193 globalState.trackingContext = prevReaction;
2194 this.isRunning_ = false;
2195 this.isTrackPending_ = false;
2196 if (this.isDisposed_) {
2197 // disposed during last run. Clean up everything that was bound after the dispose call.
2198 clearObserving(this);
2199 }
2200 if (isCaughtException(result)) {
2201 this.reportExceptionInDerivation_(result.cause);
2202 }
2203 if ( notify) {
2204 spyReportEnd({
2205 time: Date.now() - startTime
2206 });
2207 }
2208 endBatch();
2209 };
2210 _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {
2211 var _this = this;
2212 if (this.errorHandler_) {
2213 this.errorHandler_(error, this);
2214 return;
2215 }
2216 if (globalState.disableErrorBoundaries) {
2217 throw error;
2218 }
2219 var message = "[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '" + this + "'" ;
2220 if (!globalState.suppressReactionErrors) {
2221 console.error(message, error);
2222 /** If debugging brought you here, please, read the above message :-). Tnx! */
2223 } else {
2224 console.warn("[mobx] (error in reaction '" + this.name_ + "' suppressed, fix error of causing action below)");
2225 } // prettier-ignore
2226 if ( isSpyEnabled()) {
2227 spyReport({
2228 type: "error",
2229 name: this.name_,
2230 message: message,
2231 error: "" + error
2232 });
2233 }
2234 globalState.globalReactionErrorHandlers.forEach(function (f) {
2235 return f(error, _this);
2236 });
2237 };
2238 _proto.dispose = function dispose() {
2239 if (!this.isDisposed_) {
2240 this.isDisposed_ = true;
2241 if (!this.isRunning_) {
2242 // if disposed while running, clean up later. Maybe not optimal, but rare case
2243 startBatch();
2244 clearObserving(this);
2245 endBatch();
2246 }
2247 }
2248 };
2249 _proto.getDisposer_ = function getDisposer_(abortSignal) {
2250 var _this2 = this;
2251 var dispose = function dispose() {
2252 _this2.dispose();
2253 abortSignal == null ? void 0 : abortSignal.removeEventListener == null ? void 0 : abortSignal.removeEventListener("abort", dispose);
2254 };
2255 abortSignal == null ? void 0 : abortSignal.addEventListener == null ? void 0 : abortSignal.addEventListener("abort", dispose);
2256 dispose[$mobx] = this;
2257 return dispose;
2258 };
2259 _proto.toString = function toString() {
2260 return "Reaction[" + this.name_ + "]";
2261 };
2262 _proto.trace = function trace$1(enterBreakPoint) {
2263 if (enterBreakPoint === void 0) {
2264 enterBreakPoint = false;
2265 }
2266 trace(this, enterBreakPoint);
2267 };
2268 return Reaction;
2269}();
2270function onReactionError(handler) {
2271 globalState.globalReactionErrorHandlers.push(handler);
2272 return function () {
2273 var idx = globalState.globalReactionErrorHandlers.indexOf(handler);
2274 if (idx >= 0) {
2275 globalState.globalReactionErrorHandlers.splice(idx, 1);
2276 }
2277 };
2278}
2279/**
2280 * Magic number alert!
2281 * Defines within how many times a reaction is allowed to re-trigger itself
2282 * until it is assumed that this is gonna be a never ending loop...
2283 */
2284var MAX_REACTION_ITERATIONS = 100;
2285var reactionScheduler = function reactionScheduler(f) {
2286 return f();
2287};
2288function runReactions() {
2289 // Trampolining, if runReactions are already running, new reactions will be picked up
2290 if (globalState.inBatch > 0 || globalState.isRunningReactions) {
2291 return;
2292 }
2293 reactionScheduler(runReactionsHelper);
2294}
2295function runReactionsHelper() {
2296 globalState.isRunningReactions = true;
2297 var allReactions = globalState.pendingReactions;
2298 var iterations = 0;
2299 // While running reactions, new reactions might be triggered.
2300 // Hence we work with two variables and check whether
2301 // we converge to no remaining reactions after a while.
2302 while (allReactions.length > 0) {
2303 if (++iterations === MAX_REACTION_ITERATIONS) {
2304 console.error( "Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations." + (" Probably there is a cycle in the reactive function: " + allReactions[0]) );
2305 allReactions.splice(0); // clear reactions
2306 }
2307
2308 var remainingReactions = allReactions.splice(0);
2309 for (var i = 0, l = remainingReactions.length; i < l; i++) {
2310 remainingReactions[i].runReaction_();
2311 }
2312 }
2313 globalState.isRunningReactions = false;
2314}
2315var isReaction = /*#__PURE__*/createInstanceofPredicate("Reaction", Reaction);
2316function setReactionScheduler(fn) {
2317 var baseScheduler = reactionScheduler;
2318 reactionScheduler = function reactionScheduler(f) {
2319 return fn(function () {
2320 return baseScheduler(f);
2321 });
2322 };
2323}
2324
2325function isSpyEnabled() {
2326 return !!globalState.spyListeners.length;
2327}
2328function spyReport(event) {
2329 if (!globalState.spyListeners.length) {
2330 return;
2331 }
2332 var listeners = globalState.spyListeners;
2333 for (var i = 0, l = listeners.length; i < l; i++) {
2334 listeners[i](event);
2335 }
2336}
2337function spyReportStart(event) {
2338 var change = _extends({}, event, {
2339 spyReportStart: true
2340 });
2341 spyReport(change);
2342}
2343var END_EVENT = {
2344 type: "report-end",
2345 spyReportEnd: true
2346};
2347function spyReportEnd(change) {
2348 if (change) {
2349 spyReport(_extends({}, change, {
2350 type: "report-end",
2351 spyReportEnd: true
2352 }));
2353 } else {
2354 spyReport(END_EVENT);
2355 }
2356}
2357function spy(listener) {
2358 {
2359 globalState.spyListeners.push(listener);
2360 return once(function () {
2361 globalState.spyListeners = globalState.spyListeners.filter(function (l) {
2362 return l !== listener;
2363 });
2364 });
2365 }
2366}
2367
2368var ACTION = "action";
2369var ACTION_BOUND = "action.bound";
2370var AUTOACTION = "autoAction";
2371var AUTOACTION_BOUND = "autoAction.bound";
2372var DEFAULT_ACTION_NAME = "<unnamed action>";
2373var actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);
2374var actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {
2375 bound: true
2376});
2377var autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {
2378 autoAction: true
2379});
2380var autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {
2381 autoAction: true,
2382 bound: true
2383});
2384function createActionFactory(autoAction) {
2385 var res = function action(arg1, arg2) {
2386 // action(fn() {})
2387 if (isFunction(arg1)) {
2388 return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);
2389 }
2390 // action("name", fn() {})
2391 if (isFunction(arg2)) {
2392 return createAction(arg1, arg2, autoAction);
2393 }
2394 // @action
2395 if (isStringish(arg2)) {
2396 return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);
2397 }
2398 // action("name") & @action("name")
2399 if (isStringish(arg1)) {
2400 return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {
2401 name: arg1,
2402 autoAction: autoAction
2403 }));
2404 }
2405 {
2406 die("Invalid arguments for `action`");
2407 }
2408 };
2409 return res;
2410}
2411var action = /*#__PURE__*/createActionFactory(false);
2412Object.assign(action, actionAnnotation);
2413var autoAction = /*#__PURE__*/createActionFactory(true);
2414Object.assign(autoAction, autoActionAnnotation);
2415action.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);
2416autoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);
2417function runInAction(fn) {
2418 return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);
2419}
2420function isAction(thing) {
2421 return isFunction(thing) && thing.isMobxAction === true;
2422}
2423
2424/**
2425 * Creates a named reactive view and keeps it alive, so that the view is always
2426 * updated if one of the dependencies changes, even when the view is not further used by something else.
2427 * @param view The reactive view
2428 * @returns disposer function, which can be used to stop the view from being updated in the future.
2429 */
2430function autorun(view, opts) {
2431 var _opts$name, _opts, _opts2, _opts2$signal, _opts3;
2432 if (opts === void 0) {
2433 opts = EMPTY_OBJECT;
2434 }
2435 {
2436 if (!isFunction(view)) {
2437 die("Autorun expects a function as first argument");
2438 }
2439 if (isAction(view)) {
2440 die("Autorun does not accept actions since actions are untrackable");
2441 }
2442 }
2443 var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : view.name || "Autorun@" + getNextId() ;
2444 var runSync = !opts.scheduler && !opts.delay;
2445 var reaction;
2446 if (runSync) {
2447 // normal autorun
2448 reaction = new Reaction(name, function () {
2449 this.track(reactionRunner);
2450 }, opts.onError, opts.requiresObservable);
2451 } else {
2452 var scheduler = createSchedulerFromOptions(opts);
2453 // debounced autorun
2454 var isScheduled = false;
2455 reaction = new Reaction(name, function () {
2456 if (!isScheduled) {
2457 isScheduled = true;
2458 scheduler(function () {
2459 isScheduled = false;
2460 if (!reaction.isDisposed_) {
2461 reaction.track(reactionRunner);
2462 }
2463 });
2464 }
2465 }, opts.onError, opts.requiresObservable);
2466 }
2467 function reactionRunner() {
2468 view(reaction);
2469 }
2470 if (!((_opts2 = opts) != null && (_opts2$signal = _opts2.signal) != null && _opts2$signal.aborted)) {
2471 reaction.schedule_();
2472 }
2473 return reaction.getDisposer_((_opts3 = opts) == null ? void 0 : _opts3.signal);
2474}
2475var run = function run(f) {
2476 return f();
2477};
2478function createSchedulerFromOptions(opts) {
2479 return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {
2480 return setTimeout(f, opts.delay);
2481 } : run;
2482}
2483function reaction(expression, effect, opts) {
2484 var _opts$name2, _opts4, _opts4$signal, _opts5;
2485 if (opts === void 0) {
2486 opts = EMPTY_OBJECT;
2487 }
2488 {
2489 if (!isFunction(expression) || !isFunction(effect)) {
2490 die("First and second argument to reaction should be functions");
2491 }
2492 if (!isPlainObject(opts)) {
2493 die("Third argument of reactions should be an object");
2494 }
2495 }
2496 var name = (_opts$name2 = opts.name) != null ? _opts$name2 : "Reaction@" + getNextId() ;
2497 var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);
2498 var runSync = !opts.scheduler && !opts.delay;
2499 var scheduler = createSchedulerFromOptions(opts);
2500 var firstTime = true;
2501 var isScheduled = false;
2502 var value;
2503 var oldValue;
2504 var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer["default"];
2505 var r = new Reaction(name, function () {
2506 if (firstTime || runSync) {
2507 reactionRunner();
2508 } else if (!isScheduled) {
2509 isScheduled = true;
2510 scheduler(reactionRunner);
2511 }
2512 }, opts.onError, opts.requiresObservable);
2513 function reactionRunner() {
2514 isScheduled = false;
2515 if (r.isDisposed_) {
2516 return;
2517 }
2518 var changed = false;
2519 r.track(function () {
2520 var nextValue = allowStateChanges(false, function () {
2521 return expression(r);
2522 });
2523 changed = firstTime || !equals(value, nextValue);
2524 oldValue = value;
2525 value = nextValue;
2526 });
2527 if (firstTime && opts.fireImmediately) {
2528 effectAction(value, oldValue, r);
2529 } else if (!firstTime && changed) {
2530 effectAction(value, oldValue, r);
2531 }
2532 firstTime = false;
2533 }
2534 if (!((_opts4 = opts) != null && (_opts4$signal = _opts4.signal) != null && _opts4$signal.aborted)) {
2535 r.schedule_();
2536 }
2537 return r.getDisposer_((_opts5 = opts) == null ? void 0 : _opts5.signal);
2538}
2539function wrapErrorHandler(errorHandler, baseFn) {
2540 return function () {
2541 try {
2542 return baseFn.apply(this, arguments);
2543 } catch (e) {
2544 errorHandler.call(this, e);
2545 }
2546 };
2547}
2548
2549var ON_BECOME_OBSERVED = "onBO";
2550var ON_BECOME_UNOBSERVED = "onBUO";
2551function onBecomeObserved(thing, arg2, arg3) {
2552 return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);
2553}
2554function onBecomeUnobserved(thing, arg2, arg3) {
2555 return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);
2556}
2557function interceptHook(hook, thing, arg2, arg3) {
2558 var atom = typeof arg3 === "function" ? getAtom(thing, arg2) : getAtom(thing);
2559 var cb = isFunction(arg3) ? arg3 : arg2;
2560 var listenersKey = hook + "L";
2561 if (atom[listenersKey]) {
2562 atom[listenersKey].add(cb);
2563 } else {
2564 atom[listenersKey] = new Set([cb]);
2565 }
2566 return function () {
2567 var hookListeners = atom[listenersKey];
2568 if (hookListeners) {
2569 hookListeners["delete"](cb);
2570 if (hookListeners.size === 0) {
2571 delete atom[listenersKey];
2572 }
2573 }
2574 };
2575}
2576
2577var NEVER = "never";
2578var ALWAYS = "always";
2579var OBSERVED = "observed";
2580// const IF_AVAILABLE = "ifavailable"
2581function configure(options) {
2582 if (options.isolateGlobalState === true) {
2583 isolateGlobalState();
2584 }
2585 var useProxies = options.useProxies,
2586 enforceActions = options.enforceActions;
2587 if (useProxies !== undefined) {
2588 globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== "undefined";
2589 }
2590 if (useProxies === "ifavailable") {
2591 globalState.verifyProxies = true;
2592 }
2593 if (enforceActions !== undefined) {
2594 var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;
2595 globalState.enforceActions = ea;
2596 globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;
2597 }
2598 ["computedRequiresReaction", "reactionRequiresObservable", "observableRequiresReaction", "disableErrorBoundaries", "safeDescriptors"].forEach(function (key) {
2599 if (key in options) {
2600 globalState[key] = !!options[key];
2601 }
2602 });
2603 globalState.allowStateReads = !globalState.observableRequiresReaction;
2604 if ( globalState.disableErrorBoundaries === true) {
2605 console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.");
2606 }
2607 if (options.reactionScheduler) {
2608 setReactionScheduler(options.reactionScheduler);
2609 }
2610}
2611
2612function extendObservable(target, properties, annotations, options) {
2613 {
2614 if (arguments.length > 4) {
2615 die("'extendObservable' expected 2-4 arguments");
2616 }
2617 if (typeof target !== "object") {
2618 die("'extendObservable' expects an object as first argument");
2619 }
2620 if (isObservableMap(target)) {
2621 die("'extendObservable' should not be used on maps, use map.merge instead");
2622 }
2623 if (!isPlainObject(properties)) {
2624 die("'extendObservable' only accepts plain objects as second argument");
2625 }
2626 if (isObservable(properties) || isObservable(annotations)) {
2627 die("Extending an object with another observable (object) is not supported");
2628 }
2629 }
2630 // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)
2631 var descriptors = getOwnPropertyDescriptors(properties);
2632 var adm = asObservableObject(target, options)[$mobx];
2633 startBatch();
2634 try {
2635 ownKeys(descriptors).forEach(function (key) {
2636 adm.extend_(key, descriptors[key],
2637 // must pass "undefined" for { key: undefined }
2638 !annotations ? true : key in annotations ? annotations[key] : true);
2639 });
2640 } finally {
2641 endBatch();
2642 }
2643 return target;
2644}
2645
2646function getDependencyTree(thing, property) {
2647 return nodeToDependencyTree(getAtom(thing, property));
2648}
2649function nodeToDependencyTree(node) {
2650 var result = {
2651 name: node.name_
2652 };
2653 if (node.observing_ && node.observing_.length > 0) {
2654 result.dependencies = unique(node.observing_).map(nodeToDependencyTree);
2655 }
2656 return result;
2657}
2658function getObserverTree(thing, property) {
2659 return nodeToObserverTree(getAtom(thing, property));
2660}
2661function nodeToObserverTree(node) {
2662 var result = {
2663 name: node.name_
2664 };
2665 if (hasObservers(node)) {
2666 result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);
2667 }
2668 return result;
2669}
2670function unique(list) {
2671 return Array.from(new Set(list));
2672}
2673
2674var generatorId = 0;
2675function FlowCancellationError() {
2676 this.message = "FLOW_CANCELLED";
2677}
2678FlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);
2679function isFlowCancellationError(error) {
2680 return error instanceof FlowCancellationError;
2681}
2682var flowAnnotation = /*#__PURE__*/createFlowAnnotation("flow");
2683var flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation("flow.bound", {
2684 bound: true
2685});
2686var flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {
2687 // @flow
2688 if (isStringish(arg2)) {
2689 return storeAnnotation(arg1, arg2, flowAnnotation);
2690 }
2691 // flow(fn)
2692 if ( arguments.length !== 1) {
2693 die("Flow expects single argument with generator function");
2694 }
2695 var generator = arg1;
2696 var name = generator.name || "<unnamed flow>";
2697 // Implementation based on https://github.com/tj/co/blob/master/index.js
2698 var res = function res() {
2699 var ctx = this;
2700 var args = arguments;
2701 var runId = ++generatorId;
2702 var gen = action(name + " - runid: " + runId + " - init", generator).apply(ctx, args);
2703 var rejector;
2704 var pendingPromise = undefined;
2705 var promise = new Promise(function (resolve, reject) {
2706 var stepId = 0;
2707 rejector = reject;
2708 function onFulfilled(res) {
2709 pendingPromise = undefined;
2710 var ret;
2711 try {
2712 ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.next).call(gen, res);
2713 } catch (e) {
2714 return reject(e);
2715 }
2716 next(ret);
2717 }
2718 function onRejected(err) {
2719 pendingPromise = undefined;
2720 var ret;
2721 try {
2722 ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen["throw"]).call(gen, err);
2723 } catch (e) {
2724 return reject(e);
2725 }
2726 next(ret);
2727 }
2728 function next(ret) {
2729 if (isFunction(ret == null ? void 0 : ret.then)) {
2730 // an async iterator
2731 ret.then(next, reject);
2732 return;
2733 }
2734 if (ret.done) {
2735 return resolve(ret.value);
2736 }
2737 pendingPromise = Promise.resolve(ret.value);
2738 return pendingPromise.then(onFulfilled, onRejected);
2739 }
2740 onFulfilled(undefined); // kick off the process
2741 });
2742
2743 promise.cancel = action(name + " - runid: " + runId + " - cancel", function () {
2744 try {
2745 if (pendingPromise) {
2746 cancelPromise(pendingPromise);
2747 }
2748 // Finally block can return (or yield) stuff..
2749 var _res = gen["return"](undefined);
2750 // eat anything that promise would do, it's cancelled!
2751 var yieldedPromise = Promise.resolve(_res.value);
2752 yieldedPromise.then(noop, noop);
2753 cancelPromise(yieldedPromise); // maybe it can be cancelled :)
2754 // reject our original promise
2755 rejector(new FlowCancellationError());
2756 } catch (e) {
2757 rejector(e); // there could be a throwing finally block
2758 }
2759 });
2760
2761 return promise;
2762 };
2763 res.isMobXFlow = true;
2764 return res;
2765}, flowAnnotation);
2766flow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);
2767function cancelPromise(promise) {
2768 if (isFunction(promise.cancel)) {
2769 promise.cancel();
2770 }
2771}
2772function flowResult(result) {
2773 return result; // just tricking TypeScript :)
2774}
2775
2776function isFlow(fn) {
2777 return (fn == null ? void 0 : fn.isMobXFlow) === true;
2778}
2779
2780function interceptReads(thing, propOrHandler, handler) {
2781 var target;
2782 if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {
2783 target = getAdministration(thing);
2784 } else if (isObservableObject(thing)) {
2785 if ( !isStringish(propOrHandler)) {
2786 return die("InterceptReads can only be used with a specific property, not with an object in general");
2787 }
2788 target = getAdministration(thing, propOrHandler);
2789 } else {
2790 return die("Expected observable map, object or array as first array");
2791 }
2792 if ( target.dehancer !== undefined) {
2793 return die("An intercept reader was already established");
2794 }
2795 target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler;
2796 return function () {
2797 target.dehancer = undefined;
2798 };
2799}
2800
2801function intercept(thing, propOrHandler, handler) {
2802 if (isFunction(handler)) {
2803 return interceptProperty(thing, propOrHandler, handler);
2804 } else {
2805 return interceptInterceptable(thing, propOrHandler);
2806 }
2807}
2808function interceptInterceptable(thing, handler) {
2809 return getAdministration(thing).intercept_(handler);
2810}
2811function interceptProperty(thing, property, handler) {
2812 return getAdministration(thing, property).intercept_(handler);
2813}
2814
2815function _isComputed(value, property) {
2816 if (property === undefined) {
2817 return isComputedValue(value);
2818 }
2819 if (isObservableObject(value) === false) {
2820 return false;
2821 }
2822 if (!value[$mobx].values_.has(property)) {
2823 return false;
2824 }
2825 var atom = getAtom(value, property);
2826 return isComputedValue(atom);
2827}
2828function isComputed(value) {
2829 if ( arguments.length > 1) {
2830 return die("isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property");
2831 }
2832 return _isComputed(value);
2833}
2834function isComputedProp(value, propName) {
2835 if ( !isStringish(propName)) {
2836 return die("isComputed expected a property name as second argument");
2837 }
2838 return _isComputed(value, propName);
2839}
2840
2841function _isObservable(value, property) {
2842 if (!value) {
2843 return false;
2844 }
2845 if (property !== undefined) {
2846 if ( (isObservableMap(value) || isObservableArray(value))) {
2847 return die("isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");
2848 }
2849 if (isObservableObject(value)) {
2850 return value[$mobx].values_.has(property);
2851 }
2852 return false;
2853 }
2854 // For first check, see #701
2855 return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);
2856}
2857function isObservable(value) {
2858 if ( arguments.length !== 1) {
2859 die("isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property");
2860 }
2861 return _isObservable(value);
2862}
2863function isObservableProp(value, propName) {
2864 if ( !isStringish(propName)) {
2865 return die("expected a property name as second argument");
2866 }
2867 return _isObservable(value, propName);
2868}
2869
2870function keys(obj) {
2871 if (isObservableObject(obj)) {
2872 return obj[$mobx].keys_();
2873 }
2874 if (isObservableMap(obj) || isObservableSet(obj)) {
2875 return Array.from(obj.keys());
2876 }
2877 if (isObservableArray(obj)) {
2878 return obj.map(function (_, index) {
2879 return index;
2880 });
2881 }
2882 die(5);
2883}
2884function values(obj) {
2885 if (isObservableObject(obj)) {
2886 return keys(obj).map(function (key) {
2887 return obj[key];
2888 });
2889 }
2890 if (isObservableMap(obj)) {
2891 return keys(obj).map(function (key) {
2892 return obj.get(key);
2893 });
2894 }
2895 if (isObservableSet(obj)) {
2896 return Array.from(obj.values());
2897 }
2898 if (isObservableArray(obj)) {
2899 return obj.slice();
2900 }
2901 die(6);
2902}
2903function entries(obj) {
2904 if (isObservableObject(obj)) {
2905 return keys(obj).map(function (key) {
2906 return [key, obj[key]];
2907 });
2908 }
2909 if (isObservableMap(obj)) {
2910 return keys(obj).map(function (key) {
2911 return [key, obj.get(key)];
2912 });
2913 }
2914 if (isObservableSet(obj)) {
2915 return Array.from(obj.entries());
2916 }
2917 if (isObservableArray(obj)) {
2918 return obj.map(function (key, index) {
2919 return [index, key];
2920 });
2921 }
2922 die(7);
2923}
2924function set(obj, key, value) {
2925 if (arguments.length === 2 && !isObservableSet(obj)) {
2926 startBatch();
2927 var _values = key;
2928 try {
2929 for (var _key in _values) {
2930 set(obj, _key, _values[_key]);
2931 }
2932 } finally {
2933 endBatch();
2934 }
2935 return;
2936 }
2937 if (isObservableObject(obj)) {
2938 obj[$mobx].set_(key, value);
2939 } else if (isObservableMap(obj)) {
2940 obj.set(key, value);
2941 } else if (isObservableSet(obj)) {
2942 obj.add(key);
2943 } else if (isObservableArray(obj)) {
2944 if (typeof key !== "number") {
2945 key = parseInt(key, 10);
2946 }
2947 if (key < 0) {
2948 die("Invalid index: '" + key + "'");
2949 }
2950 startBatch();
2951 if (key >= obj.length) {
2952 obj.length = key + 1;
2953 }
2954 obj[key] = value;
2955 endBatch();
2956 } else {
2957 die(8);
2958 }
2959}
2960function remove(obj, key) {
2961 if (isObservableObject(obj)) {
2962 obj[$mobx].delete_(key);
2963 } else if (isObservableMap(obj)) {
2964 obj["delete"](key);
2965 } else if (isObservableSet(obj)) {
2966 obj["delete"](key);
2967 } else if (isObservableArray(obj)) {
2968 if (typeof key !== "number") {
2969 key = parseInt(key, 10);
2970 }
2971 obj.splice(key, 1);
2972 } else {
2973 die(9);
2974 }
2975}
2976function has(obj, key) {
2977 if (isObservableObject(obj)) {
2978 return obj[$mobx].has_(key);
2979 } else if (isObservableMap(obj)) {
2980 return obj.has(key);
2981 } else if (isObservableSet(obj)) {
2982 return obj.has(key);
2983 } else if (isObservableArray(obj)) {
2984 return key >= 0 && key < obj.length;
2985 }
2986 die(10);
2987}
2988function get(obj, key) {
2989 if (!has(obj, key)) {
2990 return undefined;
2991 }
2992 if (isObservableObject(obj)) {
2993 return obj[$mobx].get_(key);
2994 } else if (isObservableMap(obj)) {
2995 return obj.get(key);
2996 } else if (isObservableArray(obj)) {
2997 return obj[key];
2998 }
2999 die(11);
3000}
3001function apiDefineProperty(obj, key, descriptor) {
3002 if (isObservableObject(obj)) {
3003 return obj[$mobx].defineProperty_(key, descriptor);
3004 }
3005 die(39);
3006}
3007function apiOwnKeys(obj) {
3008 if (isObservableObject(obj)) {
3009 return obj[$mobx].ownKeys_();
3010 }
3011 die(38);
3012}
3013
3014function observe(thing, propOrCb, cbOrFire, fireImmediately) {
3015 if (isFunction(cbOrFire)) {
3016 return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);
3017 } else {
3018 return observeObservable(thing, propOrCb, cbOrFire);
3019 }
3020}
3021function observeObservable(thing, listener, fireImmediately) {
3022 return getAdministration(thing).observe_(listener, fireImmediately);
3023}
3024function observeObservableProperty(thing, property, listener, fireImmediately) {
3025 return getAdministration(thing, property).observe_(listener, fireImmediately);
3026}
3027
3028function cache(map, key, value) {
3029 map.set(key, value);
3030 return value;
3031}
3032function toJSHelper(source, __alreadySeen) {
3033 if (source == null || typeof source !== "object" || source instanceof Date || !isObservable(source)) {
3034 return source;
3035 }
3036 if (isObservableValue(source) || isComputedValue(source)) {
3037 return toJSHelper(source.get(), __alreadySeen);
3038 }
3039 if (__alreadySeen.has(source)) {
3040 return __alreadySeen.get(source);
3041 }
3042 if (isObservableArray(source)) {
3043 var res = cache(__alreadySeen, source, new Array(source.length));
3044 source.forEach(function (value, idx) {
3045 res[idx] = toJSHelper(value, __alreadySeen);
3046 });
3047 return res;
3048 }
3049 if (isObservableSet(source)) {
3050 var _res = cache(__alreadySeen, source, new Set());
3051 source.forEach(function (value) {
3052 _res.add(toJSHelper(value, __alreadySeen));
3053 });
3054 return _res;
3055 }
3056 if (isObservableMap(source)) {
3057 var _res2 = cache(__alreadySeen, source, new Map());
3058 source.forEach(function (value, key) {
3059 _res2.set(key, toJSHelper(value, __alreadySeen));
3060 });
3061 return _res2;
3062 } else {
3063 // must be observable object
3064 var _res3 = cache(__alreadySeen, source, {});
3065 apiOwnKeys(source).forEach(function (key) {
3066 if (objectPrototype.propertyIsEnumerable.call(source, key)) {
3067 _res3[key] = toJSHelper(source[key], __alreadySeen);
3068 }
3069 });
3070 return _res3;
3071 }
3072}
3073/**
3074 * Recursively converts an observable to it's non-observable native counterpart.
3075 * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.
3076 * Computed and other non-enumerable properties are completely ignored.
3077 * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.
3078 */
3079function toJS(source, options) {
3080 if ( options) {
3081 die("toJS no longer supports options");
3082 }
3083 return toJSHelper(source, new Map());
3084}
3085
3086function trace() {
3087 var enterBreakPoint = false;
3088 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3089 args[_key] = arguments[_key];
3090 }
3091 if (typeof args[args.length - 1] === "boolean") {
3092 enterBreakPoint = args.pop();
3093 }
3094 var derivation = getAtomFromArgs(args);
3095 if (!derivation) {
3096 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");
3097 }
3098 if (derivation.isTracing_ === TraceMode.NONE) {
3099 console.log("[mobx.trace] '" + derivation.name_ + "' tracing enabled");
3100 }
3101 derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;
3102}
3103function getAtomFromArgs(args) {
3104 switch (args.length) {
3105 case 0:
3106 return globalState.trackingDerivation;
3107 case 1:
3108 return getAtom(args[0]);
3109 case 2:
3110 return getAtom(args[0], args[1]);
3111 }
3112}
3113
3114/**
3115 * During a transaction no views are updated until the end of the transaction.
3116 * The transaction will be run synchronously nonetheless.
3117 *
3118 * @param action a function that updates some reactive state
3119 * @returns any value that was returned by the 'action' parameter.
3120 */
3121function transaction(action, thisArg) {
3122 if (thisArg === void 0) {
3123 thisArg = undefined;
3124 }
3125 startBatch();
3126 try {
3127 return action.apply(thisArg);
3128 } finally {
3129 endBatch();
3130 }
3131}
3132
3133function when(predicate, arg1, arg2) {
3134 if (arguments.length === 1 || arg1 && typeof arg1 === "object") {
3135 return whenPromise(predicate, arg1);
3136 }
3137 return _when(predicate, arg1, arg2 || {});
3138}
3139function _when(predicate, effect, opts) {
3140 var timeoutHandle;
3141 if (typeof opts.timeout === "number") {
3142 var error = new Error("WHEN_TIMEOUT");
3143 timeoutHandle = setTimeout(function () {
3144 if (!disposer[$mobx].isDisposed_) {
3145 disposer();
3146 if (opts.onError) {
3147 opts.onError(error);
3148 } else {
3149 throw error;
3150 }
3151 }
3152 }, opts.timeout);
3153 }
3154 opts.name = opts.name || "When@" + getNextId() ;
3155 var effectAction = createAction( opts.name + "-effect" , effect);
3156 // eslint-disable-next-line
3157 var disposer = autorun(function (r) {
3158 // predicate should not change state
3159 var cond = allowStateChanges(false, predicate);
3160 if (cond) {
3161 r.dispose();
3162 if (timeoutHandle) {
3163 clearTimeout(timeoutHandle);
3164 }
3165 effectAction();
3166 }
3167 }, opts);
3168 return disposer;
3169}
3170function whenPromise(predicate, opts) {
3171 var _opts$signal;
3172 if ( opts && opts.onError) {
3173 return die("the options 'onError' and 'promise' cannot be combined");
3174 }
3175 if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {
3176 return Object.assign(Promise.reject(new Error("WHEN_ABORTED")), {
3177 cancel: function cancel() {
3178 return null;
3179 }
3180 });
3181 }
3182 var cancel;
3183 var abort;
3184 var res = new Promise(function (resolve, reject) {
3185 var _opts$signal2;
3186 var disposer = _when(predicate, resolve, _extends({}, opts, {
3187 onError: reject
3188 }));
3189 cancel = function cancel() {
3190 disposer();
3191 reject(new Error("WHEN_CANCELLED"));
3192 };
3193 abort = function abort() {
3194 disposer();
3195 reject(new Error("WHEN_ABORTED"));
3196 };
3197 opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener == null ? void 0 : _opts$signal2.addEventListener("abort", abort);
3198 })["finally"](function () {
3199 var _opts$signal3;
3200 return opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener == null ? void 0 : _opts$signal3.removeEventListener("abort", abort);
3201 });
3202 res.cancel = cancel;
3203 return res;
3204}
3205
3206function getAdm(target) {
3207 return target[$mobx];
3208}
3209// Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,
3210// and skip either the internal values map, or the base object with its property descriptors!
3211var objectProxyTraps = {
3212 has: function has(target, name) {
3213 if ( globalState.trackingDerivation) {
3214 warnAboutProxyRequirement("detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.");
3215 }
3216 return getAdm(target).has_(name);
3217 },
3218 get: function get(target, name) {
3219 return getAdm(target).get_(name);
3220 },
3221 set: function set(target, name, value) {
3222 var _getAdm$set_;
3223 if (!isStringish(name)) {
3224 return false;
3225 }
3226 if ( !getAdm(target).values_.has(name)) {
3227 warnAboutProxyRequirement("add a new observable property through direct assignment. Use 'set' from 'mobx' instead.");
3228 }
3229 // null (intercepted) -> true (success)
3230 return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;
3231 },
3232 deleteProperty: function deleteProperty(target, name) {
3233 var _getAdm$delete_;
3234 {
3235 warnAboutProxyRequirement("delete properties from an observable object. Use 'remove' from 'mobx' instead.");
3236 }
3237 if (!isStringish(name)) {
3238 return false;
3239 }
3240 // null (intercepted) -> true (success)
3241 return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;
3242 },
3243 defineProperty: function defineProperty(target, name, descriptor) {
3244 var _getAdm$definePropert;
3245 {
3246 warnAboutProxyRequirement("define property on an observable object. Use 'defineProperty' from 'mobx' instead.");
3247 }
3248 // null (intercepted) -> true (success)
3249 return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;
3250 },
3251 ownKeys: function ownKeys(target) {
3252 if ( globalState.trackingDerivation) {
3253 warnAboutProxyRequirement("iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.");
3254 }
3255 return getAdm(target).ownKeys_();
3256 },
3257 preventExtensions: function preventExtensions(target) {
3258 die(13);
3259 }
3260};
3261function asDynamicObservableObject(target, options) {
3262 var _target$$mobx, _target$$mobx$proxy_;
3263 assertProxies();
3264 target = asObservableObject(target, options);
3265 return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);
3266}
3267
3268function hasInterceptors(interceptable) {
3269 return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;
3270}
3271function registerInterceptor(interceptable, handler) {
3272 var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);
3273 interceptors.push(handler);
3274 return once(function () {
3275 var idx = interceptors.indexOf(handler);
3276 if (idx !== -1) {
3277 interceptors.splice(idx, 1);
3278 }
3279 });
3280}
3281function interceptChange(interceptable, change) {
3282 var prevU = untrackedStart();
3283 try {
3284 // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950
3285 var interceptors = [].concat(interceptable.interceptors_ || []);
3286 for (var i = 0, l = interceptors.length; i < l; i++) {
3287 change = interceptors[i](change);
3288 if (change && !change.type) {
3289 die(14);
3290 }
3291 if (!change) {
3292 break;
3293 }
3294 }
3295 return change;
3296 } finally {
3297 untrackedEnd(prevU);
3298 }
3299}
3300
3301function hasListeners(listenable) {
3302 return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;
3303}
3304function registerListener(listenable, handler) {
3305 var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);
3306 listeners.push(handler);
3307 return once(function () {
3308 var idx = listeners.indexOf(handler);
3309 if (idx !== -1) {
3310 listeners.splice(idx, 1);
3311 }
3312 });
3313}
3314function notifyListeners(listenable, change) {
3315 var prevU = untrackedStart();
3316 var listeners = listenable.changeListeners_;
3317 if (!listeners) {
3318 return;
3319 }
3320 listeners = listeners.slice();
3321 for (var i = 0, l = listeners.length; i < l; i++) {
3322 listeners[i](change);
3323 }
3324 untrackedEnd(prevU);
3325}
3326
3327function makeObservable(target, annotations, options) {
3328 var adm = asObservableObject(target, options)[$mobx];
3329 startBatch();
3330 try {
3331 var _annotations;
3332 if ("development" !== "production" && annotations && target[storedAnnotationsSymbol]) {
3333 die("makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.");
3334 }
3335 // Default to decorators
3336 (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target);
3337 // Annotate
3338 ownKeys(annotations).forEach(function (key) {
3339 return adm.make_(key, annotations[key]);
3340 });
3341 } finally {
3342 endBatch();
3343 }
3344 return target;
3345}
3346// proto[keysSymbol] = new Set<PropertyKey>()
3347var keysSymbol = /*#__PURE__*/Symbol("mobx-keys");
3348function makeAutoObservable(target, overrides, options) {
3349 {
3350 if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {
3351 die("'makeAutoObservable' can only be used for classes that don't have a superclass");
3352 }
3353 if (isObservableObject(target)) {
3354 die("makeAutoObservable can only be used on objects not already made observable");
3355 }
3356 }
3357 // Optimization: avoid visiting protos
3358 // Assumes that annotation.make_/.extend_ works the same for plain objects
3359 if (isPlainObject(target)) {
3360 return extendObservable(target, target, overrides, options);
3361 }
3362 var adm = asObservableObject(target, options)[$mobx];
3363 // Optimization: cache keys on proto
3364 // Assumes makeAutoObservable can be called only once per object and can't be used in subclass
3365 if (!target[keysSymbol]) {
3366 var proto = Object.getPrototypeOf(target);
3367 var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));
3368 keys["delete"]("constructor");
3369 keys["delete"]($mobx);
3370 addHiddenProp(proto, keysSymbol, keys);
3371 }
3372 startBatch();
3373 try {
3374 target[keysSymbol].forEach(function (key) {
3375 return adm.make_(key,
3376 // must pass "undefined" for { key: undefined }
3377 !overrides ? true : key in overrides ? overrides[key] : true);
3378 });
3379 } finally {
3380 endBatch();
3381 }
3382 return target;
3383}
3384
3385var SPLICE = "splice";
3386var UPDATE = "update";
3387var MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859
3388var arrayTraps = {
3389 get: function get(target, name) {
3390 var adm = target[$mobx];
3391 if (name === $mobx) {
3392 return adm;
3393 }
3394 if (name === "length") {
3395 return adm.getArrayLength_();
3396 }
3397 if (typeof name === "string" && !isNaN(name)) {
3398 return adm.get_(parseInt(name));
3399 }
3400 if (hasProp(arrayExtensions, name)) {
3401 return arrayExtensions[name];
3402 }
3403 return target[name];
3404 },
3405 set: function set(target, name, value) {
3406 var adm = target[$mobx];
3407 if (name === "length") {
3408 adm.setArrayLength_(value);
3409 }
3410 if (typeof name === "symbol" || isNaN(name)) {
3411 target[name] = value;
3412 } else {
3413 // numeric string
3414 adm.set_(parseInt(name), value);
3415 }
3416 return true;
3417 },
3418 preventExtensions: function preventExtensions() {
3419 die(15);
3420 }
3421};
3422var ObservableArrayAdministration = /*#__PURE__*/function () {
3423 // this is the prop that gets proxied, so can't replace it!
3424
3425 function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {
3426 if (name === void 0) {
3427 name = "ObservableArray@" + getNextId() ;
3428 }
3429 this.owned_ = void 0;
3430 this.legacyMode_ = void 0;
3431 this.atom_ = void 0;
3432 this.values_ = [];
3433 this.interceptors_ = void 0;
3434 this.changeListeners_ = void 0;
3435 this.enhancer_ = void 0;
3436 this.dehancer = void 0;
3437 this.proxy_ = void 0;
3438 this.lastKnownLength_ = 0;
3439 this.owned_ = owned_;
3440 this.legacyMode_ = legacyMode_;
3441 this.atom_ = new Atom(name);
3442 this.enhancer_ = function (newV, oldV) {
3443 return enhancer(newV, oldV, name + "[..]" );
3444 };
3445 }
3446 var _proto = ObservableArrayAdministration.prototype;
3447 _proto.dehanceValue_ = function dehanceValue_(value) {
3448 if (this.dehancer !== undefined) {
3449 return this.dehancer(value);
3450 }
3451 return value;
3452 };
3453 _proto.dehanceValues_ = function dehanceValues_(values) {
3454 if (this.dehancer !== undefined && values.length > 0) {
3455 return values.map(this.dehancer);
3456 }
3457 return values;
3458 };
3459 _proto.intercept_ = function intercept_(handler) {
3460 return registerInterceptor(this, handler);
3461 };
3462 _proto.observe_ = function observe_(listener, fireImmediately) {
3463 if (fireImmediately === void 0) {
3464 fireImmediately = false;
3465 }
3466 if (fireImmediately) {
3467 listener({
3468 observableKind: "array",
3469 object: this.proxy_,
3470 debugObjectName: this.atom_.name_,
3471 type: "splice",
3472 index: 0,
3473 added: this.values_.slice(),
3474 addedCount: this.values_.length,
3475 removed: [],
3476 removedCount: 0
3477 });
3478 }
3479 return registerListener(this, listener);
3480 };
3481 _proto.getArrayLength_ = function getArrayLength_() {
3482 this.atom_.reportObserved();
3483 return this.values_.length;
3484 };
3485 _proto.setArrayLength_ = function setArrayLength_(newLength) {
3486 if (typeof newLength !== "number" || isNaN(newLength) || newLength < 0) {
3487 die("Out of range: " + newLength);
3488 }
3489 var currentLength = this.values_.length;
3490 if (newLength === currentLength) {
3491 return;
3492 } else if (newLength > currentLength) {
3493 var newItems = new Array(newLength - currentLength);
3494 for (var i = 0; i < newLength - currentLength; i++) {
3495 newItems[i] = undefined;
3496 } // No Array.fill everywhere...
3497 this.spliceWithArray_(currentLength, 0, newItems);
3498 } else {
3499 this.spliceWithArray_(newLength, currentLength - newLength);
3500 }
3501 };
3502 _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {
3503 if (oldLength !== this.lastKnownLength_) {
3504 die(16);
3505 }
3506 this.lastKnownLength_ += delta;
3507 if (this.legacyMode_ && delta > 0) {
3508 reserveArrayBuffer(oldLength + delta + 1);
3509 }
3510 };
3511 _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {
3512 var _this = this;
3513 checkIfStateModificationsAreAllowed(this.atom_);
3514 var length = this.values_.length;
3515 if (index === undefined) {
3516 index = 0;
3517 } else if (index > length) {
3518 index = length;
3519 } else if (index < 0) {
3520 index = Math.max(0, length + index);
3521 }
3522 if (arguments.length === 1) {
3523 deleteCount = length - index;
3524 } else if (deleteCount === undefined || deleteCount === null) {
3525 deleteCount = 0;
3526 } else {
3527 deleteCount = Math.max(0, Math.min(deleteCount, length - index));
3528 }
3529 if (newItems === undefined) {
3530 newItems = EMPTY_ARRAY;
3531 }
3532 if (hasInterceptors(this)) {
3533 var change = interceptChange(this, {
3534 object: this.proxy_,
3535 type: SPLICE,
3536 index: index,
3537 removedCount: deleteCount,
3538 added: newItems
3539 });
3540 if (!change) {
3541 return EMPTY_ARRAY;
3542 }
3543 deleteCount = change.removedCount;
3544 newItems = change.added;
3545 }
3546 newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {
3547 return _this.enhancer_(v, undefined);
3548 });
3549 if (this.legacyMode_ || "development" !== "production") {
3550 var lengthDelta = newItems.length - deleteCount;
3551 this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified
3552 }
3553
3554 var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);
3555 if (deleteCount !== 0 || newItems.length !== 0) {
3556 this.notifyArraySplice_(index, newItems, res);
3557 }
3558 return this.dehanceValues_(res);
3559 };
3560 _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {
3561 if (newItems.length < MAX_SPLICE_SIZE) {
3562 var _this$values_;
3563 return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));
3564 } else {
3565 // The items removed by the splice
3566 var res = this.values_.slice(index, index + deleteCount);
3567 // The items that that should remain at the end of the array
3568 var oldItems = this.values_.slice(index + deleteCount);
3569 // New length is the previous length + addition count - deletion count
3570 this.values_.length += newItems.length - deleteCount;
3571 for (var i = 0; i < newItems.length; i++) {
3572 this.values_[index + i] = newItems[i];
3573 }
3574 for (var _i = 0; _i < oldItems.length; _i++) {
3575 this.values_[index + newItems.length + _i] = oldItems[_i];
3576 }
3577 return res;
3578 }
3579 };
3580 _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {
3581 var notifySpy = !this.owned_ && isSpyEnabled();
3582 var notify = hasListeners(this);
3583 var change = notify || notifySpy ? {
3584 observableKind: "array",
3585 object: this.proxy_,
3586 type: UPDATE,
3587 debugObjectName: this.atom_.name_,
3588 index: index,
3589 newValue: newValue,
3590 oldValue: oldValue
3591 } : null;
3592 // 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
3593 // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled
3594 if ( notifySpy) {
3595 spyReportStart(change);
3596 }
3597 this.atom_.reportChanged();
3598 if (notify) {
3599 notifyListeners(this, change);
3600 }
3601 if ( notifySpy) {
3602 spyReportEnd();
3603 }
3604 };
3605 _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {
3606 var notifySpy = !this.owned_ && isSpyEnabled();
3607 var notify = hasListeners(this);
3608 var change = notify || notifySpy ? {
3609 observableKind: "array",
3610 object: this.proxy_,
3611 debugObjectName: this.atom_.name_,
3612 type: SPLICE,
3613 index: index,
3614 removed: removed,
3615 added: added,
3616 removedCount: removed.length,
3617 addedCount: added.length
3618 } : null;
3619 if ( notifySpy) {
3620 spyReportStart(change);
3621 }
3622 this.atom_.reportChanged();
3623 // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe
3624 if (notify) {
3625 notifyListeners(this, change);
3626 }
3627 if ( notifySpy) {
3628 spyReportEnd();
3629 }
3630 };
3631 _proto.get_ = function get_(index) {
3632 if (this.legacyMode_ && index >= this.values_.length) {
3633 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" );
3634 return undefined;
3635 }
3636 this.atom_.reportObserved();
3637 return this.dehanceValue_(this.values_[index]);
3638 };
3639 _proto.set_ = function set_(index, newValue) {
3640 var values = this.values_;
3641 if (this.legacyMode_ && index > values.length) {
3642 // out of bounds
3643 die(17, index, values.length);
3644 }
3645 if (index < values.length) {
3646 // update at index in range
3647 checkIfStateModificationsAreAllowed(this.atom_);
3648 var oldValue = values[index];
3649 if (hasInterceptors(this)) {
3650 var change = interceptChange(this, {
3651 type: UPDATE,
3652 object: this.proxy_,
3653 index: index,
3654 newValue: newValue
3655 });
3656 if (!change) {
3657 return;
3658 }
3659 newValue = change.newValue;
3660 }
3661 newValue = this.enhancer_(newValue, oldValue);
3662 var changed = newValue !== oldValue;
3663 if (changed) {
3664 values[index] = newValue;
3665 this.notifyArrayChildUpdate_(index, newValue, oldValue);
3666 }
3667 } else {
3668 // For out of bound index, we don't create an actual sparse array,
3669 // but rather fill the holes with undefined (same as setArrayLength_).
3670 // This could be considered a bug.
3671 var newItems = new Array(index + 1 - values.length);
3672 for (var i = 0; i < newItems.length - 1; i++) {
3673 newItems[i] = undefined;
3674 } // No Array.fill everywhere...
3675 newItems[newItems.length - 1] = newValue;
3676 this.spliceWithArray_(values.length, 0, newItems);
3677 }
3678 };
3679 return ObservableArrayAdministration;
3680}();
3681function createObservableArray(initialValues, enhancer, name, owned) {
3682 if (name === void 0) {
3683 name = "ObservableArray@" + getNextId() ;
3684 }
3685 if (owned === void 0) {
3686 owned = false;
3687 }
3688 assertProxies();
3689 var adm = new ObservableArrayAdministration(name, enhancer, owned, false);
3690 addHiddenFinalProp(adm.values_, $mobx, adm);
3691 var proxy = new Proxy(adm.values_, arrayTraps);
3692 adm.proxy_ = proxy;
3693 if (initialValues && initialValues.length) {
3694 var prev = allowStateChangesStart(true);
3695 adm.spliceWithArray_(0, 0, initialValues);
3696 allowStateChangesEnd(prev);
3697 }
3698 return proxy;
3699}
3700// eslint-disable-next-line
3701var arrayExtensions = {
3702 clear: function clear() {
3703 return this.splice(0);
3704 },
3705 replace: function replace(newItems) {
3706 var adm = this[$mobx];
3707 return adm.spliceWithArray_(0, adm.values_.length, newItems);
3708 },
3709 // Used by JSON.stringify
3710 toJSON: function toJSON() {
3711 return this.slice();
3712 },
3713 /*
3714 * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)
3715 * since these functions alter the inner structure of the array, the have side effects.
3716 * Because the have side effects, they should not be used in computed function,
3717 * and for that reason the do not call dependencyState.notifyObserved
3718 */
3719 splice: function splice(index, deleteCount) {
3720 for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
3721 newItems[_key - 2] = arguments[_key];
3722 }
3723 var adm = this[$mobx];
3724 switch (arguments.length) {
3725 case 0:
3726 return [];
3727 case 1:
3728 return adm.spliceWithArray_(index);
3729 case 2:
3730 return adm.spliceWithArray_(index, deleteCount);
3731 }
3732 return adm.spliceWithArray_(index, deleteCount, newItems);
3733 },
3734 spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {
3735 return this[$mobx].spliceWithArray_(index, deleteCount, newItems);
3736 },
3737 push: function push() {
3738 var adm = this[$mobx];
3739 for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
3740 items[_key2] = arguments[_key2];
3741 }
3742 adm.spliceWithArray_(adm.values_.length, 0, items);
3743 return adm.values_.length;
3744 },
3745 pop: function pop() {
3746 return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];
3747 },
3748 shift: function shift() {
3749 return this.splice(0, 1)[0];
3750 },
3751 unshift: function unshift() {
3752 var adm = this[$mobx];
3753 for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
3754 items[_key3] = arguments[_key3];
3755 }
3756 adm.spliceWithArray_(0, 0, items);
3757 return adm.values_.length;
3758 },
3759 reverse: function reverse() {
3760 // reverse by default mutates in place before returning the result
3761 // which makes it both a 'derivation' and a 'mutation'.
3762 if (globalState.trackingDerivation) {
3763 die(37, "reverse");
3764 }
3765 this.replace(this.slice().reverse());
3766 return this;
3767 },
3768 sort: function sort() {
3769 // sort by default mutates in place before returning the result
3770 // which goes against all good practices. Let's not change the array in place!
3771 if (globalState.trackingDerivation) {
3772 die(37, "sort");
3773 }
3774 var copy = this.slice();
3775 copy.sort.apply(copy, arguments);
3776 this.replace(copy);
3777 return this;
3778 },
3779 remove: function remove(value) {
3780 var adm = this[$mobx];
3781 var idx = adm.dehanceValues_(adm.values_).indexOf(value);
3782 if (idx > -1) {
3783 this.splice(idx, 1);
3784 return true;
3785 }
3786 return false;
3787 }
3788};
3789/**
3790 * Wrap function from prototype
3791 * Without this, everything works as well, but this works
3792 * faster as everything works on unproxied values
3793 */
3794addArrayExtension("concat", simpleFunc);
3795addArrayExtension("flat", simpleFunc);
3796addArrayExtension("includes", simpleFunc);
3797addArrayExtension("indexOf", simpleFunc);
3798addArrayExtension("join", simpleFunc);
3799addArrayExtension("lastIndexOf", simpleFunc);
3800addArrayExtension("slice", simpleFunc);
3801addArrayExtension("toString", simpleFunc);
3802addArrayExtension("toLocaleString", simpleFunc);
3803// map
3804addArrayExtension("every", mapLikeFunc);
3805addArrayExtension("filter", mapLikeFunc);
3806addArrayExtension("find", mapLikeFunc);
3807addArrayExtension("findIndex", mapLikeFunc);
3808addArrayExtension("flatMap", mapLikeFunc);
3809addArrayExtension("forEach", mapLikeFunc);
3810addArrayExtension("map", mapLikeFunc);
3811addArrayExtension("some", mapLikeFunc);
3812// reduce
3813addArrayExtension("reduce", reduceLikeFunc);
3814addArrayExtension("reduceRight", reduceLikeFunc);
3815function addArrayExtension(funcName, funcFactory) {
3816 if (typeof Array.prototype[funcName] === "function") {
3817 arrayExtensions[funcName] = funcFactory(funcName);
3818 }
3819}
3820// Report and delegate to dehanced array
3821function simpleFunc(funcName) {
3822 return function () {
3823 var adm = this[$mobx];
3824 adm.atom_.reportObserved();
3825 var dehancedValues = adm.dehanceValues_(adm.values_);
3826 return dehancedValues[funcName].apply(dehancedValues, arguments);
3827 };
3828}
3829// Make sure callbacks recieve correct array arg #2326
3830function mapLikeFunc(funcName) {
3831 return function (callback, thisArg) {
3832 var _this2 = this;
3833 var adm = this[$mobx];
3834 adm.atom_.reportObserved();
3835 var dehancedValues = adm.dehanceValues_(adm.values_);
3836 return dehancedValues[funcName](function (element, index) {
3837 return callback.call(thisArg, element, index, _this2);
3838 });
3839 };
3840}
3841// Make sure callbacks recieve correct array arg #2326
3842function reduceLikeFunc(funcName) {
3843 return function () {
3844 var _this3 = this;
3845 var adm = this[$mobx];
3846 adm.atom_.reportObserved();
3847 var dehancedValues = adm.dehanceValues_(adm.values_);
3848 // #2432 - reduce behavior depends on arguments.length
3849 var callback = arguments[0];
3850 arguments[0] = function (accumulator, currentValue, index) {
3851 return callback(accumulator, currentValue, index, _this3);
3852 };
3853 return dehancedValues[funcName].apply(dehancedValues, arguments);
3854 };
3855}
3856var isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration);
3857function isObservableArray(thing) {
3858 return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);
3859}
3860
3861var _Symbol$iterator, _Symbol$toStringTag;
3862var ObservableMapMarker = {};
3863var ADD = "add";
3864var DELETE = "delete";
3865// just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54
3866// But: https://github.com/mobxjs/mobx/issues/1556
3867_Symbol$iterator = Symbol.iterator;
3868_Symbol$toStringTag = Symbol.toStringTag;
3869var ObservableMap = /*#__PURE__*/function () {
3870 // hasMap, not hashMap >-).
3871
3872 function ObservableMap(initialData, enhancer_, name_) {
3873 var _this = this;
3874 if (enhancer_ === void 0) {
3875 enhancer_ = deepEnhancer;
3876 }
3877 if (name_ === void 0) {
3878 name_ = "ObservableMap@" + getNextId() ;
3879 }
3880 this.enhancer_ = void 0;
3881 this.name_ = void 0;
3882 this[$mobx] = ObservableMapMarker;
3883 this.data_ = void 0;
3884 this.hasMap_ = void 0;
3885 this.keysAtom_ = void 0;
3886 this.interceptors_ = void 0;
3887 this.changeListeners_ = void 0;
3888 this.dehancer = void 0;
3889 this.enhancer_ = enhancer_;
3890 this.name_ = name_;
3891 if (!isFunction(Map)) {
3892 die(18);
3893 }
3894 this.keysAtom_ = createAtom( this.name_ + ".keys()" );
3895 this.data_ = new Map();
3896 this.hasMap_ = new Map();
3897 allowStateChanges(true, function () {
3898 _this.merge(initialData);
3899 });
3900 }
3901 var _proto = ObservableMap.prototype;
3902 _proto.has_ = function has_(key) {
3903 return this.data_.has(key);
3904 };
3905 _proto.has = function has(key) {
3906 var _this2 = this;
3907 if (!globalState.trackingDerivation) {
3908 return this.has_(key);
3909 }
3910 var entry = this.hasMap_.get(key);
3911 if (!entry) {
3912 var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, this.name_ + "." + stringifyKey(key) + "?" , false);
3913 this.hasMap_.set(key, newEntry);
3914 onBecomeUnobserved(newEntry, function () {
3915 return _this2.hasMap_["delete"](key);
3916 });
3917 }
3918 return entry.get();
3919 };
3920 _proto.set = function set(key, value) {
3921 var hasKey = this.has_(key);
3922 if (hasInterceptors(this)) {
3923 var change = interceptChange(this, {
3924 type: hasKey ? UPDATE : ADD,
3925 object: this,
3926 newValue: value,
3927 name: key
3928 });
3929 if (!change) {
3930 return this;
3931 }
3932 value = change.newValue;
3933 }
3934 if (hasKey) {
3935 this.updateValue_(key, value);
3936 } else {
3937 this.addValue_(key, value);
3938 }
3939 return this;
3940 };
3941 _proto["delete"] = function _delete(key) {
3942 var _this3 = this;
3943 checkIfStateModificationsAreAllowed(this.keysAtom_);
3944 if (hasInterceptors(this)) {
3945 var change = interceptChange(this, {
3946 type: DELETE,
3947 object: this,
3948 name: key
3949 });
3950 if (!change) {
3951 return false;
3952 }
3953 }
3954 if (this.has_(key)) {
3955 var notifySpy = isSpyEnabled();
3956 var notify = hasListeners(this);
3957 var _change = notify || notifySpy ? {
3958 observableKind: "map",
3959 debugObjectName: this.name_,
3960 type: DELETE,
3961 object: this,
3962 oldValue: this.data_.get(key).value_,
3963 name: key
3964 } : null;
3965 if ( notifySpy) {
3966 spyReportStart(_change);
3967 } // TODO fix type
3968 transaction(function () {
3969 var _this3$hasMap_$get;
3970 _this3.keysAtom_.reportChanged();
3971 (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false);
3972 var observable = _this3.data_.get(key);
3973 observable.setNewValue_(undefined);
3974 _this3.data_["delete"](key);
3975 });
3976 if (notify) {
3977 notifyListeners(this, _change);
3978 }
3979 if ( notifySpy) {
3980 spyReportEnd();
3981 }
3982 return true;
3983 }
3984 return false;
3985 };
3986 _proto.updateValue_ = function updateValue_(key, newValue) {
3987 var observable = this.data_.get(key);
3988 newValue = observable.prepareNewValue_(newValue);
3989 if (newValue !== globalState.UNCHANGED) {
3990 var notifySpy = isSpyEnabled();
3991 var notify = hasListeners(this);
3992 var change = notify || notifySpy ? {
3993 observableKind: "map",
3994 debugObjectName: this.name_,
3995 type: UPDATE,
3996 object: this,
3997 oldValue: observable.value_,
3998 name: key,
3999 newValue: newValue
4000 } : null;
4001 if ( notifySpy) {
4002 spyReportStart(change);
4003 } // TODO fix type
4004 observable.setNewValue_(newValue);
4005 if (notify) {
4006 notifyListeners(this, change);
4007 }
4008 if ( notifySpy) {
4009 spyReportEnd();
4010 }
4011 }
4012 };
4013 _proto.addValue_ = function addValue_(key, newValue) {
4014 var _this4 = this;
4015 checkIfStateModificationsAreAllowed(this.keysAtom_);
4016 transaction(function () {
4017 var _this4$hasMap_$get;
4018 var observable = new ObservableValue(newValue, _this4.enhancer_, _this4.name_ + "." + stringifyKey(key) , false);
4019 _this4.data_.set(key, observable);
4020 newValue = observable.value_; // value might have been changed
4021 (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true);
4022 _this4.keysAtom_.reportChanged();
4023 });
4024 var notifySpy = isSpyEnabled();
4025 var notify = hasListeners(this);
4026 var change = notify || notifySpy ? {
4027 observableKind: "map",
4028 debugObjectName: this.name_,
4029 type: ADD,
4030 object: this,
4031 name: key,
4032 newValue: newValue
4033 } : null;
4034 if ( notifySpy) {
4035 spyReportStart(change);
4036 } // TODO fix type
4037 if (notify) {
4038 notifyListeners(this, change);
4039 }
4040 if ( notifySpy) {
4041 spyReportEnd();
4042 }
4043 };
4044 _proto.get = function get(key) {
4045 if (this.has(key)) {
4046 return this.dehanceValue_(this.data_.get(key).get());
4047 }
4048 return this.dehanceValue_(undefined);
4049 };
4050 _proto.dehanceValue_ = function dehanceValue_(value) {
4051 if (this.dehancer !== undefined) {
4052 return this.dehancer(value);
4053 }
4054 return value;
4055 };
4056 _proto.keys = function keys() {
4057 this.keysAtom_.reportObserved();
4058 return this.data_.keys();
4059 };
4060 _proto.values = function values() {
4061 var self = this;
4062 var keys = this.keys();
4063 return makeIterable({
4064 next: function next() {
4065 var _keys$next = keys.next(),
4066 done = _keys$next.done,
4067 value = _keys$next.value;
4068 return {
4069 done: done,
4070 value: done ? undefined : self.get(value)
4071 };
4072 }
4073 });
4074 };
4075 _proto.entries = function entries() {
4076 var self = this;
4077 var keys = this.keys();
4078 return makeIterable({
4079 next: function next() {
4080 var _keys$next2 = keys.next(),
4081 done = _keys$next2.done,
4082 value = _keys$next2.value;
4083 return {
4084 done: done,
4085 value: done ? undefined : [value, self.get(value)]
4086 };
4087 }
4088 });
4089 };
4090 _proto[_Symbol$iterator] = function () {
4091 return this.entries();
4092 };
4093 _proto.forEach = function forEach(callback, thisArg) {
4094 for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {
4095 var _step$value = _step.value,
4096 key = _step$value[0],
4097 value = _step$value[1];
4098 callback.call(thisArg, value, key, this);
4099 }
4100 }
4101 /** Merge another object into this object, returns this. */;
4102 _proto.merge = function merge(other) {
4103 var _this5 = this;
4104 if (isObservableMap(other)) {
4105 other = new Map(other);
4106 }
4107 transaction(function () {
4108 if (isPlainObject(other)) {
4109 getPlainObjectKeys(other).forEach(function (key) {
4110 return _this5.set(key, other[key]);
4111 });
4112 } else if (Array.isArray(other)) {
4113 other.forEach(function (_ref) {
4114 var key = _ref[0],
4115 value = _ref[1];
4116 return _this5.set(key, value);
4117 });
4118 } else if (isES6Map(other)) {
4119 if (other.constructor !== Map) {
4120 die(19, other);
4121 }
4122 other.forEach(function (value, key) {
4123 return _this5.set(key, value);
4124 });
4125 } else if (other !== null && other !== undefined) {
4126 die(20, other);
4127 }
4128 });
4129 return this;
4130 };
4131 _proto.clear = function clear() {
4132 var _this6 = this;
4133 transaction(function () {
4134 untracked(function () {
4135 for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {
4136 var key = _step2.value;
4137 _this6["delete"](key);
4138 }
4139 });
4140 });
4141 };
4142 _proto.replace = function replace(values) {
4143 var _this7 = this;
4144 // Implementation requirements:
4145 // - respect ordering of replacement map
4146 // - allow interceptors to run and potentially prevent individual operations
4147 // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)
4148 // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)
4149 // - note that result map may differ from replacement map due to the interceptors
4150 transaction(function () {
4151 // Convert to map so we can do quick key lookups
4152 var replacementMap = convertToMap(values);
4153 var orderedData = new Map();
4154 // Used for optimization
4155 var keysReportChangedCalled = false;
4156 // Delete keys that don't exist in replacement map
4157 // if the key deletion is prevented by interceptor
4158 // add entry at the beginning of the result map
4159 for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {
4160 var key = _step3.value;
4161 // Concurrently iterating/deleting keys
4162 // iterator should handle this correctly
4163 if (!replacementMap.has(key)) {
4164 var deleted = _this7["delete"](key);
4165 // Was the key removed?
4166 if (deleted) {
4167 // _keysAtom.reportChanged() was already called
4168 keysReportChangedCalled = true;
4169 } else {
4170 // Delete prevented by interceptor
4171 var value = _this7.data_.get(key);
4172 orderedData.set(key, value);
4173 }
4174 }
4175 }
4176 // Merge entries
4177 for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {
4178 var _step4$value = _step4.value,
4179 _key = _step4$value[0],
4180 _value = _step4$value[1];
4181 // We will want to know whether a new key is added
4182 var keyExisted = _this7.data_.has(_key);
4183 // Add or update value
4184 _this7.set(_key, _value);
4185 // The addition could have been prevent by interceptor
4186 if (_this7.data_.has(_key)) {
4187 // The update could have been prevented by interceptor
4188 // and also we want to preserve existing values
4189 // so use value from _data map (instead of replacement map)
4190 var _value2 = _this7.data_.get(_key);
4191 orderedData.set(_key, _value2);
4192 // Was a new key added?
4193 if (!keyExisted) {
4194 // _keysAtom.reportChanged() was already called
4195 keysReportChangedCalled = true;
4196 }
4197 }
4198 }
4199 // Check for possible key order change
4200 if (!keysReportChangedCalled) {
4201 if (_this7.data_.size !== orderedData.size) {
4202 // If size differs, keys are definitely modified
4203 _this7.keysAtom_.reportChanged();
4204 } else {
4205 var iter1 = _this7.data_.keys();
4206 var iter2 = orderedData.keys();
4207 var next1 = iter1.next();
4208 var next2 = iter2.next();
4209 while (!next1.done) {
4210 if (next1.value !== next2.value) {
4211 _this7.keysAtom_.reportChanged();
4212 break;
4213 }
4214 next1 = iter1.next();
4215 next2 = iter2.next();
4216 }
4217 }
4218 }
4219 // Use correctly ordered map
4220 _this7.data_ = orderedData;
4221 });
4222 return this;
4223 };
4224 _proto.toString = function toString() {
4225 return "[object ObservableMap]";
4226 };
4227 _proto.toJSON = function toJSON() {
4228 return Array.from(this);
4229 };
4230 /**
4231 * Observes this object. Triggers for the events 'add', 'update' and 'delete'.
4232 * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe
4233 * for callback details
4234 */
4235 _proto.observe_ = function observe_(listener, fireImmediately) {
4236 if ( fireImmediately === true) {
4237 die("`observe` doesn't support fireImmediately=true in combination with maps.");
4238 }
4239 return registerListener(this, listener);
4240 };
4241 _proto.intercept_ = function intercept_(handler) {
4242 return registerInterceptor(this, handler);
4243 };
4244 _createClass(ObservableMap, [{
4245 key: "size",
4246 get: function get() {
4247 this.keysAtom_.reportObserved();
4248 return this.data_.size;
4249 }
4250 }, {
4251 key: _Symbol$toStringTag,
4252 get: function get() {
4253 return "Map";
4254 }
4255 }]);
4256 return ObservableMap;
4257}();
4258// eslint-disable-next-line
4259var isObservableMap = /*#__PURE__*/createInstanceofPredicate("ObservableMap", ObservableMap);
4260function convertToMap(dataStructure) {
4261 if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {
4262 return dataStructure;
4263 } else if (Array.isArray(dataStructure)) {
4264 return new Map(dataStructure);
4265 } else if (isPlainObject(dataStructure)) {
4266 var map = new Map();
4267 for (var key in dataStructure) {
4268 map.set(key, dataStructure[key]);
4269 }
4270 return map;
4271 } else {
4272 return die(21, dataStructure);
4273 }
4274}
4275
4276var _Symbol$iterator$1, _Symbol$toStringTag$1;
4277var ObservableSetMarker = {};
4278_Symbol$iterator$1 = Symbol.iterator;
4279_Symbol$toStringTag$1 = Symbol.toStringTag;
4280var ObservableSet = /*#__PURE__*/function () {
4281 function ObservableSet(initialData, enhancer, name_) {
4282 if (enhancer === void 0) {
4283 enhancer = deepEnhancer;
4284 }
4285 if (name_ === void 0) {
4286 name_ = "ObservableSet@" + getNextId() ;
4287 }
4288 this.name_ = void 0;
4289 this[$mobx] = ObservableSetMarker;
4290 this.data_ = new Set();
4291 this.atom_ = void 0;
4292 this.changeListeners_ = void 0;
4293 this.interceptors_ = void 0;
4294 this.dehancer = void 0;
4295 this.enhancer_ = void 0;
4296 this.name_ = name_;
4297 if (!isFunction(Set)) {
4298 die(22);
4299 }
4300 this.atom_ = createAtom(this.name_);
4301 this.enhancer_ = function (newV, oldV) {
4302 return enhancer(newV, oldV, name_);
4303 };
4304 if (initialData) {
4305 this.replace(initialData);
4306 }
4307 }
4308 var _proto = ObservableSet.prototype;
4309 _proto.dehanceValue_ = function dehanceValue_(value) {
4310 if (this.dehancer !== undefined) {
4311 return this.dehancer(value);
4312 }
4313 return value;
4314 };
4315 _proto.clear = function clear() {
4316 var _this = this;
4317 transaction(function () {
4318 untracked(function () {
4319 for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) {
4320 var value = _step.value;
4321 _this["delete"](value);
4322 }
4323 });
4324 });
4325 };
4326 _proto.forEach = function forEach(callbackFn, thisArg) {
4327 for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {
4328 var value = _step2.value;
4329 callbackFn.call(thisArg, value, value, this);
4330 }
4331 };
4332 _proto.add = function add(value) {
4333 var _this2 = this;
4334 checkIfStateModificationsAreAllowed(this.atom_);
4335 if (hasInterceptors(this)) {
4336 var change = interceptChange(this, {
4337 type: ADD,
4338 object: this,
4339 newValue: value
4340 });
4341 if (!change) {
4342 return this;
4343 }
4344 // ideally, value = change.value would be done here, so that values can be
4345 // changed by interceptor. Same applies for other Set and Map api's.
4346 }
4347
4348 if (!this.has(value)) {
4349 transaction(function () {
4350 _this2.data_.add(_this2.enhancer_(value, undefined));
4351 _this2.atom_.reportChanged();
4352 });
4353 var notifySpy = isSpyEnabled();
4354 var notify = hasListeners(this);
4355 var _change = notify || notifySpy ? {
4356 observableKind: "set",
4357 debugObjectName: this.name_,
4358 type: ADD,
4359 object: this,
4360 newValue: value
4361 } : null;
4362 if (notifySpy && "development" !== "production") {
4363 spyReportStart(_change);
4364 }
4365 if (notify) {
4366 notifyListeners(this, _change);
4367 }
4368 if (notifySpy && "development" !== "production") {
4369 spyReportEnd();
4370 }
4371 }
4372 return this;
4373 };
4374 _proto["delete"] = function _delete(value) {
4375 var _this3 = this;
4376 if (hasInterceptors(this)) {
4377 var change = interceptChange(this, {
4378 type: DELETE,
4379 object: this,
4380 oldValue: value
4381 });
4382 if (!change) {
4383 return false;
4384 }
4385 }
4386 if (this.has(value)) {
4387 var notifySpy = isSpyEnabled();
4388 var notify = hasListeners(this);
4389 var _change2 = notify || notifySpy ? {
4390 observableKind: "set",
4391 debugObjectName: this.name_,
4392 type: DELETE,
4393 object: this,
4394 oldValue: value
4395 } : null;
4396 if (notifySpy && "development" !== "production") {
4397 spyReportStart(_change2);
4398 }
4399 transaction(function () {
4400 _this3.atom_.reportChanged();
4401 _this3.data_["delete"](value);
4402 });
4403 if (notify) {
4404 notifyListeners(this, _change2);
4405 }
4406 if (notifySpy && "development" !== "production") {
4407 spyReportEnd();
4408 }
4409 return true;
4410 }
4411 return false;
4412 };
4413 _proto.has = function has(value) {
4414 this.atom_.reportObserved();
4415 return this.data_.has(this.dehanceValue_(value));
4416 };
4417 _proto.entries = function entries() {
4418 var nextIndex = 0;
4419 var keys = Array.from(this.keys());
4420 var values = Array.from(this.values());
4421 return makeIterable({
4422 next: function next() {
4423 var index = nextIndex;
4424 nextIndex += 1;
4425 return index < values.length ? {
4426 value: [keys[index], values[index]],
4427 done: false
4428 } : {
4429 done: true
4430 };
4431 }
4432 });
4433 };
4434 _proto.keys = function keys() {
4435 return this.values();
4436 };
4437 _proto.values = function values() {
4438 this.atom_.reportObserved();
4439 var self = this;
4440 var nextIndex = 0;
4441 var observableValues = Array.from(this.data_.values());
4442 return makeIterable({
4443 next: function next() {
4444 return nextIndex < observableValues.length ? {
4445 value: self.dehanceValue_(observableValues[nextIndex++]),
4446 done: false
4447 } : {
4448 done: true
4449 };
4450 }
4451 });
4452 };
4453 _proto.replace = function replace(other) {
4454 var _this4 = this;
4455 if (isObservableSet(other)) {
4456 other = new Set(other);
4457 }
4458 transaction(function () {
4459 if (Array.isArray(other)) {
4460 _this4.clear();
4461 other.forEach(function (value) {
4462 return _this4.add(value);
4463 });
4464 } else if (isES6Set(other)) {
4465 _this4.clear();
4466 other.forEach(function (value) {
4467 return _this4.add(value);
4468 });
4469 } else if (other !== null && other !== undefined) {
4470 die("Cannot initialize set from " + other);
4471 }
4472 });
4473 return this;
4474 };
4475 _proto.observe_ = function observe_(listener, fireImmediately) {
4476 // ... 'fireImmediately' could also be true?
4477 if ( fireImmediately === true) {
4478 die("`observe` doesn't support fireImmediately=true in combination with sets.");
4479 }
4480 return registerListener(this, listener);
4481 };
4482 _proto.intercept_ = function intercept_(handler) {
4483 return registerInterceptor(this, handler);
4484 };
4485 _proto.toJSON = function toJSON() {
4486 return Array.from(this);
4487 };
4488 _proto.toString = function toString() {
4489 return "[object ObservableSet]";
4490 };
4491 _proto[_Symbol$iterator$1] = function () {
4492 return this.values();
4493 };
4494 _createClass(ObservableSet, [{
4495 key: "size",
4496 get: function get() {
4497 this.atom_.reportObserved();
4498 return this.data_.size;
4499 }
4500 }, {
4501 key: _Symbol$toStringTag$1,
4502 get: function get() {
4503 return "Set";
4504 }
4505 }]);
4506 return ObservableSet;
4507}();
4508// eslint-disable-next-line
4509var isObservableSet = /*#__PURE__*/createInstanceofPredicate("ObservableSet", ObservableSet);
4510
4511var descriptorCache = /*#__PURE__*/Object.create(null);
4512var REMOVE = "remove";
4513var ObservableObjectAdministration = /*#__PURE__*/function () {
4514 function ObservableObjectAdministration(target_, values_, name_,
4515 // Used anytime annotation is not explicitely provided
4516 defaultAnnotation_) {
4517 if (values_ === void 0) {
4518 values_ = new Map();
4519 }
4520 if (defaultAnnotation_ === void 0) {
4521 defaultAnnotation_ = autoAnnotation;
4522 }
4523 this.target_ = void 0;
4524 this.values_ = void 0;
4525 this.name_ = void 0;
4526 this.defaultAnnotation_ = void 0;
4527 this.keysAtom_ = void 0;
4528 this.changeListeners_ = void 0;
4529 this.interceptors_ = void 0;
4530 this.proxy_ = void 0;
4531 this.isPlainObject_ = void 0;
4532 this.appliedAnnotations_ = void 0;
4533 this.pendingKeys_ = void 0;
4534 this.target_ = target_;
4535 this.values_ = values_;
4536 this.name_ = name_;
4537 this.defaultAnnotation_ = defaultAnnotation_;
4538 this.keysAtom_ = new Atom( this.name_ + ".keys" );
4539 // Optimization: we use this frequently
4540 this.isPlainObject_ = isPlainObject(this.target_);
4541 if ( !isAnnotation(this.defaultAnnotation_)) {
4542 die("defaultAnnotation must be valid annotation");
4543 }
4544 {
4545 // Prepare structure for tracking which fields were already annotated
4546 this.appliedAnnotations_ = {};
4547 }
4548 }
4549 var _proto = ObservableObjectAdministration.prototype;
4550 _proto.getObservablePropValue_ = function getObservablePropValue_(key) {
4551 return this.values_.get(key).get();
4552 };
4553 _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {
4554 var observable = this.values_.get(key);
4555 if (observable instanceof ComputedValue) {
4556 observable.set(newValue);
4557 return true;
4558 }
4559 // intercept
4560 if (hasInterceptors(this)) {
4561 var change = interceptChange(this, {
4562 type: UPDATE,
4563 object: this.proxy_ || this.target_,
4564 name: key,
4565 newValue: newValue
4566 });
4567 if (!change) {
4568 return null;
4569 }
4570 newValue = change.newValue;
4571 }
4572 newValue = observable.prepareNewValue_(newValue);
4573 // notify spy & observers
4574 if (newValue !== globalState.UNCHANGED) {
4575 var notify = hasListeners(this);
4576 var notifySpy = isSpyEnabled();
4577 var _change = notify || notifySpy ? {
4578 type: UPDATE,
4579 observableKind: "object",
4580 debugObjectName: this.name_,
4581 object: this.proxy_ || this.target_,
4582 oldValue: observable.value_,
4583 name: key,
4584 newValue: newValue
4585 } : null;
4586 if ( notifySpy) {
4587 spyReportStart(_change);
4588 }
4589 observable.setNewValue_(newValue);
4590 if (notify) {
4591 notifyListeners(this, _change);
4592 }
4593 if ( notifySpy) {
4594 spyReportEnd();
4595 }
4596 }
4597 return true;
4598 };
4599 _proto.get_ = function get_(key) {
4600 if (globalState.trackingDerivation && !hasProp(this.target_, key)) {
4601 // Key doesn't exist yet, subscribe for it in case it's added later
4602 this.has_(key);
4603 }
4604 return this.target_[key];
4605 }
4606 /**
4607 * @param {PropertyKey} key
4608 * @param {any} value
4609 * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is
4610 * @param {boolean} proxyTrap whether it's called from proxy trap
4611 * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
4612 */;
4613 _proto.set_ = function set_(key, value, proxyTrap) {
4614 if (proxyTrap === void 0) {
4615 proxyTrap = false;
4616 }
4617 // Don't use .has(key) - we care about own
4618 if (hasProp(this.target_, key)) {
4619 // Existing prop
4620 if (this.values_.has(key)) {
4621 // Observable (can be intercepted)
4622 return this.setObservablePropValue_(key, value);
4623 } else if (proxyTrap) {
4624 // Non-observable - proxy
4625 return Reflect.set(this.target_, key, value);
4626 } else {
4627 // Non-observable
4628 this.target_[key] = value;
4629 return true;
4630 }
4631 } else {
4632 // New prop
4633 return this.extend_(key, {
4634 value: value,
4635 enumerable: true,
4636 writable: true,
4637 configurable: true
4638 }, this.defaultAnnotation_, proxyTrap);
4639 }
4640 }
4641 // Trap for "in"
4642 ;
4643 _proto.has_ = function has_(key) {
4644 if (!globalState.trackingDerivation) {
4645 // Skip key subscription outside derivation
4646 return key in this.target_;
4647 }
4648 this.pendingKeys_ || (this.pendingKeys_ = new Map());
4649 var entry = this.pendingKeys_.get(key);
4650 if (!entry) {
4651 entry = new ObservableValue(key in this.target_, referenceEnhancer, this.name_ + "." + stringifyKey(key) + "?" , false);
4652 this.pendingKeys_.set(key, entry);
4653 }
4654 return entry.get();
4655 }
4656 /**
4657 * @param {PropertyKey} key
4658 * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop
4659 */;
4660 _proto.make_ = function make_(key, annotation) {
4661 if (annotation === true) {
4662 annotation = this.defaultAnnotation_;
4663 }
4664 if (annotation === false) {
4665 return;
4666 }
4667 assertAnnotable(this, annotation, key);
4668 if (!(key in this.target_)) {
4669 var _this$target_$storedA;
4670 // Throw on missing key, except for decorators:
4671 // Decorator annotations are collected from whole prototype chain.
4672 // When called from super() some props may not exist yet.
4673 // However we don't have to worry about missing prop,
4674 // because the decorator must have been applied to something.
4675 if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {
4676 return; // will be annotated by subclass constructor
4677 } else {
4678 die(1, annotation.annotationType_, this.name_ + "." + key.toString());
4679 }
4680 }
4681 var source = this.target_;
4682 while (source && source !== objectPrototype) {
4683 var descriptor = getDescriptor(source, key);
4684 if (descriptor) {
4685 var outcome = annotation.make_(this, key, descriptor, source);
4686 if (outcome === 0 /* Cancel */) {
4687 return;
4688 }
4689 if (outcome === 1 /* Break */) {
4690 break;
4691 }
4692 }
4693 source = Object.getPrototypeOf(source);
4694 }
4695 recordAnnotationApplied(this, annotation, key);
4696 }
4697 /**
4698 * @param {PropertyKey} key
4699 * @param {PropertyDescriptor} descriptor
4700 * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is
4701 * @param {boolean} proxyTrap whether it's called from proxy trap
4702 * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
4703 */;
4704 _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {
4705 if (proxyTrap === void 0) {
4706 proxyTrap = false;
4707 }
4708 if (annotation === true) {
4709 annotation = this.defaultAnnotation_;
4710 }
4711 if (annotation === false) {
4712 return this.defineProperty_(key, descriptor, proxyTrap);
4713 }
4714 assertAnnotable(this, annotation, key);
4715 var outcome = annotation.extend_(this, key, descriptor, proxyTrap);
4716 if (outcome) {
4717 recordAnnotationApplied(this, annotation, key);
4718 }
4719 return outcome;
4720 }
4721 /**
4722 * @param {PropertyKey} key
4723 * @param {PropertyDescriptor} descriptor
4724 * @param {boolean} proxyTrap whether it's called from proxy trap
4725 * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
4726 */;
4727 _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {
4728 if (proxyTrap === void 0) {
4729 proxyTrap = false;
4730 }
4731 try {
4732 startBatch();
4733 // Delete
4734 var deleteOutcome = this.delete_(key);
4735 if (!deleteOutcome) {
4736 // Failure or intercepted
4737 return deleteOutcome;
4738 }
4739 // ADD interceptor
4740 if (hasInterceptors(this)) {
4741 var change = interceptChange(this, {
4742 object: this.proxy_ || this.target_,
4743 name: key,
4744 type: ADD,
4745 newValue: descriptor.value
4746 });
4747 if (!change) {
4748 return null;
4749 }
4750 var newValue = change.newValue;
4751 if (descriptor.value !== newValue) {
4752 descriptor = _extends({}, descriptor, {
4753 value: newValue
4754 });
4755 }
4756 }
4757 // Define
4758 if (proxyTrap) {
4759 if (!Reflect.defineProperty(this.target_, key, descriptor)) {
4760 return false;
4761 }
4762 } else {
4763 defineProperty(this.target_, key, descriptor);
4764 }
4765 // Notify
4766 this.notifyPropertyAddition_(key, descriptor.value);
4767 } finally {
4768 endBatch();
4769 }
4770 return true;
4771 }
4772 // If original descriptor becomes relevant, move this to annotation directly
4773 ;
4774 _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {
4775 if (proxyTrap === void 0) {
4776 proxyTrap = false;
4777 }
4778 try {
4779 startBatch();
4780 // Delete
4781 var deleteOutcome = this.delete_(key);
4782 if (!deleteOutcome) {
4783 // Failure or intercepted
4784 return deleteOutcome;
4785 }
4786 // ADD interceptor
4787 if (hasInterceptors(this)) {
4788 var change = interceptChange(this, {
4789 object: this.proxy_ || this.target_,
4790 name: key,
4791 type: ADD,
4792 newValue: value
4793 });
4794 if (!change) {
4795 return null;
4796 }
4797 value = change.newValue;
4798 }
4799 var cachedDescriptor = getCachedObservablePropDescriptor(key);
4800 var descriptor = {
4801 configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,
4802 enumerable: true,
4803 get: cachedDescriptor.get,
4804 set: cachedDescriptor.set
4805 };
4806 // Define
4807 if (proxyTrap) {
4808 if (!Reflect.defineProperty(this.target_, key, descriptor)) {
4809 return false;
4810 }
4811 } else {
4812 defineProperty(this.target_, key, descriptor);
4813 }
4814 var observable = new ObservableValue(value, enhancer, "development" !== "production" ? this.name_ + "." + key.toString() : "ObservableObject.key", false);
4815 this.values_.set(key, observable);
4816 // Notify (value possibly changed by ObservableValue)
4817 this.notifyPropertyAddition_(key, observable.value_);
4818 } finally {
4819 endBatch();
4820 }
4821 return true;
4822 }
4823 // If original descriptor becomes relevant, move this to annotation directly
4824 ;
4825 _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {
4826 if (proxyTrap === void 0) {
4827 proxyTrap = false;
4828 }
4829 try {
4830 startBatch();
4831 // Delete
4832 var deleteOutcome = this.delete_(key);
4833 if (!deleteOutcome) {
4834 // Failure or intercepted
4835 return deleteOutcome;
4836 }
4837 // ADD interceptor
4838 if (hasInterceptors(this)) {
4839 var change = interceptChange(this, {
4840 object: this.proxy_ || this.target_,
4841 name: key,
4842 type: ADD,
4843 newValue: undefined
4844 });
4845 if (!change) {
4846 return null;
4847 }
4848 }
4849 options.name || (options.name = "development" !== "production" ? this.name_ + "." + key.toString() : "ObservableObject.key");
4850 options.context = this.proxy_ || this.target_;
4851 var cachedDescriptor = getCachedObservablePropDescriptor(key);
4852 var descriptor = {
4853 configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,
4854 enumerable: false,
4855 get: cachedDescriptor.get,
4856 set: cachedDescriptor.set
4857 };
4858 // Define
4859 if (proxyTrap) {
4860 if (!Reflect.defineProperty(this.target_, key, descriptor)) {
4861 return false;
4862 }
4863 } else {
4864 defineProperty(this.target_, key, descriptor);
4865 }
4866 this.values_.set(key, new ComputedValue(options));
4867 // Notify
4868 this.notifyPropertyAddition_(key, undefined);
4869 } finally {
4870 endBatch();
4871 }
4872 return true;
4873 }
4874 /**
4875 * @param {PropertyKey} key
4876 * @param {PropertyDescriptor} descriptor
4877 * @param {boolean} proxyTrap whether it's called from proxy trap
4878 * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
4879 */;
4880 _proto.delete_ = function delete_(key, proxyTrap) {
4881 if (proxyTrap === void 0) {
4882 proxyTrap = false;
4883 }
4884 // No such prop
4885 if (!hasProp(this.target_, key)) {
4886 return true;
4887 }
4888 // Intercept
4889 if (hasInterceptors(this)) {
4890 var change = interceptChange(this, {
4891 object: this.proxy_ || this.target_,
4892 name: key,
4893 type: REMOVE
4894 });
4895 // Cancelled
4896 if (!change) {
4897 return null;
4898 }
4899 }
4900 // Delete
4901 try {
4902 var _this$pendingKeys_, _this$pendingKeys_$ge;
4903 startBatch();
4904 var notify = hasListeners(this);
4905 var notifySpy = "development" !== "production" && isSpyEnabled();
4906 var observable = this.values_.get(key);
4907 // Value needed for spies/listeners
4908 var value = undefined;
4909 // Optimization: don't pull the value unless we will need it
4910 if (!observable && (notify || notifySpy)) {
4911 var _getDescriptor;
4912 value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;
4913 }
4914 // delete prop (do first, may fail)
4915 if (proxyTrap) {
4916 if (!Reflect.deleteProperty(this.target_, key)) {
4917 return false;
4918 }
4919 } else {
4920 delete this.target_[key];
4921 }
4922 // Allow re-annotating this field
4923 if ("development" !== "production") {
4924 delete this.appliedAnnotations_[key];
4925 }
4926 // Clear observable
4927 if (observable) {
4928 this.values_["delete"](key);
4929 // for computed, value is undefined
4930 if (observable instanceof ObservableValue) {
4931 value = observable.value_;
4932 }
4933 // Notify: autorun(() => obj[key]), see #1796
4934 propagateChanged(observable);
4935 }
4936 // Notify "keys/entries/values" observers
4937 this.keysAtom_.reportChanged();
4938 // Notify "has" observers
4939 // "in" as it may still exist in proto
4940 (_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_);
4941 // Notify spies/listeners
4942 if (notify || notifySpy) {
4943 var _change2 = {
4944 type: REMOVE,
4945 observableKind: "object",
4946 object: this.proxy_ || this.target_,
4947 debugObjectName: this.name_,
4948 oldValue: value,
4949 name: key
4950 };
4951 if ("development" !== "production" && notifySpy) {
4952 spyReportStart(_change2);
4953 }
4954 if (notify) {
4955 notifyListeners(this, _change2);
4956 }
4957 if ("development" !== "production" && notifySpy) {
4958 spyReportEnd();
4959 }
4960 }
4961 } finally {
4962 endBatch();
4963 }
4964 return true;
4965 }
4966 /**
4967 * Observes this object. Triggers for the events 'add', 'update' and 'delete'.
4968 * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe
4969 * for callback details
4970 */;
4971 _proto.observe_ = function observe_(callback, fireImmediately) {
4972 if ( fireImmediately === true) {
4973 die("`observe` doesn't support the fire immediately property for observable objects.");
4974 }
4975 return registerListener(this, callback);
4976 };
4977 _proto.intercept_ = function intercept_(handler) {
4978 return registerInterceptor(this, handler);
4979 };
4980 _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {
4981 var _this$pendingKeys_2, _this$pendingKeys_2$g;
4982 var notify = hasListeners(this);
4983 var notifySpy = isSpyEnabled();
4984 if (notify || notifySpy) {
4985 var change = notify || notifySpy ? {
4986 type: ADD,
4987 observableKind: "object",
4988 debugObjectName: this.name_,
4989 object: this.proxy_ || this.target_,
4990 name: key,
4991 newValue: value
4992 } : null;
4993 if ( notifySpy) {
4994 spyReportStart(change);
4995 }
4996 if (notify) {
4997 notifyListeners(this, change);
4998 }
4999 if ( notifySpy) {
5000 spyReportEnd();
5001 }
5002 }
5003 (_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);
5004 // Notify "keys/entries/values" observers
5005 this.keysAtom_.reportChanged();
5006 };
5007 _proto.ownKeys_ = function ownKeys_() {
5008 this.keysAtom_.reportObserved();
5009 return ownKeys(this.target_);
5010 };
5011 _proto.keys_ = function keys_() {
5012 // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.
5013 // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.
5014 // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)
5015 // We choose to over-report in Object.keys(object), because:
5016 // - typically it's used with simple data objects
5017 // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected
5018 this.keysAtom_.reportObserved();
5019 return Object.keys(this.target_);
5020 };
5021 return ObservableObjectAdministration;
5022}();
5023function asObservableObject(target, options) {
5024 var _options$name;
5025 if ( options && isObservableObject(target)) {
5026 die("Options can't be provided for already observable objects.");
5027 }
5028 if (hasProp(target, $mobx)) {
5029 if ( !(getAdministration(target) instanceof ObservableObjectAdministration)) {
5030 die("Cannot convert '" + getDebugName(target) + "' into observable object:" + "\nThe target is already observable of different type." + "\nExtending builtins is not supported.");
5031 }
5032 return target;
5033 }
5034 if ( !Object.isExtensible(target)) {
5035 die("Cannot make the designated object observable; it is not extensible");
5036 }
5037 var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : (isPlainObject(target) ? "ObservableObject" : target.constructor.name) + "@" + getNextId() ;
5038 var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));
5039 addHiddenProp(target, $mobx, adm);
5040 return target;
5041}
5042var isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration);
5043function getCachedObservablePropDescriptor(key) {
5044 return descriptorCache[key] || (descriptorCache[key] = {
5045 get: function get() {
5046 return this[$mobx].getObservablePropValue_(key);
5047 },
5048 set: function set(value) {
5049 return this[$mobx].setObservablePropValue_(key, value);
5050 }
5051 });
5052}
5053function isObservableObject(thing) {
5054 if (isObject(thing)) {
5055 return isObservableObjectAdministration(thing[$mobx]);
5056 }
5057 return false;
5058}
5059function recordAnnotationApplied(adm, annotation, key) {
5060 var _adm$target_$storedAn;
5061 {
5062 adm.appliedAnnotations_[key] = annotation;
5063 }
5064 // Remove applied decorator annotation so we don't try to apply it again in subclass constructor
5065 (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key];
5066}
5067function assertAnnotable(adm, annotation, key) {
5068 // Valid annotation
5069 if ( !isAnnotation(annotation)) {
5070 die("Cannot annotate '" + adm.name_ + "." + key.toString() + "': Invalid annotation.");
5071 }
5072 /*
5073 // Configurable, not sealed, not frozen
5074 // Possibly not needed, just a little better error then the one thrown by engine.
5075 // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.
5076 if (__DEV__) {
5077 const configurable = getDescriptor(adm.target_, key)?.configurable
5078 const frozen = Object.isFrozen(adm.target_)
5079 const sealed = Object.isSealed(adm.target_)
5080 if (!configurable || frozen || sealed) {
5081 const fieldName = `${adm.name_}.${key.toString()}`
5082 const requestedAnnotationType = annotation.annotationType_
5083 let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`
5084 if (frozen) {
5085 error += `\nObject is frozen.`
5086 }
5087 if (sealed) {
5088 error += `\nObject is sealed.`
5089 }
5090 if (!configurable) {
5091 error += `\nproperty is not configurable.`
5092 // Mention only if caused by us to avoid confusion
5093 if (hasProp(adm.appliedAnnotations!, key)) {
5094 error += `\nTo prevent accidental re-definition of a field by a subclass, `
5095 error += `all annotated fields of non-plain objects (classes) are not configurable.`
5096 }
5097 }
5098 die(error)
5099 }
5100 }
5101 */
5102 // Not annotated
5103 if ( !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {
5104 var fieldName = adm.name_ + "." + key.toString();
5105 var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;
5106 var requestedAnnotationType = annotation.annotationType_;
5107 die("Cannot apply '" + requestedAnnotationType + "' to '" + fieldName + "':" + ("\nThe field is already annotated with '" + currentAnnotationType + "'.") + "\nRe-annotating fields is not allowed." + "\nUse 'override' annotation for methods overridden by subclass.");
5108 }
5109}
5110
5111// Bug in safari 9.* (or iOS 9 safari mobile). See #364
5112var ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);
5113/**
5114 * This array buffer contains two lists of properties, so that all arrays
5115 * can recycle their property definitions, which significantly improves performance of creating
5116 * properties on the fly.
5117 */
5118var OBSERVABLE_ARRAY_BUFFER_SIZE = 0;
5119// Typescript workaround to make sure ObservableArray extends Array
5120var StubArray = function StubArray() {};
5121function inherit(ctor, proto) {
5122 if (Object.setPrototypeOf) {
5123 Object.setPrototypeOf(ctor.prototype, proto);
5124 } else if (ctor.prototype.__proto__ !== undefined) {
5125 ctor.prototype.__proto__ = proto;
5126 } else {
5127 ctor.prototype = proto;
5128 }
5129}
5130inherit(StubArray, Array.prototype);
5131// Weex proto freeze protection was here,
5132// but it is unclear why the hack is need as MobX never changed the prototype
5133// anyway, so removed it in V6
5134var LegacyObservableArray = /*#__PURE__*/function (_StubArray, _Symbol$toStringTag, _Symbol$iterator) {
5135 _inheritsLoose(LegacyObservableArray, _StubArray);
5136 function LegacyObservableArray(initialValues, enhancer, name, owned) {
5137 var _this;
5138 if (name === void 0) {
5139 name = "ObservableArray@" + getNextId() ;
5140 }
5141 if (owned === void 0) {
5142 owned = false;
5143 }
5144 _this = _StubArray.call(this) || this;
5145 var adm = new ObservableArrayAdministration(name, enhancer, owned, true);
5146 adm.proxy_ = _assertThisInitialized(_this);
5147 addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm);
5148 if (initialValues && initialValues.length) {
5149 var prev = allowStateChangesStart(true);
5150 // @ts-ignore
5151 _this.spliceWithArray(0, 0, initialValues);
5152 allowStateChangesEnd(prev);
5153 }
5154 {
5155 // Seems that Safari won't use numeric prototype setter untill any * numeric property is
5156 // defined on the instance. After that it works fine, even if this property is deleted.
5157 Object.defineProperty(_assertThisInitialized(_this), "0", ENTRY_0);
5158 }
5159 return _this;
5160 }
5161 var _proto = LegacyObservableArray.prototype;
5162 _proto.concat = function concat() {
5163 this[$mobx].atom_.reportObserved();
5164 for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {
5165 arrays[_key] = arguments[_key];
5166 }
5167 return Array.prototype.concat.apply(this.slice(),
5168 //@ts-ignore
5169 arrays.map(function (a) {
5170 return isObservableArray(a) ? a.slice() : a;
5171 }));
5172 };
5173 _proto[_Symbol$iterator] = function () {
5174 var self = this;
5175 var nextIndex = 0;
5176 return makeIterable({
5177 next: function next() {
5178 return nextIndex < self.length ? {
5179 value: self[nextIndex++],
5180 done: false
5181 } : {
5182 done: true,
5183 value: undefined
5184 };
5185 }
5186 });
5187 };
5188 _createClass(LegacyObservableArray, [{
5189 key: "length",
5190 get: function get() {
5191 return this[$mobx].getArrayLength_();
5192 },
5193 set: function set(newLength) {
5194 this[$mobx].setArrayLength_(newLength);
5195 }
5196 }, {
5197 key: _Symbol$toStringTag,
5198 get: function get() {
5199 return "Array";
5200 }
5201 }]);
5202 return LegacyObservableArray;
5203}(StubArray, Symbol.toStringTag, Symbol.iterator);
5204Object.entries(arrayExtensions).forEach(function (_ref) {
5205 var prop = _ref[0],
5206 fn = _ref[1];
5207 if (prop !== "concat") {
5208 addHiddenProp(LegacyObservableArray.prototype, prop, fn);
5209 }
5210});
5211function createArrayEntryDescriptor(index) {
5212 return {
5213 enumerable: false,
5214 configurable: true,
5215 get: function get() {
5216 return this[$mobx].get_(index);
5217 },
5218 set: function set(value) {
5219 this[$mobx].set_(index, value);
5220 }
5221 };
5222}
5223function createArrayBufferItem(index) {
5224 defineProperty(LegacyObservableArray.prototype, "" + index, createArrayEntryDescriptor(index));
5225}
5226function reserveArrayBuffer(max) {
5227 if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {
5228 for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {
5229 createArrayBufferItem(index);
5230 }
5231 OBSERVABLE_ARRAY_BUFFER_SIZE = max;
5232 }
5233}
5234reserveArrayBuffer(1000);
5235function createLegacyArray(initialValues, enhancer, name) {
5236 return new LegacyObservableArray(initialValues, enhancer, name);
5237}
5238
5239function getAtom(thing, property) {
5240 if (typeof thing === "object" && thing !== null) {
5241 if (isObservableArray(thing)) {
5242 if (property !== undefined) {
5243 die(23);
5244 }
5245 return thing[$mobx].atom_;
5246 }
5247 if (isObservableSet(thing)) {
5248 return thing.atom_;
5249 }
5250 if (isObservableMap(thing)) {
5251 if (property === undefined) {
5252 return thing.keysAtom_;
5253 }
5254 var observable = thing.data_.get(property) || thing.hasMap_.get(property);
5255 if (!observable) {
5256 die(25, property, getDebugName(thing));
5257 }
5258 return observable;
5259 }
5260 if (isObservableObject(thing)) {
5261 if (!property) {
5262 return die(26);
5263 }
5264 var _observable = thing[$mobx].values_.get(property);
5265 if (!_observable) {
5266 die(27, property, getDebugName(thing));
5267 }
5268 return _observable;
5269 }
5270 if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {
5271 return thing;
5272 }
5273 } else if (isFunction(thing)) {
5274 if (isReaction(thing[$mobx])) {
5275 // disposer function
5276 return thing[$mobx];
5277 }
5278 }
5279 die(28);
5280}
5281function getAdministration(thing, property) {
5282 if (!thing) {
5283 die(29);
5284 }
5285 if (property !== undefined) {
5286 return getAdministration(getAtom(thing, property));
5287 }
5288 if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {
5289 return thing;
5290 }
5291 if (isObservableMap(thing) || isObservableSet(thing)) {
5292 return thing;
5293 }
5294 if (thing[$mobx]) {
5295 return thing[$mobx];
5296 }
5297 die(24, thing);
5298}
5299function getDebugName(thing, property) {
5300 var named;
5301 if (property !== undefined) {
5302 named = getAtom(thing, property);
5303 } else if (isAction(thing)) {
5304 return thing.name;
5305 } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {
5306 named = getAdministration(thing);
5307 } else {
5308 // valid for arrays as well
5309 named = getAtom(thing);
5310 }
5311 return named.name_;
5312}
5313
5314var toString = objectPrototype.toString;
5315function deepEqual(a, b, depth) {
5316 if (depth === void 0) {
5317 depth = -1;
5318 }
5319 return eq(a, b, depth);
5320}
5321// Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289
5322// Internal recursive comparison function for `isEqual`.
5323function eq(a, b, depth, aStack, bStack) {
5324 // Identical objects are equal. `0 === -0`, but they aren't identical.
5325 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
5326 if (a === b) {
5327 return a !== 0 || 1 / a === 1 / b;
5328 }
5329 // `null` or `undefined` only equal to itself (strict comparison).
5330 if (a == null || b == null) {
5331 return false;
5332 }
5333 // `NaN`s are equivalent, but non-reflexive.
5334 if (a !== a) {
5335 return b !== b;
5336 }
5337 // Exhaust primitive checks
5338 var type = typeof a;
5339 if (type !== "function" && type !== "object" && typeof b != "object") {
5340 return false;
5341 }
5342 // Compare `[[Class]]` names.
5343 var className = toString.call(a);
5344 if (className !== toString.call(b)) {
5345 return false;
5346 }
5347 switch (className) {
5348 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
5349 case "[object RegExp]":
5350 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
5351 case "[object String]":
5352 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
5353 // equivalent to `new String("5")`.
5354 return "" + a === "" + b;
5355 case "[object Number]":
5356 // `NaN`s are equivalent, but non-reflexive.
5357 // Object(NaN) is equivalent to NaN.
5358 if (+a !== +a) {
5359 return +b !== +b;
5360 }
5361 // An `egal` comparison is performed for other numeric values.
5362 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
5363 case "[object Date]":
5364 case "[object Boolean]":
5365 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
5366 // millisecond representations. Note that invalid dates with millisecond representations
5367 // of `NaN` are not equivalent.
5368 return +a === +b;
5369 case "[object Symbol]":
5370 return typeof Symbol !== "undefined" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);
5371 case "[object Map]":
5372 case "[object Set]":
5373 // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.
5374 // Hide this extra level by increasing the depth.
5375 if (depth >= 0) {
5376 depth++;
5377 }
5378 break;
5379 }
5380 // Unwrap any wrapped objects.
5381 a = unwrap(a);
5382 b = unwrap(b);
5383 var areArrays = className === "[object Array]";
5384 if (!areArrays) {
5385 if (typeof a != "object" || typeof b != "object") {
5386 return false;
5387 }
5388 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
5389 // from different frames are.
5390 var aCtor = a.constructor,
5391 bCtor = b.constructor;
5392 if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && "constructor" in a && "constructor" in b) {
5393 return false;
5394 }
5395 }
5396 if (depth === 0) {
5397 return false;
5398 } else if (depth < 0) {
5399 depth = -1;
5400 }
5401 // Assume equality for cyclic structures. The algorithm for detecting cyclic
5402 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
5403 // Initializing stack of traversed objects.
5404 // It's done here since we only need them for objects and arrays comparison.
5405 aStack = aStack || [];
5406 bStack = bStack || [];
5407 var length = aStack.length;
5408 while (length--) {
5409 // Linear search. Performance is inversely proportional to the number of
5410 // unique nested structures.
5411 if (aStack[length] === a) {
5412 return bStack[length] === b;
5413 }
5414 }
5415 // Add the first object to the stack of traversed objects.
5416 aStack.push(a);
5417 bStack.push(b);
5418 // Recursively compare objects and arrays.
5419 if (areArrays) {
5420 // Compare array lengths to determine if a deep comparison is necessary.
5421 length = a.length;
5422 if (length !== b.length) {
5423 return false;
5424 }
5425 // Deep compare the contents, ignoring non-numeric properties.
5426 while (length--) {
5427 if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {
5428 return false;
5429 }
5430 }
5431 } else {
5432 // Deep compare objects.
5433 var keys = Object.keys(a);
5434 var key;
5435 length = keys.length;
5436 // Ensure that both objects contain the same number of properties before comparing deep equality.
5437 if (Object.keys(b).length !== length) {
5438 return false;
5439 }
5440 while (length--) {
5441 // Deep compare each member
5442 key = keys[length];
5443 if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {
5444 return false;
5445 }
5446 }
5447 }
5448 // Remove the first object from the stack of traversed objects.
5449 aStack.pop();
5450 bStack.pop();
5451 return true;
5452}
5453function unwrap(a) {
5454 if (isObservableArray(a)) {
5455 return a.slice();
5456 }
5457 if (isES6Map(a) || isObservableMap(a)) {
5458 return Array.from(a.entries());
5459 }
5460 if (isES6Set(a) || isObservableSet(a)) {
5461 return Array.from(a.entries());
5462 }
5463 return a;
5464}
5465
5466function makeIterable(iterator) {
5467 iterator[Symbol.iterator] = getSelf;
5468 return iterator;
5469}
5470function getSelf() {
5471 return this;
5472}
5473
5474function isAnnotation(thing) {
5475 return (
5476 // Can be function
5477 thing instanceof Object && typeof thing.annotationType_ === "string" && isFunction(thing.make_) && isFunction(thing.extend_)
5478 );
5479}
5480
5481/**
5482 * (c) Michel Weststrate 2015 - 2020
5483 * MIT Licensed
5484 *
5485 * Welcome to the mobx sources! To get a global overview of how MobX internally works,
5486 * this is a good place to start:
5487 * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74
5488 *
5489 * Source folders:
5490 * ===============
5491 *
5492 * - api/ Most of the public static methods exposed by the module can be found here.
5493 * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.
5494 * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.
5495 * - utils/ Utility stuff.
5496 *
5497 */
5498["Symbol", "Map", "Set"].forEach(function (m) {
5499 var g = getGlobal();
5500 if (typeof g[m] === "undefined") {
5501 die("MobX requires global '" + m + "' to be available or polyfilled");
5502 }
5503});
5504if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "object") {
5505 // See: https://github.com/andykog/mobx-devtools/
5506 __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({
5507 spy: spy,
5508 extras: {
5509 getDebugName: getDebugName
5510 },
5511 $mobx: $mobx
5512 });
5513}
5514
5515exports.$mobx = $mobx;
5516exports.FlowCancellationError = FlowCancellationError;
5517exports.ObservableMap = ObservableMap;
5518exports.ObservableSet = ObservableSet;
5519exports.Reaction = Reaction;
5520exports._allowStateChanges = allowStateChanges;
5521exports._allowStateChangesInsideComputed = runInAction;
5522exports._allowStateReadsEnd = allowStateReadsEnd;
5523exports._allowStateReadsStart = allowStateReadsStart;
5524exports._autoAction = autoAction;
5525exports._endAction = _endAction;
5526exports._getAdministration = getAdministration;
5527exports._getGlobalState = getGlobalState;
5528exports._interceptReads = interceptReads;
5529exports._isComputingDerivation = isComputingDerivation;
5530exports._resetGlobalState = resetGlobalState;
5531exports._startAction = _startAction;
5532exports.action = action;
5533exports.autorun = autorun;
5534exports.comparer = comparer;
5535exports.computed = computed;
5536exports.configure = configure;
5537exports.createAtom = createAtom;
5538exports.defineProperty = apiDefineProperty;
5539exports.entries = entries;
5540exports.extendObservable = extendObservable;
5541exports.flow = flow;
5542exports.flowResult = flowResult;
5543exports.get = get;
5544exports.getAtom = getAtom;
5545exports.getDebugName = getDebugName;
5546exports.getDependencyTree = getDependencyTree;
5547exports.getObserverTree = getObserverTree;
5548exports.has = has;
5549exports.intercept = intercept;
5550exports.isAction = isAction;
5551exports.isBoxedObservable = isObservableValue;
5552exports.isComputed = isComputed;
5553exports.isComputedProp = isComputedProp;
5554exports.isFlow = isFlow;
5555exports.isFlowCancellationError = isFlowCancellationError;
5556exports.isObservable = isObservable;
5557exports.isObservableArray = isObservableArray;
5558exports.isObservableMap = isObservableMap;
5559exports.isObservableObject = isObservableObject;
5560exports.isObservableProp = isObservableProp;
5561exports.isObservableSet = isObservableSet;
5562exports.keys = keys;
5563exports.makeAutoObservable = makeAutoObservable;
5564exports.makeObservable = makeObservable;
5565exports.observable = observable;
5566exports.observe = observe;
5567exports.onBecomeObserved = onBecomeObserved;
5568exports.onBecomeUnobserved = onBecomeUnobserved;
5569exports.onReactionError = onReactionError;
5570exports.override = override;
5571exports.ownKeys = apiOwnKeys;
5572exports.reaction = reaction;
5573exports.remove = remove;
5574exports.runInAction = runInAction;
5575exports.set = set;
5576exports.spy = spy;
5577exports.toJS = toJS;
5578exports.trace = trace;
5579exports.transaction = transaction;
5580exports.untracked = untracked;
5581exports.values = values;
5582exports.when = when;
5583//# sourceMappingURL=mobx.cjs.development.js.map