UNPKG

mobx

Version:

Simple, scalable state management.

1,399 lines (1,380 loc) 205 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var niceErrors = { 0: "Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'", 1: function _(annotationType, key) { return "Cannot apply '" + annotationType + "' to '" + key.toString() + "': Field not found."; }, /* 2(prop) { return `invalid decorator for '${prop.toString()}'` }, 3(prop) { return `Cannot decorate '${prop.toString()}': action can only be used on properties with a function value.` }, 4(prop) { return `Cannot decorate '${prop.toString()}': computed can only be used on getter properties.` }, */ 5: "'keys()' can only be used on observable objects, arrays, sets and maps", 6: "'values()' can only be used on observable objects, arrays, sets and maps", 7: "'entries()' can only be used on observable objects, arrays and maps", 8: "'set()' can only be used on observable objects, arrays and maps", 9: "'remove()' can only be used on observable objects, arrays and maps", 10: "'has()' can only be used on observable objects, arrays and maps", 11: "'get()' can only be used on observable objects, arrays and maps", 12: "Invalid annotation", 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)", 14: "Intercept handlers should return nothing or a change object", 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)", 16: "Modification exception: the internal structure of an observable array was changed.", 17: function _(index, length) { return "[mobx.array] Index out of bounds, " + index + " is larger than " + length; }, 18: "mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js", 19: function _(other) { return "Cannot initialize from classes that inherit from Map: " + other.constructor.name; }, 20: function _(other) { return "Cannot initialize map from " + other; }, 21: function _(dataStructure) { return "Cannot convert to map from '" + dataStructure + "'"; }, 22: "mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js", 23: "It is not possible to get index atoms from arrays", 24: function _(thing) { return "Cannot obtain administration from " + thing; }, 25: function _(property, name) { return "the entry '" + property + "' does not exist in the observable map '" + name + "'"; }, 26: "please specify a property", 27: function _(property, name) { return "no observable property '" + property.toString() + "' found on the observable object '" + name + "'"; }, 28: function _(thing) { return "Cannot obtain atom from " + thing; }, 29: "Expecting some object", 30: "invalid action stack. did you forget to finish an action?", 31: "missing option for computed: get", 32: function _(name, derivation) { return "Cycle detected in computation " + name + ": " + derivation; }, 33: function _(name) { 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?"; }, 34: function _(name) { return "[ComputedValue '" + name + "'] It is not possible to assign a new value to a computed value."; }, 35: "There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`", 36: "isolateGlobalState should be called before MobX is running any reactions", 37: function _(method) { return "[mobx] `observableArray." + method + "()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice()." + method + "()` instead"; }, 38: "'ownKeys()' can only be used on observable objects", 39: "'defineProperty()' can only be used on observable objects" }; var errors = niceErrors ; function die(error) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } { var e = typeof error === "string" ? error : errors[error]; if (typeof e === "function") e = e.apply(null, args); throw new Error("[MobX] " + e); } } var mockGlobal = {}; function getGlobal() { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } if (typeof self !== "undefined") { return self; } return mockGlobal; } // We shorten anything used > 5 times var assign = Object.assign; var getDescriptor = Object.getOwnPropertyDescriptor; var defineProperty = Object.defineProperty; var objectPrototype = Object.prototype; var EMPTY_ARRAY = []; Object.freeze(EMPTY_ARRAY); var EMPTY_OBJECT = {}; Object.freeze(EMPTY_OBJECT); var hasProxy = typeof Proxy !== "undefined"; var plainObjectString = /*#__PURE__*/Object.toString(); function assertProxies() { if (!hasProxy) { die( "`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`" ); } } function warnAboutProxyRequirement(msg) { if ( globalState.verifyProxies) { die("MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to " + msg); } } function getNextId() { return ++globalState.mobxGuid; } /** * Makes sure that the provided function is invoked at most once. */ function once(func) { var invoked = false; return function () { if (invoked) { return; } invoked = true; return func.apply(this, arguments); }; } var noop = function noop() {}; function isFunction(fn) { return typeof fn === "function"; } function isStringish(value) { var t = typeof value; switch (t) { case "string": case "symbol": case "number": return true; } return false; } function isObject(value) { return value !== null && typeof value === "object"; } function isPlainObject(value) { if (!isObject(value)) { return false; } var proto = Object.getPrototypeOf(value); if (proto == null) { return true; } var protoConstructor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof protoConstructor === "function" && protoConstructor.toString() === plainObjectString; } // https://stackoverflow.com/a/37865170 function isGenerator(obj) { var constructor = obj == null ? void 0 : obj.constructor; if (!constructor) { return false; } if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) { return true; } return false; } function addHiddenProp(object, propName, value) { defineProperty(object, propName, { enumerable: false, writable: true, configurable: true, value: value }); } function addHiddenFinalProp(object, propName, value) { defineProperty(object, propName, { enumerable: false, writable: false, configurable: true, value: value }); } function createInstanceofPredicate(name, theClass) { var propName = "isMobX" + name; theClass.prototype[propName] = true; return function (x) { return isObject(x) && x[propName] === true; }; } /** * Yields true for both native and observable Map, even across different windows. */ function isES6Map(thing) { return thing != null && Object.prototype.toString.call(thing) === "[object Map]"; } /** * Makes sure a Map is an instance of non-inherited native or observable Map. */ function isPlainES6Map(thing) { var mapProto = Object.getPrototypeOf(thing); var objectProto = Object.getPrototypeOf(mapProto); var nullProto = Object.getPrototypeOf(objectProto); return nullProto === null; } /** * Yields true for both native and observable Set, even across different windows. */ function isES6Set(thing) { return thing != null && Object.prototype.toString.call(thing) === "[object Set]"; } var hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefined"; /** * Returns the following: own enumerable keys and symbols. */ function getPlainObjectKeys(object) { var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway... if (!hasGetOwnPropertySymbols) { return keys; } var symbols = Object.getOwnPropertySymbols(object); if (!symbols.length) { return keys; } return [].concat(keys, symbols.filter(function (s) { return objectPrototype.propertyIsEnumerable.call(object, s); })); } // From Immer utils // Returns all own keys, including non-enumerable and symbolic var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) { return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj)); } : /* istanbul ignore next */Object.getOwnPropertyNames; function stringifyKey(key) { if (typeof key === "string") { return key; } if (typeof key === "symbol") { return key.toString(); } return new String(key).toString(); } function toPrimitive(value) { return value === null ? null : typeof value === "object" ? "" + value : value; } function hasProp(target, prop) { return objectPrototype.hasOwnProperty.call(target, prop); } // From Immer utils var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) { // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274 var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up ownKeys(target).forEach(function (key) { res[key] = getDescriptor(target, key); }); return res; }; function getFlag(flags, mask) { return !!(flags & mask); } function setFlag(flags, mask, newValue) { if (newValue) { flags |= mask; } else { flags &= ~mask; } return flags; } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _createForOfIteratorHelperLoose(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (t) return (t = t.call(r)).next.bind(t); if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var o = 0; return function () { return o >= r.length ? { done: !0 } : { done: !1, value: r[o++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } var storedAnnotationsSymbol = /*#__PURE__*/Symbol("mobx-stored-annotations"); /** * Creates a function that acts as * - decorator * - annotation object */ function createDecoratorAnnotation(annotation) { function decorator(target, property) { if (is20223Decorator(property)) { return annotation.decorate_20223_(target, property); } else { storeAnnotation(target, property, annotation); } } return Object.assign(decorator, annotation); } /** * Stores annotation to prototype, * so it can be inspected later by `makeObservable` called from constructor */ function storeAnnotation(prototype, key, annotation) { if (!hasProp(prototype, storedAnnotationsSymbol)) { addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol])); } // @override must override something if ( isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) { var fieldName = prototype.constructor.name + ".prototype." + key.toString(); die("'" + fieldName + "' is decorated with 'override', " + "but no such decorated member was found on prototype."); } // Cannot re-decorate assertNotDecorated(prototype, annotation, key); // Ignore override if (!isOverride(annotation)) { prototype[storedAnnotationsSymbol][key] = annotation; } } function assertNotDecorated(prototype, annotation, key) { if ( !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) { var fieldName = prototype.constructor.name + ".prototype." + key.toString(); var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_; var requestedAnnotationType = annotation.annotationType_; 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."); } } /** * Collects annotations from prototypes and stores them on target (instance) */ function collectStoredAnnotations(target) { if (!hasProp(target, storedAnnotationsSymbol)) { // if (__DEV__ && !target[storedAnnotationsSymbol]) { // die( // `No annotations were passed to makeObservable, but no decorated members have been found either` // ) // } // We need a copy as we will remove annotation from the list once it's applied. addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol])); } return target[storedAnnotationsSymbol]; } function is20223Decorator(context) { return typeof context == "object" && typeof context["kind"] == "string"; } function assert20223DecoratorType(context, types) { if ( !types.includes(context.kind)) { die("The decorator applied to '" + String(context.name) + "' cannot be used on a " + context.kind + " element"); } } var $mobx = /*#__PURE__*/Symbol("mobx administration"); var Atom = /*#__PURE__*/function () { /** * Create a new atom. For debugging purposes it is recommended to give it a name. * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management. */ function Atom(name_) { if (name_ === void 0) { name_ = "Atom@" + getNextId() ; } this.name_ = void 0; this.flags_ = 0; this.observers_ = new Set(); this.lastAccessedBy_ = 0; this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_; // onBecomeObservedListeners this.onBOL = void 0; // onBecomeUnobservedListeners this.onBUOL = void 0; this.name_ = name_; } // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed var _proto = Atom.prototype; _proto.onBO = function onBO() { if (this.onBOL) { this.onBOL.forEach(function (listener) { return listener(); }); } }; _proto.onBUO = function onBUO() { if (this.onBUOL) { this.onBUOL.forEach(function (listener) { return listener(); }); } } /** * Invoke this method to notify mobx that your atom has been used somehow. * Returns true if there is currently a reactive context. */; _proto.reportObserved = function reportObserved$1() { return reportObserved(this); } /** * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate. */; _proto.reportChanged = function reportChanged() { startBatch(); propagateChanged(this); endBatch(); }; _proto.toString = function toString() { return this.name_; }; return _createClass(Atom, [{ key: "isBeingObserved", get: function get() { return getFlag(this.flags_, Atom.isBeingObservedMask_); }, set: function set(newValue) { this.flags_ = setFlag(this.flags_, Atom.isBeingObservedMask_, newValue); } }, { key: "isPendingUnobservation", get: function get() { return getFlag(this.flags_, Atom.isPendingUnobservationMask_); }, set: function set(newValue) { this.flags_ = setFlag(this.flags_, Atom.isPendingUnobservationMask_, newValue); } }, { key: "diffValue", get: function get() { return getFlag(this.flags_, Atom.diffValueMask_) ? 1 : 0; }, set: function set(newValue) { this.flags_ = setFlag(this.flags_, Atom.diffValueMask_, newValue === 1 ? true : false); } }]); }(); Atom.isBeingObservedMask_ = 1; Atom.isPendingUnobservationMask_ = 2; Atom.diffValueMask_ = 4; var isAtom = /*#__PURE__*/createInstanceofPredicate("Atom", Atom); function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { if (onBecomeObservedHandler === void 0) { onBecomeObservedHandler = noop; } if (onBecomeUnobservedHandler === void 0) { onBecomeUnobservedHandler = noop; } var atom = new Atom(name); // default `noop` listener will not initialize the hook Set if (onBecomeObservedHandler !== noop) { onBecomeObserved(atom, onBecomeObservedHandler); } if (onBecomeUnobservedHandler !== noop) { onBecomeUnobserved(atom, onBecomeUnobservedHandler); } return atom; } function identityComparer(a, b) { return a === b; } function structuralComparer(a, b) { return deepEqual(a, b); } function shallowComparer(a, b) { return deepEqual(a, b, 1); } function defaultComparer(a, b) { if (Object.is) { return Object.is(a, b); } return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b; } var comparer = { identity: identityComparer, structural: structuralComparer, "default": defaultComparer, shallow: shallowComparer }; function deepEnhancer(v, _, name) { // it is an observable already, done if (isObservable(v)) { return v; } // something that can be converted and mutated? if (Array.isArray(v)) { return observable.array(v, { name: name }); } if (isPlainObject(v)) { return observable.object(v, undefined, { name: name }); } if (isES6Map(v)) { return observable.map(v, { name: name }); } if (isES6Set(v)) { return observable.set(v, { name: name }); } if (typeof v === "function" && !isAction(v) && !isFlow(v)) { if (isGenerator(v)) { return flow(v); } else { return autoAction(name, v); } } return v; } function shallowEnhancer(v, _, name) { if (v === undefined || v === null) { return v; } if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) { return v; } if (Array.isArray(v)) { return observable.array(v, { name: name, deep: false }); } if (isPlainObject(v)) { return observable.object(v, undefined, { name: name, deep: false }); } if (isES6Map(v)) { return observable.map(v, { name: name, deep: false }); } if (isES6Set(v)) { return observable.set(v, { name: name, deep: false }); } { die("The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets"); } } function referenceEnhancer(newValue) { // never turn into an observable return newValue; } function refStructEnhancer(v, oldValue) { if ( isObservable(v)) { die("observable.struct should not be used with observable values"); } if (deepEqual(v, oldValue)) { return oldValue; } return v; } var OVERRIDE = "override"; var override = /*#__PURE__*/createDecoratorAnnotation({ annotationType_: OVERRIDE, make_: make_, extend_: extend_, decorate_20223_: decorate_20223_ }); function isOverride(annotation) { return annotation.annotationType_ === OVERRIDE; } function make_(adm, key) { // Must not be plain object if ( adm.isPlainObject_) { die("Cannot apply '" + this.annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + this.annotationType_ + "' cannot be used on plain objects.")); } // Must override something if ( !hasProp(adm.appliedAnnotations_, key)) { die("'" + adm.name_ + "." + key.toString() + "' is annotated with '" + this.annotationType_ + "', " + "but no such annotated member was found on prototype."); } return 0 /* MakeResult.Cancel */; } function extend_(adm, key, descriptor, proxyTrap) { die("'" + this.annotationType_ + "' can only be used with 'makeObservable'"); } function decorate_20223_(desc, context) { console.warn("'" + this.annotationType_ + "' cannot be used with decorators - this is a no-op"); } function createActionAnnotation(name, options) { return { annotationType_: name, options_: options, make_: make_$1, extend_: extend_$1, decorate_20223_: decorate_20223_$1 }; } function make_$1(adm, key, descriptor, source) { var _this$options_; // bound if ((_this$options_ = this.options_) != null && _this$options_.bound) { return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */; } // own if (source === adm.target_) { return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */; } // prototype if (isAction(descriptor.value)) { // A prototype could have been annotated already by other constructor, // rest of the proto chain must be annotated already return 1 /* MakeResult.Break */; } var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false); defineProperty(source, key, actionDescriptor); return 2 /* MakeResult.Continue */; } function extend_$1(adm, key, descriptor, proxyTrap) { var actionDescriptor = createActionDescriptor(adm, this, key, descriptor); return adm.defineProperty_(key, actionDescriptor, proxyTrap); } function decorate_20223_$1(mthd, context) { { assert20223DecoratorType(context, ["method", "field"]); } var kind = context.kind, name = context.name, addInitializer = context.addInitializer; var ann = this; var _createAction = function _createAction(m) { var _ann$options_$name, _ann$options_, _ann$options_$autoAct, _ann$options_2; return createAction((_ann$options_$name = (_ann$options_ = ann.options_) == null ? void 0 : _ann$options_.name) != null ? _ann$options_$name : name.toString(), m, (_ann$options_$autoAct = (_ann$options_2 = ann.options_) == null ? void 0 : _ann$options_2.autoAction) != null ? _ann$options_$autoAct : false); }; if (kind == "field") { return function (initMthd) { var _ann$options_3; var mthd = initMthd; if (!isAction(mthd)) { mthd = _createAction(mthd); } if ((_ann$options_3 = ann.options_) != null && _ann$options_3.bound) { mthd = mthd.bind(this); mthd.isMobxAction = true; } return mthd; }; } if (kind == "method") { var _this$options_2; if (!isAction(mthd)) { mthd = _createAction(mthd); } if ((_this$options_2 = this.options_) != null && _this$options_2.bound) { addInitializer(function () { var self = this; var bound = self[name].bind(self); bound.isMobxAction = true; self[name] = bound; }); } return mthd; } die("Cannot apply '" + ann.annotationType_ + "' to '" + String(name) + "' (kind: " + kind + "):" + ("\n'" + ann.annotationType_ + "' can only be used on properties with a function value.")); } function assertActionDescriptor(adm, _ref, key, _ref2) { var annotationType_ = _ref.annotationType_; var value = _ref2.value; if ( !isFunction(value)) { die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a function value.")); } } function createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes safeDescriptors) { var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2; if (safeDescriptors === void 0) { safeDescriptors = globalState.safeDescriptors; } assertActionDescriptor(adm, annotation, key, descriptor); var value = descriptor.value; if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) { var _adm$proxy_; value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); } return { value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false, // https://github.com/mobxjs/mobx/discussions/3140 (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined), // Non-configurable for classes // prevents accidental field redefinition in subclass configurable: safeDescriptors ? adm.isPlainObject_ : true, // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058 enumerable: false, // Non-obsevable, therefore non-writable // Also prevents rewriting in subclass constructor writable: safeDescriptors ? false : true }; } function createFlowAnnotation(name, options) { return { annotationType_: name, options_: options, make_: make_$2, extend_: extend_$2, decorate_20223_: decorate_20223_$2 }; } function make_$2(adm, key, descriptor, source) { var _this$options_; // own if (source === adm.target_) { return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */; } // prototype // bound - must annotate protos to support super.flow() if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) { if (this.extend_(adm, key, descriptor, false) === null) { return 0 /* MakeResult.Cancel */; } } if (isFlow(descriptor.value)) { // A prototype could have been annotated already by other constructor, // rest of the proto chain must be annotated already return 1 /* MakeResult.Break */; } var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false); defineProperty(source, key, flowDescriptor); return 2 /* MakeResult.Continue */; } function extend_$2(adm, key, descriptor, proxyTrap) { var _this$options_2; var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound); return adm.defineProperty_(key, flowDescriptor, proxyTrap); } function decorate_20223_$2(mthd, context) { var _this$options_3; { assert20223DecoratorType(context, ["method"]); } var name = context.name, addInitializer = context.addInitializer; if (!isFlow(mthd)) { mthd = flow(mthd); } if ((_this$options_3 = this.options_) != null && _this$options_3.bound) { addInitializer(function () { var self = this; var bound = self[name].bind(self); bound.isMobXFlow = true; self[name] = bound; }); } return mthd; } function assertFlowDescriptor(adm, _ref, key, _ref2) { var annotationType_ = _ref.annotationType_; var value = _ref2.value; if ( !isFunction(value)) { die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a generator function value.")); } } function createFlowDescriptor(adm, annotation, key, descriptor, bound, // provides ability to disable safeDescriptors for prototypes safeDescriptors) { if (safeDescriptors === void 0) { safeDescriptors = globalState.safeDescriptors; } assertFlowDescriptor(adm, annotation, key, descriptor); var value = descriptor.value; // In case of flow.bound, the descriptor can be from already annotated prototype if (!isFlow(value)) { value = flow(value); } if (bound) { var _adm$proxy_; // We do not keep original function around, so we bind the existing flow value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); // This is normally set by `flow`, but `bind` returns new function... value.isMobXFlow = true; } return { value: value, // Non-configurable for classes // prevents accidental field redefinition in subclass configurable: safeDescriptors ? adm.isPlainObject_ : true, // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058 enumerable: false, // Non-obsevable, therefore non-writable // Also prevents rewriting in subclass constructor writable: safeDescriptors ? false : true }; } function createComputedAnnotation(name, options) { return { annotationType_: name, options_: options, make_: make_$3, extend_: extend_$3, decorate_20223_: decorate_20223_$3 }; } function make_$3(adm, key, descriptor) { return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */; } function extend_$3(adm, key, descriptor, proxyTrap) { assertComputedDescriptor(adm, this, key, descriptor); return adm.defineComputedProperty_(key, _extends({}, this.options_, { get: descriptor.get, set: descriptor.set }), proxyTrap); } function decorate_20223_$3(get, context) { { assert20223DecoratorType(context, ["getter"]); } var ann = this; var key = context.name, addInitializer = context.addInitializer; addInitializer(function () { var adm = asObservableObject(this)[$mobx]; var options = _extends({}, ann.options_, { get: get, context: this }); options.name || (options.name = adm.name_ + "." + key.toString() ); adm.values_.set(key, new ComputedValue(options)); }); return function () { return this[$mobx].getObservablePropValue_(key); }; } function assertComputedDescriptor(adm, _ref, key, _ref2) { var annotationType_ = _ref.annotationType_; var get = _ref2.get; if ( !get) { die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on getter(+setter) properties.")); } } function createObservableAnnotation(name, options) { return { annotationType_: name, options_: options, make_: make_$4, extend_: extend_$4, decorate_20223_: decorate_20223_$4 }; } function make_$4(adm, key, descriptor) { return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */; } function extend_$4(adm, key, descriptor, proxyTrap) { var _this$options_$enhanc, _this$options_; assertObservableDescriptor(adm, this, key, descriptor); return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap); } function decorate_20223_$4(desc, context) { { if (context.kind === "field") { throw die("Please use `@observable accessor " + String(context.name) + "` instead of `@observable " + String(context.name) + "`"); } assert20223DecoratorType(context, ["accessor"]); } var ann = this; var kind = context.kind, name = context.name; // The laziness here is not ideal... It's a workaround to how 2022.3 Decorators are implemented: // `addInitializer` callbacks are executed _before_ any accessors are defined (instead of the ideal-for-us right after each). // This means that, if we were to do our stuff in an `addInitializer`, we'd attempt to read a private slot // before it has been initialized. The runtime doesn't like that and throws a `Cannot read private member // from an object whose class did not declare it` error. // TODO: it seems that this will not be required anymore in the final version of the spec // See TODO: link var initializedObjects = new WeakSet(); function initializeObservable(target, value) { var _ann$options_$enhance, _ann$options_; var adm = asObservableObject(target)[$mobx]; var observable = new ObservableValue(value, (_ann$options_$enhance = (_ann$options_ = ann.options_) == null ? void 0 : _ann$options_.enhancer) != null ? _ann$options_$enhance : deepEnhancer, adm.name_ + "." + name.toString() , false); adm.values_.set(name, observable); initializedObjects.add(target); } if (kind == "accessor") { return { get: function get() { if (!initializedObjects.has(this)) { initializeObservable(this, desc.get.call(this)); } return this[$mobx].getObservablePropValue_(name); }, set: function set(value) { if (!initializedObjects.has(this)) { initializeObservable(this, value); } return this[$mobx].setObservablePropValue_(name, value); }, init: function init(value) { if (!initializedObjects.has(this)) { initializeObservable(this, value); } return value; } }; } return; } function assertObservableDescriptor(adm, _ref, key, descriptor) { var annotationType_ = _ref.annotationType_; if ( !("value" in descriptor)) { die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' cannot be used on getter/setter properties")); } } var AUTO = "true"; var autoAnnotation = /*#__PURE__*/createAutoAnnotation(); function createAutoAnnotation(options) { return { annotationType_: AUTO, options_: options, make_: make_$5, extend_: extend_$5, decorate_20223_: decorate_20223_$5 }; } function make_$5(adm, key, descriptor, source) { var _this$options_3, _this$options_4; // getter -> computed if (descriptor.get) { return computed.make_(adm, key, descriptor, source); } // lone setter -> action setter if (descriptor.set) { // TODO make action applicable to setter and delegate to action.make_ var set = createAction(key.toString(), descriptor.set); // own if (source === adm.target_) { return adm.defineProperty_(key, { configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true, set: set }) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */; } // proto defineProperty(source, key, { configurable: true, set: set }); return 2 /* MakeResult.Continue */; } // function on proto -> autoAction/flow if (source !== adm.target_ && typeof descriptor.value === "function") { var _this$options_2; if (isGenerator(descriptor.value)) { var _this$options_; var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow; return flowAnnotation.make_(adm, key, descriptor, source); } var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction; return actionAnnotation.make_(adm, key, descriptor, source); } // other -> observable // Copy props from proto as well, see test: // "decorate should work with Object.create" var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable; // if function respect autoBind option if (typeof descriptor.value === "function" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) { var _adm$proxy_; descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); } return observableAnnotation.make_(adm, key, descriptor, source); } function extend_$5(adm, key, descriptor, proxyTrap) { var _this$options_5, _this$options_6; // getter -> computed if (descriptor.get) { return computed.extend_(adm, key, descriptor, proxyTrap); } // lone setter -> action setter if (descriptor.set) { // TODO make action applicable to setter and delegate to action.extend_ return adm.defineProperty_(key, { configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true, set: createAction(key.toString(), descriptor.set) }, proxyTrap); } // other -> observable // if function respect autoBind option if (typeof descriptor.value === "function" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) { var _adm$proxy_2; descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_); } var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable; return observableAnnotation.extend_(adm, key, descriptor, proxyTrap); } function decorate_20223_$5(desc, context) { die("'" + this.annotationType_ + "' cannot be used as a decorator"); } var OBSERVABLE = "observable"; var OBSERVABLE_REF = "observable.ref"; var OBSERVABLE_SHALLOW = "observable.shallow"; var OBSERVABLE_STRUCT = "observable.struct"; // Predefined bags of create observable options, to avoid allocating temporarily option objects // in the majority of cases var defaultCreateObservableOptions = { deep: true, name: undefined, defaultDecorator: undefined, proxy: true }; Object.freeze(defaultCreateObservableOptions); function asCreateObservableOptions(thing) { return thing || defaultCreateObservableOptions; } var observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE); var observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, { enhancer: referenceEnhancer }); var observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, { enhancer: shallowEnhancer }); var observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, { enhancer: refStructEnhancer }); var observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation); function getEnhancerFromOptions(options) { return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator); } function getAnnotationFromOptions(options) { var _options$defaultDecor; return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined; } function getEnhancerFromAnnotation(annotation) { var _annotation$options_$, _annotation$options_; return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer; } /** * Turns an object, array or function into a reactive structure. * @param v the value which should become observable. */ function createObservable(v, arg2, arg3) { // @observable someProp; (2022.3 Decorators) if (is20223Decorator(arg2)) { return observableAnnotation.decorate_20223_(v, arg2); } // @observable someProp; if (isStringish(arg2)) { storeAnnotation(v, arg2, observableAnnotation); return; } // already observable - ignore if (isObservable(v)) { return v; } // plain object if (isPlainObject(v)) { return observable.object(v, arg2, arg3); } // Array if (Array.isArray(v)) { return observable.array(v, arg2); } // Map if (isES6Map(v)) { return observable.map(v, arg2); } // Set if (isES6Set(v)) { return observable.set(v, arg2); } // other object - ignore if (typeof v === "object" && v !== null) { return v; } // anything else return observable.box(v, arg2); } assign(createObservable, observableDecoratorAnnotation); var observableFactories = { box: function box(value, options) { var o = asCreateObservableOptions(options); return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals); }, array: function array(initialValues, options) { var o = asCreateObservableOptions(options); return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name); }, map: function map(initialValues, options) { var o = asCreateObservableOptions(options); return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name); }, set: function set(initialValues, options) { var o = asCreateObservableOptions(options); return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name); }, object: function object(props, decorators, options) { return initObservable(function () { return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators); }); }, ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation), shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation), deep: observableDecoratorAnnotation, struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation) }; // eslint-disable-next-line var observable = /*#__PURE__*/assign(createObservable, observableFactories); var COMPUTED = "computed"; var COMPUTED_STRUCT = "computed.struct"; var computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED); var computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, { equals: comparer.structural }); /** * Decorator for class properties: @computed get value() { return expr; }. * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`; */ var computed = function computed(arg1, arg2) { if (is20223Decorator(arg2)) { // @computed (2022.3 Decorators) return computedAnnotation.decorate_20223_(arg1, arg2); } if (isStringish(arg2)) { // @computed return storeAnnotation(arg1, arg2, computedAnnotation); } if (isPlainObject(arg1)) { // @computed({ options }) return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1)); } // computed(expr, options?) { if (!isFunction(arg1)) { die("First argument to `computed` should be an expression."); } if (isFunction(arg2)) { die("A setter as second argument is no longer supported, use `{ set: fn }` option instead"); } } var opts = isPlainObject(arg2) ? arg2 : {}; opts.get = arg1; opts.name || (opts.name = arg1.name || ""); /* for generated name */ return new ComputedValue(opts); }; Object.assign(computed, computedAnnotation); computed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation); var _getDescriptor$config, _getDescriptor; // we don't use globalState for these in order to avoid possible issues with multiple // mobx versions var currentActionId = 0; var nextActionId = 1; var isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, "name")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object var tmpNameDescriptor = { value: "action", configurable: true, writable: false, enumerable: false }; function createAction(actionName, fn, autoAction, ref) { if (autoAction === void 0) { autoAction = false; } { if (!isFunction(fn)) { die("`action` can only be invoked on functions"); } if (typeof actionName !== "string" || !actionName) { die("actions should have valid names, got: '" + actionName + "'"); } } function res() { return executeAction(actionName, autoAction, fn, ref || this, arguments); } res.isMobxAction = true; res.toString = function () { return fn.toString(); }; if (isFunctionNameConfigurable) { tmpNameDescriptor.value = actionName; defineProperty(res, "name", tmpNameDescriptor); } return res; } function executeAction(actionName, canRunAsDerivation, fn, scope, args) { var runInfo = _startAction(actionName, canRunAsDerivation, scope, args); try { return fn.apply(scope, args); } catch (err) { runInfo.error_ = err; throw err; } finally { _endAction(runInfo); } } function _startAction(actionName, canRunAsDerivation, // true for autoAction scope, args) { var notifySpy_ = isSpyEnabled() && !!actionName; var startTime_ = 0; if ( notifySpy_) { startTime_ = Date.now(); var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY; spyReportStart({ type: ACTION, name: actionName, object: scope, arguments: flattenedArgs }); } var prevDerivation_ = globalState.trackingDerivation; var runAsAction = !canRunAsDerivation || !prevDerivation_; startBatch(); var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow if (runAsAction) { untrackedStart(); prevAllowStateChanges_ = allowStateChangesStart(true); } var prevAllowStateReads_ = allowStateReadsStart(true); var runInfo = { runAsAction_: runAsAction, prevDerivation_: prevDerivation_, prevAllowStateChanges_: prevAllowStateChanges_, prevAllowStateReads_: prevAllowStateReads_, notifySpy_: notifySpy_, startTime_: startTime_, actionId_: nextActionId++, parentActionId_: currentActionId }; currentActionId = runInfo.actionId_; return runInfo; } function _endAction(runInfo) { if (currentActionId !== runInfo.actionId_) { die(30); } currentActionId = runInfo.parentActionId_; if (runInfo.error_ !== undefined) { globalState.suppressReactionErrors = true; } allowStateChangesEnd(runInfo.prevAllowStateChanges_); allowStateReadsEnd(runInfo.prevAllowStateReads_); endBatch(); if (runInfo.runAsAction_) { untrackedEnd(runInfo.prevDerivation_); } if ( runInfo.notifySpy_) { spyReportEnd({ time: Date.now() - runInfo.startTime_ }); } globalState.suppressReactionErrors = false; } function allowStateChanges(allowStateChanges, func) { var prev = allowStateChangesStart(allowStateChanges); try { return func(); } finally { allowStateChangesEnd(prev); } } function allowStateChangesStart(allowStateChanges) { var prev = globalState.allowStateChanges; globalState.allowStateChanges = allowStateChanges; return prev; } function allowStateChangesEnd(prev) { globalState.allowStateChanges = prev; } var CREATE = "create"; var ObservableValue = /*#__PURE__*/function (_Atom) { function ObservableValue(value, enhancer, name_, notifySpy, equals) { var _this; if (name_ === void 0) { name_ = "ObservableValue@" + getNextId() ; } if (notifySpy === void 0) { notifySpy = true; } if (equals === void 0) { equals = comparer["default"]; } _this = _Atom.call(this, name_) || this; _this.enhancer = void 0; _this.name_ = void 0; _this.equals = void 0; _this.hasUnreportedChange_ = false; _this.interceptors_ = void 0; _this.changeListeners_ = void 0; _this.value_ = void 0; _this.dehancer = void 0; _this.enhancer = enhancer; _this.name_ = name_; _this.equals = equals; _this.value_ = enhancer(value, undefined, name_); if ( notifySpy && isSpyEnabled()) { // only notify spy if this is a stand-alone observable spyReport({ type: CREATE, object: _this, observableKind: "value", debugObjectName: _this.name_, newValue: "" + _this.value_ }); } return _this; } _inheritsLoose(ObservableValue, _Atom); var _proto = ObservableValue.prototype; _proto.dehanceValue = function dehanceValue(value) { if (this.dehancer !== undefined) { return this.dehancer(value); } return value; }; _proto.set = function set(newValue) { var oldValue = this.value_; newValue