mobx-state-tree 3.14.1 → 3.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { isComputedProp, isObservableProp, createAtom, action, _allowStateChangesInsideComputed, reaction, computed, runInAction, observable, values, entries, isObservableArray, getAtom, $mobx, ObservableMap, _interceptReads, intercept, observe, _getAdministration, set } from 'mobx';
1
+ import { isComputedProp, isObservableProp, createAtom, action, _allowStateChangesInsideComputed, reaction, computed, runInAction, observable, values, entries, isObservableArray, $mobx, getAtom, ObservableMap, _interceptReads, intercept, observe, _getAdministration, set } from 'mobx';
2
2
 
3
3
  var livelinessChecking = "warn";
4
4
  /**
@@ -34,7 +34,6 @@ function setLivelynessChecking(mode) {
34
34
  }
35
35
 
36
36
  /**
37
- * @internal
38
37
  * @hidden
39
38
  */
40
39
  var Hook;
@@ -47,18 +46,18 @@ var Hook;
47
46
  })(Hook || (Hook = {}));
48
47
 
49
48
  /*! *****************************************************************************
50
- Copyright (c) Microsoft Corporation. All rights reserved.
51
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
52
- this file except in compliance with the License. You may obtain a copy of the
53
- License at http://www.apache.org/licenses/LICENSE-2.0
49
+ Copyright (c) Microsoft Corporation.
54
50
 
55
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
56
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
57
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
58
- MERCHANTABLITY OR NON-INFRINGEMENT.
51
+ Permission to use, copy, modify, and/or distribute this software for any
52
+ purpose with or without fee is hereby granted.
59
53
 
60
- See the Apache Version 2.0 License for specific language governing permissions
61
- and limitations under the License.
54
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
55
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
56
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
57
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
58
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
59
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
60
+ PERFORMANCE OF THIS SOFTWARE.
62
61
  ***************************************************************************** */
63
62
  /* global Reflect, Promise */
64
63
 
@@ -105,15 +104,44 @@ function __decorate(decorators, target, key, desc) {
105
104
  return c > 3 && r && Object.defineProperty(target, key, r), r;
106
105
  }
107
106
 
107
+ function __generator(thisArg, body) {
108
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
109
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
110
+ function verb(n) { return function (v) { return step([n, v]); }; }
111
+ function step(op) {
112
+ if (f) throw new TypeError("Generator is already executing.");
113
+ while (_) try {
114
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
115
+ if (y = 0, t) op = [op[0] & 2, t.value];
116
+ switch (op[0]) {
117
+ case 0: case 1: t = op; break;
118
+ case 4: _.label++; return { value: op[1], done: false };
119
+ case 5: _.label++; y = op[1]; op = [0]; continue;
120
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
121
+ default:
122
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
123
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
124
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
125
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
126
+ if (t[2]) _.ops.pop();
127
+ _.trys.pop(); continue;
128
+ }
129
+ op = body.call(thisArg, _);
130
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
131
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
132
+ }
133
+ }
134
+
108
135
  function __values(o) {
109
- var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
136
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
110
137
  if (m) return m.call(o);
111
- return {
138
+ if (o && typeof o.length === "number") return {
112
139
  next: function () {
113
140
  if (o && i >= o.length) o = void 0;
114
141
  return { value: o && o[i++], done: !o };
115
142
  }
116
143
  };
144
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
117
145
  }
118
146
 
119
147
  function __read(o, n) {
@@ -821,7 +849,7 @@ function getPropertyMembers(typeOrNode) {
821
849
  */
822
850
  function getMembers(target) {
823
851
  var type = getStateTreeNode(target).type;
824
- var reflected = __assign({}, getPropertyMembers(type), { actions: [], volatile: [], views: [] });
852
+ var reflected = __assign(__assign({}, getPropertyMembers(type)), { actions: [], volatile: [], views: [] });
825
853
  var props = Object.getOwnPropertyNames(target);
826
854
  props.forEach(function (key) {
827
855
  if (key in reflected.properties)
@@ -966,28 +994,28 @@ var BaseNode = /** @class */ (function () {
966
994
  get: function () {
967
995
  return this._subpath;
968
996
  },
969
- enumerable: true,
997
+ enumerable: false,
970
998
  configurable: true
971
999
  });
972
1000
  Object.defineProperty(BaseNode.prototype, "subpathUponDeath", {
973
1001
  get: function () {
974
1002
  return this._subpathUponDeath;
975
1003
  },
976
- enumerable: true,
1004
+ enumerable: false,
977
1005
  configurable: true
978
1006
  });
979
1007
  Object.defineProperty(BaseNode.prototype, "pathUponDeath", {
980
1008
  get: function () {
981
1009
  return this._pathUponDeath;
982
1010
  },
983
- enumerable: true,
1011
+ enumerable: false,
984
1012
  configurable: true
985
1013
  });
986
1014
  Object.defineProperty(BaseNode.prototype, "value", {
987
1015
  get: function () {
988
1016
  return this.type.getValue(this);
989
1017
  },
990
- enumerable: true,
1018
+ enumerable: false,
991
1019
  configurable: true
992
1020
  });
993
1021
  Object.defineProperty(BaseNode.prototype, "state", {
@@ -1002,7 +1030,7 @@ var BaseNode = /** @class */ (function () {
1002
1030
  this.aliveAtom.reportChanged();
1003
1031
  }
1004
1032
  },
1005
- enumerable: true,
1033
+ enumerable: false,
1006
1034
  configurable: true
1007
1035
  });
1008
1036
  BaseNode.prototype.fireInternalHook = function (name) {
@@ -1020,7 +1048,7 @@ var BaseNode = /** @class */ (function () {
1020
1048
  get: function () {
1021
1049
  return this._parent;
1022
1050
  },
1023
- enumerable: true,
1051
+ enumerable: false,
1024
1052
  configurable: true
1025
1053
  });
1026
1054
  BaseNode.prototype.baseSetParent = function (parent, subpath) {
@@ -1038,7 +1066,7 @@ var BaseNode = /** @class */ (function () {
1038
1066
  get: function () {
1039
1067
  return this.getEscapedPath(true);
1040
1068
  },
1041
- enumerable: true,
1069
+ enumerable: false,
1042
1070
  configurable: true
1043
1071
  });
1044
1072
  BaseNode.prototype.getEscapedPath = function (reportObserved) {
@@ -1060,21 +1088,21 @@ var BaseNode = /** @class */ (function () {
1060
1088
  get: function () {
1061
1089
  return this.parent === null;
1062
1090
  },
1063
- enumerable: true,
1091
+ enumerable: false,
1064
1092
  configurable: true
1065
1093
  });
1066
1094
  Object.defineProperty(BaseNode.prototype, "isAlive", {
1067
1095
  get: function () {
1068
1096
  return this.state !== NodeLifeCycle.DEAD;
1069
1097
  },
1070
- enumerable: true,
1098
+ enumerable: false,
1071
1099
  configurable: true
1072
1100
  });
1073
1101
  Object.defineProperty(BaseNode.prototype, "isDetaching", {
1074
1102
  get: function () {
1075
1103
  return this.state === NodeLifeCycle.DETACHING;
1076
1104
  },
1077
- enumerable: true,
1105
+ enumerable: false,
1078
1106
  configurable: true
1079
1107
  });
1080
1108
  Object.defineProperty(BaseNode.prototype, "observableIsAlive", {
@@ -1085,7 +1113,7 @@ var BaseNode = /** @class */ (function () {
1085
1113
  this.aliveAtom.reportObserved();
1086
1114
  return this.isAlive;
1087
1115
  },
1088
- enumerable: true,
1116
+ enumerable: false,
1089
1117
  configurable: true
1090
1118
  });
1091
1119
  BaseNode.prototype.baseFinalizeCreation = function (whenFinalized) {
@@ -1155,7 +1183,7 @@ var ScalarNode = /** @class */ (function (_super) {
1155
1183
  throw fail$1("This scalar node is not part of a tree");
1156
1184
  return this.parent.root;
1157
1185
  },
1158
- enumerable: true,
1186
+ enumerable: false,
1159
1187
  configurable: true
1160
1188
  });
1161
1189
  ScalarNode.prototype.setParent = function (newParent, subpath) {
@@ -1185,7 +1213,7 @@ var ScalarNode = /** @class */ (function (_super) {
1185
1213
  get: function () {
1186
1214
  return freeze(this.getSnapshot());
1187
1215
  },
1188
- enumerable: true,
1216
+ enumerable: false,
1189
1217
  configurable: true
1190
1218
  });
1191
1219
  ScalarNode.prototype.getSnapshot = function () {
@@ -1284,10 +1312,12 @@ var ObjectNode = /** @class */ (function (_super) {
1284
1312
  this._applySnapshot(snapshot);
1285
1313
  };
1286
1314
  ObjectNode.prototype.createObservableInstanceIfNeeded = function () {
1287
- var e_1, _a;
1288
- if (this._observableInstanceState !== 0 /* UNINITIALIZED */) {
1289
- return;
1315
+ if (this._observableInstanceState === 0 /* UNINITIALIZED */) {
1316
+ this.createObservableInstance();
1290
1317
  }
1318
+ };
1319
+ ObjectNode.prototype.createObservableInstance = function () {
1320
+ var e_1, _a;
1291
1321
  if (devMode()) {
1292
1322
  if (this.state !== NodeLifeCycle.INITIALIZING) {
1293
1323
  // istanbul ignore next
@@ -1353,7 +1383,7 @@ var ObjectNode = /** @class */ (function (_super) {
1353
1383
  var parent = this.parent;
1354
1384
  return parent ? parent.root : this;
1355
1385
  },
1356
- enumerable: true,
1386
+ enumerable: false,
1357
1387
  configurable: true
1358
1388
  });
1359
1389
  ObjectNode.prototype.clearParent = function () {
@@ -1438,7 +1468,7 @@ var ObjectNode = /** @class */ (function (_super) {
1438
1468
  get: function () {
1439
1469
  return freeze(this.getSnapshot());
1440
1470
  },
1441
- enumerable: true,
1471
+ enumerable: false,
1442
1472
  configurable: true
1443
1473
  });
1444
1474
  // NOTE: we use this method to get snapshot without creating @computed overhead
@@ -1531,7 +1561,7 @@ var ObjectNode = /** @class */ (function (_super) {
1531
1561
  get: function () {
1532
1562
  return this.root.isProtectionEnabled;
1533
1563
  },
1534
- enumerable: true,
1564
+ enumerable: false,
1535
1565
  configurable: true
1536
1566
  });
1537
1567
  ObjectNode.prototype.assertWritable = function (context) {
@@ -1745,7 +1775,7 @@ var ObjectNode = /** @class */ (function (_super) {
1745
1775
  };
1746
1776
  __decorate([
1747
1777
  action
1748
- ], ObjectNode.prototype, "createObservableInstanceIfNeeded", null);
1778
+ ], ObjectNode.prototype, "createObservableInstance", null);
1749
1779
  __decorate([
1750
1780
  computed
1751
1781
  ], ObjectNode.prototype, "snapshot", null);
@@ -1831,7 +1861,7 @@ var BaseType = /** @class */ (function () {
1831
1861
  // istanbul ignore next
1832
1862
  throw fail$1("Factory.Type should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.Type`");
1833
1863
  },
1834
- enumerable: true,
1864
+ enumerable: false,
1835
1865
  configurable: true
1836
1866
  });
1837
1867
  Object.defineProperty(BaseType.prototype, "TypeWithoutSTN", {
@@ -1839,7 +1869,7 @@ var BaseType = /** @class */ (function () {
1839
1869
  // istanbul ignore next
1840
1870
  throw fail$1("Factory.TypeWithoutSTN should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.TypeWithoutSTN`");
1841
1871
  },
1842
- enumerable: true,
1872
+ enumerable: false,
1843
1873
  configurable: true
1844
1874
  });
1845
1875
  Object.defineProperty(BaseType.prototype, "SnapshotType", {
@@ -1847,7 +1877,7 @@ var BaseType = /** @class */ (function () {
1847
1877
  // istanbul ignore next
1848
1878
  throw fail$1("Factory.SnapshotType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.SnapshotType`");
1849
1879
  },
1850
- enumerable: true,
1880
+ enumerable: false,
1851
1881
  configurable: true
1852
1882
  });
1853
1883
  Object.defineProperty(BaseType.prototype, "CreationType", {
@@ -1855,7 +1885,7 @@ var BaseType = /** @class */ (function () {
1855
1885
  // istanbul ignore next
1856
1886
  throw fail$1("Factory.CreationType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.CreationType`");
1857
1887
  },
1858
- enumerable: true,
1888
+ enumerable: false,
1859
1889
  configurable: true
1860
1890
  });
1861
1891
  __decorate([
@@ -2092,7 +2122,7 @@ var RunningAction = /** @class */ (function () {
2092
2122
  get: function () {
2093
2123
  return this.flowsPending > 0;
2094
2124
  },
2095
- enumerable: true,
2125
+ enumerable: false,
2096
2126
  configurable: true
2097
2127
  });
2098
2128
  return RunningAction;
@@ -2128,7 +2158,7 @@ function createActionTrackingMiddleware2(middlewareHooks) {
2128
2158
  ? runningActions.get(call.parentActionEvent)
2129
2159
  : undefined;
2130
2160
  if (call.type === "action") {
2131
- var newCall = __assign({}, call, {
2161
+ var newCall = __assign(__assign({}, call), {
2132
2162
  // make a shallow copy of the parent action env
2133
2163
  env: parentRunningAction && parentRunningAction.call.env, parentCall: parentRunningAction && parentRunningAction.call });
2134
2164
  var passesFilter = !middlewareHooks.filter || middlewareHooks.filter(newCall);
@@ -2472,7 +2502,7 @@ function createActionInvoker(target, name, fn) {
2472
2502
  * Middleware can be used to intercept any action is invoked on the subtree where it is attached.
2473
2503
  * If a tree is protected (by default), this means that any mutation of the tree will pass through your middleware.
2474
2504
  *
2475
- * For more details, see the [middleware docs](../middleware.md)
2505
+ * For more details, see the [middleware docs](concepts/middleware.md)
2476
2506
  *
2477
2507
  * @param target Node to apply the middleware to.
2478
2508
  * @param middleware Middleware to apply.
@@ -2539,7 +2569,7 @@ var CollectedMiddlewares = /** @class */ (function () {
2539
2569
  get: function () {
2540
2570
  return this.middlewares.length <= 0;
2541
2571
  },
2542
- enumerable: true,
2572
+ enumerable: false,
2543
2573
  configurable: true
2544
2574
  });
2545
2575
  CollectedMiddlewares.prototype.getNextMiddleware = function () {
@@ -2970,10 +3000,7 @@ function getRelativePathBetweenNodes(base, target) {
2970
3000
  break;
2971
3001
  }
2972
3002
  // TODO: assert that no targetParts paths are "..", "." or ""!
2973
- return (baseParts
2974
- .slice(common)
2975
- .map(doubleDot)
2976
- .join("/") + joinJsonPath(targetParts.slice(common)));
3003
+ return (baseParts.slice(common).map(doubleDot).join("/") + joinJsonPath(targetParts.slice(common)));
2977
3004
  }
2978
3005
  /**
2979
3006
  * @internal
@@ -3028,8 +3055,7 @@ function resolveNodeByPathParts(base, pathParts, failIfResolveFails) {
3028
3055
  }
3029
3056
  }
3030
3057
  if (failIfResolveFails)
3031
- throw fail$1("Could not resolve '" + part + "' in path '" + (joinJsonPath(pathParts.slice(0, i)) ||
3032
- "/") + "' while resolving '" + joinJsonPath(pathParts) + "'");
3058
+ throw fail$1("Could not resolve '" + part + "' in path '" + (joinJsonPath(pathParts.slice(0, i)) || "/") + "' while resolving '" + joinJsonPath(pathParts) + "'");
3033
3059
  else
3034
3060
  return undefined;
3035
3061
  }
@@ -3259,7 +3285,7 @@ var EventHandler = /** @class */ (function () {
3259
3285
  get: function () {
3260
3286
  return this.handlers.length > 0;
3261
3287
  },
3262
- enumerable: true,
3288
+ enumerable: false,
3263
3289
  configurable: true
3264
3290
  });
3265
3291
  EventHandler.prototype.register = function (fn, atTheBeginning) {
@@ -3458,9 +3484,24 @@ function assertIsString(value, argNumber, canBeEmpty) {
3458
3484
  assertArg(value, function (s) { return s !== ""; }, "not empty string", argNumber);
3459
3485
  }
3460
3486
  }
3487
+ /**
3488
+ * @internal
3489
+ * @hidden
3490
+ */
3491
+ function setImmediateWithFallback(fn) {
3492
+ if (typeof queueMicrotask === "function") {
3493
+ queueMicrotask(fn);
3494
+ }
3495
+ else if (typeof setImmediate === "function") {
3496
+ setImmediate(fn);
3497
+ }
3498
+ else {
3499
+ setTimeout(fn, 1);
3500
+ }
3501
+ }
3461
3502
 
3462
3503
  /**
3463
- * See [asynchronous actions](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/async-actions.md).
3504
+ * See [asynchronous actions](concepts/async-actions.md).
3464
3505
  *
3465
3506
  * @returns The flow as a promise.
3466
3507
  */
@@ -3468,7 +3509,8 @@ function flow(generator) {
3468
3509
  return createFlowSpawner(generator.name, generator);
3469
3510
  }
3470
3511
  /**
3471
- * Used for TypeScript to make flows that return a promise return the actual promise result.
3512
+ * @deprecated Not needed since TS3.6.
3513
+ * Used for TypeScript to make flows that return a promise return the actual promise result.
3472
3514
  *
3473
3515
  * @param val
3474
3516
  * @returns
@@ -3476,6 +3518,72 @@ function flow(generator) {
3476
3518
  function castFlowReturn(val) {
3477
3519
  return val;
3478
3520
  }
3521
+ /**
3522
+ * @experimental
3523
+ * experimental api - might change on minor/patch releases
3524
+ *
3525
+ * Convert a promise-returning function to a generator-returning one.
3526
+ * This is intended to allow for usage of `yield*` in async actions to
3527
+ * retain the promise return type.
3528
+ *
3529
+ * Example:
3530
+ * ```ts
3531
+ * function getDataAsync(input: string): Promise<number> { ... }
3532
+ * const getDataGen = toGeneratorFunction(getDataAsync);
3533
+ *
3534
+ * const someModel.actions(self => ({
3535
+ * someAction: flow(function*() {
3536
+ * // value is typed as number
3537
+ * const value = yield* getDataGen("input value");
3538
+ * ...
3539
+ * })
3540
+ * }))
3541
+ * ```
3542
+ */
3543
+ function toGeneratorFunction(p) {
3544
+ return function () {
3545
+ var _i;
3546
+ var args = [];
3547
+ for (_i = 0; _i < arguments.length; _i++) {
3548
+ args[_i] = arguments[_i];
3549
+ }
3550
+ return __generator(this, function (_a) {
3551
+ switch (_a.label) {
3552
+ case 0: return [4 /*yield*/, p.apply(void 0, __spread(args))];
3553
+ case 1: return [2 /*return*/, (_a.sent())];
3554
+ }
3555
+ });
3556
+ };
3557
+ }
3558
+ /**
3559
+ * @experimental
3560
+ * experimental api - might change on minor/patch releases
3561
+ *
3562
+ * Convert a promise to a generator yielding that promise
3563
+ * This is intended to allow for usage of `yield*` in async actions to
3564
+ * retain the promise return type.
3565
+ *
3566
+ * Example:
3567
+ * ```ts
3568
+ * function getDataAsync(input: string): Promise<number> { ... }
3569
+ *
3570
+ * const someModel.actions(self => ({
3571
+ * someAction: flow(function*() {
3572
+ * // value is typed as number
3573
+ * const value = yield* toGenerator(getDataAsync("input value"));
3574
+ * ...
3575
+ * })
3576
+ * }))
3577
+ * ```
3578
+ */
3579
+ function toGenerator(p) {
3580
+ return __generator(this, function (_a) {
3581
+ switch (_a.label) {
3582
+ case 0: return [4 /*yield*/, p];
3583
+ case 1: return [2 /*return*/, (_a.sent())];
3584
+ }
3585
+ });
3586
+ }
3479
3587
  /**
3480
3588
  * @internal
3481
3589
  * @hidden
@@ -3506,7 +3614,7 @@ function createFlowSpawner(name, generator) {
3506
3614
  var args = arguments;
3507
3615
  function wrap(fn, type, arg) {
3508
3616
  fn.$mst_middleware = spawner.$mst_middleware; // pick up any middleware attached to the flow
3509
- runWithActionContext(__assign({}, contextBase, { type: type, args: [arg] }), fn);
3617
+ runWithActionContext(__assign(__assign({}, contextBase), { type: type, args: [arg] }), fn);
3510
3618
  }
3511
3619
  return new Promise(function (resolve, reject) {
3512
3620
  var gen;
@@ -3515,7 +3623,7 @@ function createFlowSpawner(name, generator) {
3515
3623
  onFulfilled(undefined); // kick off the flow
3516
3624
  };
3517
3625
  init.$mst_middleware = spawner.$mst_middleware;
3518
- runWithActionContext(__assign({}, contextBase, { type: "flow_spawn", args: argsToArray(args) }), init);
3626
+ runWithActionContext(__assign(__assign({}, contextBase), { type: "flow_spawn", args: argsToArray(args) }), init);
3519
3627
  function onFulfilled(res) {
3520
3628
  var ret;
3521
3629
  try {
@@ -3524,7 +3632,7 @@ function createFlowSpawner(name, generator) {
3524
3632
  }
3525
3633
  catch (e) {
3526
3634
  // prettier-ignore
3527
- setImmediate(function () {
3635
+ setImmediateWithFallback(function () {
3528
3636
  wrap(function (r) { reject(e); }, "flow_throw", e);
3529
3637
  });
3530
3638
  return;
@@ -3540,7 +3648,7 @@ function createFlowSpawner(name, generator) {
3540
3648
  }
3541
3649
  catch (e) {
3542
3650
  // prettier-ignore
3543
- setImmediate(function () {
3651
+ setImmediateWithFallback(function () {
3544
3652
  wrap(function (r) { reject(e); }, "flow_throw", e);
3545
3653
  });
3546
3654
  return;
@@ -3550,7 +3658,7 @@ function createFlowSpawner(name, generator) {
3550
3658
  function next(ret) {
3551
3659
  if (ret.done) {
3552
3660
  // prettier-ignore
3553
- setImmediate(function () {
3661
+ setImmediateWithFallback(function () {
3554
3662
  wrap(function (r) { resolve(r); }, "flow_return", ret.value);
3555
3663
  });
3556
3664
  return;
@@ -3700,7 +3808,7 @@ var SnapshotProcessor = /** @class */ (function (_super) {
3700
3808
  get: function () {
3701
3809
  return this._subtype.flags | TypeFlags.SnapshotProcessor;
3702
3810
  },
3703
- enumerable: true,
3811
+ enumerable: false,
3704
3812
  configurable: true
3705
3813
  });
3706
3814
  SnapshotProcessor.prototype.describe = function () {
@@ -3755,9 +3863,12 @@ var SnapshotProcessor = /** @class */ (function (_super) {
3755
3863
  return this._subtype;
3756
3864
  };
3757
3865
  SnapshotProcessor.prototype.is = function (thing) {
3758
- return (this._subtype.validate(isType(thing) ? this._subtype : this.preProcessSnapshot(thing), [
3759
- { path: "", type: this._subtype }
3760
- ]).length === 0);
3866
+ var value = isType(thing)
3867
+ ? this._subtype
3868
+ : isStateTreeNode(thing)
3869
+ ? getSnapshot(thing, false)
3870
+ : this.preProcessSnapshot(thing);
3871
+ return this._subtype.validate(value, [{ path: "", type: this._subtype }]).length === 0;
3761
3872
  };
3762
3873
  return SnapshotProcessor;
3763
3874
  }(BaseType));
@@ -3930,15 +4041,22 @@ var MSTMap = /** @class */ (function (_super) {
3930
4041
  */
3931
4042
  var MapType = /** @class */ (function (_super) {
3932
4043
  __extends(MapType, _super);
3933
- function MapType(name, _subType) {
4044
+ function MapType(name, _subType, hookInitializers) {
4045
+ if (hookInitializers === void 0) { hookInitializers = []; }
3934
4046
  var _this = _super.call(this, name) || this;
3935
4047
  _this._subType = _subType;
3936
4048
  _this.identifierMode = MapIdentifierMode.UNKNOWN;
3937
4049
  _this.mapIdentifierAttribute = undefined;
3938
4050
  _this.flags = TypeFlags.Map;
4051
+ _this.hookInitializers = [];
3939
4052
  _this._determineIdentifierMode();
4053
+ _this.hookInitializers = hookInitializers;
3940
4054
  return _this;
3941
4055
  }
4056
+ MapType.prototype.hooks = function (hooks) {
4057
+ var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks];
4058
+ return new MapType(this.name, this._subType, hookInitializers);
4059
+ };
3942
4060
  MapType.prototype.instantiate = function (parent, subpath, environment, initialValue) {
3943
4061
  this._determineIdentifierMode();
3944
4062
  return createObjectNode(this, parent, subpath, environment, initialValue);
@@ -3981,6 +4099,15 @@ var MapType = /** @class */ (function (_super) {
3981
4099
  };
3982
4100
  MapType.prototype.finalizeNewInstance = function (node, instance) {
3983
4101
  _interceptReads(instance, node.unbox);
4102
+ var type = node.type;
4103
+ type.hookInitializers.forEach(function (initializer) {
4104
+ var hooks = initializer(instance);
4105
+ Object.keys(hooks).forEach(function (name) {
4106
+ var hook = hooks[name];
4107
+ var actionInvoker = createActionInvoker(instance, name, hook);
4108
+ (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(instance, name, actionInvoker);
4109
+ });
4110
+ });
3984
4111
  intercept(instance, this.willChange);
3985
4112
  observe(instance, this.didChange);
3986
4113
  };
@@ -4175,12 +4302,19 @@ function isMapType(type) {
4175
4302
  */
4176
4303
  var ArrayType = /** @class */ (function (_super) {
4177
4304
  __extends(ArrayType, _super);
4178
- function ArrayType(name, _subType) {
4305
+ function ArrayType(name, _subType, hookInitializers) {
4306
+ if (hookInitializers === void 0) { hookInitializers = []; }
4179
4307
  var _this = _super.call(this, name) || this;
4180
4308
  _this._subType = _subType;
4181
4309
  _this.flags = TypeFlags.Array;
4310
+ _this.hookInitializers = [];
4311
+ _this.hookInitializers = hookInitializers;
4182
4312
  return _this;
4183
4313
  }
4314
+ ArrayType.prototype.hooks = function (hooks) {
4315
+ var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks];
4316
+ return new ArrayType(this.name, this._subType, hookInitializers);
4317
+ };
4184
4318
  ArrayType.prototype.instantiate = function (parent, subpath, environment, initialValue) {
4185
4319
  return createObjectNode(this, parent, subpath, environment, initialValue);
4186
4320
  };
@@ -4199,6 +4333,15 @@ var ArrayType = /** @class */ (function (_super) {
4199
4333
  };
4200
4334
  ArrayType.prototype.finalizeNewInstance = function (node, instance) {
4201
4335
  _getAdministration(instance).dehancer = node.unbox;
4336
+ var type = node.type;
4337
+ type.hookInitializers.forEach(function (initializer) {
4338
+ var hooks = initializer(instance);
4339
+ Object.keys(hooks).forEach(function (name) {
4340
+ var hook = hooks[name];
4341
+ var actionInvoker = createActionInvoker(instance, name, hook);
4342
+ (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(instance, name, actionInvoker);
4343
+ });
4344
+ });
4202
4345
  intercept(instance, this.willChange);
4203
4346
  observe(instance, this.didChange);
4204
4347
  };
@@ -4578,10 +4721,6 @@ var ModelType = /** @class */ (function (_super) {
4578
4721
  postProcessor: function (snapshot) { return postProcessor(currentPostprocessor(snapshot)); }
4579
4722
  });
4580
4723
  };
4581
- var name = opts.name || defaultObjectOptions.name;
4582
- // TODO: this test still needed?
4583
- if (!/^\w[\w\d_]*$/.test(name))
4584
- throw fail$1("Typename should be a valid identifier: " + name);
4585
4724
  Object.assign(_this, defaultObjectOptions, opts);
4586
4725
  // ensures that any default value gets converted to its related type
4587
4726
  _this.properties = toPropertiesObject(_this.properties);
@@ -4652,6 +4791,9 @@ var ModelType = /** @class */ (function (_super) {
4652
4791
  };
4653
4792
  ModelType.prototype.volatile = function (fn) {
4654
4793
  var _this = this;
4794
+ if (typeof fn !== "function") {
4795
+ throw fail$1("You passed an " + typeof fn + " to volatile state as an argument, when function is expected");
4796
+ }
4655
4797
  var stateInitializer = function (self) {
4656
4798
  _this.instantiateVolatileState(self, fn(self));
4657
4799
  return self;
@@ -4858,7 +5000,9 @@ var ModelType = /** @class */ (function (_super) {
4858
5000
  var _this = this;
4859
5001
  // optimization: cache
4860
5002
  return ("{ " +
4861
- this.propertyNames.map(function (key) { return key + ": " + _this.properties[key].describe(); }).join("; ") +
5003
+ this.propertyNames
5004
+ .map(function (key) { return key + ": " + _this.properties[key].describe(); })
5005
+ .join("; ") +
4862
5006
  " }");
4863
5007
  };
4864
5008
  ModelType.prototype.getDefaultSnapshot = function () {
@@ -4875,7 +5019,7 @@ var ModelType = /** @class */ (function (_super) {
4875
5019
  /**
4876
5020
  * `types.model` - Creates a new model type by providing a name, properties, volatile state and actions.
4877
5021
  *
4878
- * See the [model type](https://github.com/mobxjs/mobx-state-tree#creating-models) description or the [getting started](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/getting-started.md#getting-started-1) tutorial.
5022
+ * See the [model type](/concepts/trees#creating-models) description or the [getting started](intro/getting-started.md#getting-started-1) tutorial.
4879
5023
  */
4880
5024
  function model() {
4881
5025
  var args = [];
@@ -5156,7 +5300,7 @@ var Refinement = /** @class */ (function (_super) {
5156
5300
  get: function () {
5157
5301
  return this._subtype.flags | TypeFlags.Refinement;
5158
5302
  },
5159
- enumerable: true,
5303
+ enumerable: false,
5160
5304
  configurable: true
5161
5305
  });
5162
5306
  Refinement.prototype.describe = function () {
@@ -5276,7 +5420,7 @@ var Union = /** @class */ (function (_super) {
5276
5420
  });
5277
5421
  return result;
5278
5422
  },
5279
- enumerable: true,
5423
+ enumerable: false,
5280
5424
  configurable: true
5281
5425
  });
5282
5426
  Union.prototype.isAssignableFrom = function (type) {
@@ -5308,7 +5452,9 @@ var Union = /** @class */ (function (_super) {
5308
5452
  if (reconcileCurrentType.is(value)) {
5309
5453
  return reconcileCurrentType;
5310
5454
  }
5311
- return this._types.filter(function (t) { return t !== reconcileCurrentType; }).find(function (type) { return type.is(value); });
5455
+ return this._types
5456
+ .filter(function (t) { return t !== reconcileCurrentType; })
5457
+ .find(function (type) { return type.is(value); });
5312
5458
  }
5313
5459
  else {
5314
5460
  return this._types.find(function (type) { return type.is(value); });
@@ -5395,7 +5541,7 @@ var OptionalValue = /** @class */ (function (_super) {
5395
5541
  get: function () {
5396
5542
  return this._subtype.flags | TypeFlags.Optional;
5397
5543
  },
5398
- enumerable: true,
5544
+ enumerable: false,
5399
5545
  configurable: true
5400
5546
  });
5401
5547
  OptionalValue.prototype.describe = function () {
@@ -5550,7 +5696,7 @@ var Late = /** @class */ (function (_super) {
5550
5696
  get: function () {
5551
5697
  return (this._subType ? this._subType.flags : 0) | TypeFlags.Late;
5552
5698
  },
5553
- enumerable: true,
5699
+ enumerable: false,
5554
5700
  configurable: true
5555
5701
  });
5556
5702
  Late.prototype.getSubType = function (mustSucceed) {
@@ -5782,7 +5928,7 @@ var StoredReference = /** @class */ (function () {
5782
5928
  this.updateResolvedReference(this.node);
5783
5929
  return this.resolvedReference.node.value;
5784
5930
  },
5785
- enumerable: true,
5931
+ enumerable: false,
5786
5932
  configurable: true
5787
5933
  });
5788
5934
  return StoredReference;
@@ -6096,7 +6242,7 @@ function isReferenceType(type) {
6096
6242
  * @returns
6097
6243
  */
6098
6244
  function safeReference(subType, options) {
6099
- var refType = reference(subType, __assign({}, options, { onInvalidated: function (ev) {
6245
+ var refType = reference(subType, __assign(__assign({}, options), { onInvalidated: function (ev) {
6100
6246
  ev.removeRef();
6101
6247
  } }));
6102
6248
  if (options && options.acceptsUndefined === false) {
@@ -6239,8 +6385,8 @@ function assertIsValidIdentifier(id, argNumber) {
6239
6385
  * export interface CustomTypeOptions<S, T> {
6240
6386
  * // Friendly name
6241
6387
  * name: string
6242
- * // given a serialized value, how to turn it into the target type
6243
- * fromSnapshot(snapshot: S): T
6388
+ * // given a serialized value and environment, how to turn it into the target type
6389
+ * fromSnapshot(snapshot: S, env: any): T
6244
6390
  * // return the serialization of the current value
6245
6391
  * toSnapshot(value: T): S
6246
6392
  * // if true, this is a converted value, if false, it's a snapshot
@@ -6310,7 +6456,7 @@ var CustomType = /** @class */ (function (_super) {
6310
6456
  CustomType.prototype.instantiate = function (parent, subpath, environment, initialValue) {
6311
6457
  var valueToStore = this.options.isTargetType(initialValue)
6312
6458
  ? initialValue
6313
- : this.options.fromSnapshot(initialValue);
6459
+ : this.options.fromSnapshot(initialValue, parent && parent.root.environment);
6314
6460
  return createScalarNode(this, parent, subpath, environment, valueToStore);
6315
6461
  };
6316
6462
  CustomType.prototype.reconcile = function (current, value, parent, subpath) {
@@ -6324,7 +6470,9 @@ var CustomType = /** @class */ (function (_super) {
6324
6470
  return current;
6325
6471
  }
6326
6472
  }
6327
- var valueToStore = isSnapshot ? this.options.fromSnapshot(value) : value;
6473
+ var valueToStore = isSnapshot
6474
+ ? this.options.fromSnapshot(value, parent.root.environment)
6475
+ : value;
6328
6476
  var newNode = this.instantiate(parent, subpath, undefined, valueToStore);
6329
6477
  current.die(); // noop if detaching
6330
6478
  return newNode;
@@ -6362,11 +6510,4 @@ var types = {
6362
6510
  snapshotProcessor: snapshotProcessor
6363
6511
  };
6364
6512
 
6365
- /*
6366
- * All imports / exports should be proxied through this file.
6367
- * Why? It gives us full control over the module load order, preventing circular dependency isses
6368
- */
6369
-
6370
- /* all code is initially loaded through internal, to avoid circular dep issues */
6371
-
6372
- export { addDisposer, addMiddleware, applyAction, applyPatch, applySnapshot, cast, castFlowReturn, castToReferenceSnapshot, castToSnapshot, clone, createActionTrackingMiddleware, createActionTrackingMiddleware2, decorate, destroy, detach, escapeJsonPath, flow, getChildType, getEnv, getIdentifier, getLivelinessChecking, getMembers, getNodeId, getParent, getParentOfType, getPath, getPathParts, getPropertyMembers, getRelativePath, getRoot, getRunningActionContext, getSnapshot, getType, hasParent, hasParentOfType, isActionContextChildOf, isActionContextThisOrChildOf, isAlive, isArrayType, isFrozenType, isIdentifierType, isLateType, isLiteralType, isMapType, isModelType, isOptionalType, isPrimitiveType, isProtected, isReferenceType, isRefinementType, isRoot, isStateTreeNode, isType, isUnionType, isValidReference, joinJsonPath, onAction, onPatch, onSnapshot, process$1 as process, protect, recordActions, recordPatches, resolveIdentifier, resolvePath, setLivelinessChecking, setLivelynessChecking, splitJsonPath, tryReference, tryResolve, typecheck, types, unescapeJsonPath, unprotect, walk };
6513
+ export { addDisposer, addMiddleware, applyAction, applyPatch, applySnapshot, cast, castFlowReturn, castToReferenceSnapshot, castToSnapshot, clone, createActionTrackingMiddleware, createActionTrackingMiddleware2, decorate, destroy, detach, escapeJsonPath, flow, getChildType, getEnv, getIdentifier, getLivelinessChecking, getMembers, getNodeId, getParent, getParentOfType, getPath, getPathParts, getPropertyMembers, getRelativePath, getRoot, getRunningActionContext, getSnapshot, getType, hasParent, hasParentOfType, isActionContextChildOf, isActionContextThisOrChildOf, isAlive, isArrayType, isFrozenType, isIdentifierType, isLateType, isLiteralType, isMapType, isModelType, isOptionalType, isPrimitiveType, isProtected, isReferenceType, isRefinementType, isRoot, isStateTreeNode, isType, isUnionType, isValidReference, joinJsonPath, onAction, onPatch, onSnapshot, process$1 as process, protect, recordActions, recordPatches, resolveIdentifier, resolvePath, setLivelinessChecking, setLivelynessChecking, splitJsonPath, toGenerator, toGeneratorFunction, tryReference, tryResolve, typecheck, types, unescapeJsonPath, unprotect, walk };