mobx-state-tree 7.0.2 → 7.2.0

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.
@@ -340,7 +340,7 @@ export declare function isAlive(target: IAnyStateTreeNode): boolean;
340
340
  export declare function addDisposer(target: IAnyStateTreeNode, disposer: IDisposer): IDisposer;
341
341
  /**
342
342
  * Returns the environment of the current state tree, or throws. For more info on environments,
343
- * see [Dependency injection](https://github.com/mobxjs/mobx-state-tree#dependency-injection)
343
+ * see [Dependency injection](/concepts/dependency-injection)
344
344
  *
345
345
  * Please note that in child nodes access to the root is only possible
346
346
  * once the `afterAttach` hook has fired
@@ -1,4 +1,4 @@
1
- import { IValidationContext, IValidationResult, IStateTreeNode, ModelPrimitive } from "../../internal";
1
+ import { IValidationContext, IValidationResult, IStateTreeNode, ObjectNode, ModelPrimitive, AnyNode } from "../../internal";
2
2
  import type { WritableKeys } from "ts-essentials";
3
3
  /**
4
4
  * A state tree node value.
@@ -154,6 +154,8 @@ export type SnapshotOut<T> = T extends {
154
154
  * ```
155
155
  */
156
156
  export type SnapshotOrInstance<T> = SnapshotIn<T> | Instance<T>;
157
+ export declare function canApplyDirectSnapshot(childType: IAnyType, childNode: AnyNode, newValue: any): childNode is ObjectNode<any, any, any>;
158
+ export declare function resolveDirectApplyType(type: IAnyType): IAnyType;
157
159
  /**
158
160
  * Returns if a given value represents a type.
159
161
  *
@@ -795,7 +795,7 @@ function addDisposer(target, disposer) {
795
795
  }
796
796
  /**
797
797
  * Returns the environment of the current state tree, or throws. For more info on environments,
798
- * see [Dependency injection](https://github.com/mobxjs/mobx-state-tree#dependency-injection)
798
+ * see [Dependency injection](/concepts/dependency-injection)
799
799
  *
800
800
  * Please note that in child nodes access to the root is only possible
801
801
  * once the `afterAttach` hook has fired
@@ -1542,6 +1542,12 @@ var ObjectNode = /** @class */ (function (_super) {
1542
1542
  writable: true,
1543
1543
  value: false
1544
1544
  });
1545
+ Object.defineProperty(_this, "_endOfActionCallbacks", {
1546
+ enumerable: true,
1547
+ configurable: true,
1548
+ writable: true,
1549
+ value: void 0
1550
+ });
1545
1551
  Object.defineProperty(_this, "_observableInstanceState", {
1546
1552
  enumerable: true,
1547
1553
  configurable: true,
@@ -1612,8 +1618,8 @@ var ObjectNode = /** @class */ (function (_super) {
1612
1618
  id = childNode.value;
1613
1619
  }
1614
1620
  }
1615
- if (typeof id !== "string" && typeof id !== "number") {
1616
- throw new MstError("Instance identifier '".concat(_this.identifierAttribute, "' for type '").concat(_this.type.name, "' must be a string or a number"));
1621
+ if (typeof id !== "string" && typeof id !== "number" && typeof id !== "bigint") {
1622
+ throw new MstError("Instance identifier '".concat(_this.identifierAttribute, "' for type '").concat(_this.type.name, "' must be a string, a number or a bigint"));
1617
1623
  }
1618
1624
  // normalize internal identifier to string
1619
1625
  _this.identifier = normalizeIdentifier(id);
@@ -1751,6 +1757,33 @@ var ObjectNode = /** @class */ (function (_super) {
1751
1757
  enumerable: false,
1752
1758
  configurable: true
1753
1759
  });
1760
+ Object.defineProperty(ObjectNode.prototype, "enqueueEndOfAction", {
1761
+ enumerable: false,
1762
+ configurable: true,
1763
+ writable: true,
1764
+ value: function (callback) {
1765
+ var root = this.root;
1766
+ if (!root._endOfActionCallbacks) {
1767
+ root._endOfActionCallbacks = [];
1768
+ }
1769
+ root._endOfActionCallbacks.push(callback);
1770
+ }
1771
+ });
1772
+ Object.defineProperty(ObjectNode.prototype, "flushEndOfActionCallbacks", {
1773
+ enumerable: false,
1774
+ configurable: true,
1775
+ writable: true,
1776
+ value: function () {
1777
+ var root = this.root;
1778
+ while (root._endOfActionCallbacks && root._endOfActionCallbacks.length > 0) {
1779
+ var callbacks = root._endOfActionCallbacks;
1780
+ root._endOfActionCallbacks = undefined;
1781
+ callbacks.forEach(function (callback) {
1782
+ callback();
1783
+ });
1784
+ }
1785
+ }
1786
+ });
1754
1787
  Object.defineProperty(ObjectNode.prototype, "clearParent", {
1755
1788
  enumerable: false,
1756
1789
  configurable: true,
@@ -2169,6 +2202,17 @@ var ObjectNode = /** @class */ (function (_super) {
2169
2202
  return this._internalEventsRegister(InternalEvents.Patch, handler);
2170
2203
  }
2171
2204
  });
2205
+ Object.defineProperty(ObjectNode.prototype, "hasPatchSubscribers", {
2206
+ enumerable: false,
2207
+ configurable: true,
2208
+ writable: true,
2209
+ value: function () {
2210
+ if (this._internalEventsHasSubscribers(InternalEvents.Patch)) {
2211
+ return true;
2212
+ }
2213
+ return this.parent ? this.parent.hasPatchSubscribers() : false;
2214
+ }
2215
+ });
2172
2216
  Object.defineProperty(ObjectNode.prototype, "emitPatch", {
2173
2217
  enumerable: false,
2174
2218
  configurable: true,
@@ -2381,6 +2425,7 @@ var TypeFlags;
2381
2425
  TypeFlags[TypeFlags["Lazy"] = 1048576] = "Lazy";
2382
2426
  TypeFlags[TypeFlags["Finite"] = 2097152] = "Finite";
2383
2427
  TypeFlags[TypeFlags["Float"] = 4194304] = "Float";
2428
+ TypeFlags[TypeFlags["BigInt"] = 8388608] = "BigInt";
2384
2429
  })(TypeFlags || (TypeFlags = {}));
2385
2430
  /**
2386
2431
  * @internal
@@ -2697,6 +2742,38 @@ var SimpleType = /** @class */ (function (_super) {
2697
2742
  });
2698
2743
  return SimpleType;
2699
2744
  }(BaseType));
2745
+ function canApplyDirectSnapshot(childType, childNode, newValue) {
2746
+ var reconciliationType = childNode.getReconciliationType();
2747
+ var expectedReconciliationType = resolveDirectApplyType(childType);
2748
+ // Only types that reconcile as the same transparent-wrapper-adjusted type can safely reuse
2749
+ // the existing child node. Wrappers with their own validation or snapshot semantics
2750
+ // intentionally keep a distinct reconciliation type so they fall back to the validated path.
2751
+ var hasMatchingReconciliationType = reconciliationType === expectedReconciliationType;
2752
+ return (childNode instanceof ObjectNode &&
2753
+ hasMatchingReconciliationType &&
2754
+ reconciliationType instanceof ComplexType &&
2755
+ isMutable(newValue) &&
2756
+ !isStateTreeNode(newValue) &&
2757
+ reconciliationType.isMatchingSnapshotId(childNode, newValue));
2758
+ }
2759
+ function resolveDirectApplyType(type) {
2760
+ var subTypes = type.getSubTypes();
2761
+ if (!subTypes ||
2762
+ Array.isArray(subTypes) ||
2763
+ subTypes === cannotDetermineSubtype ||
2764
+ !canUnwrapDirectApplyType(type)) {
2765
+ return type;
2766
+ }
2767
+ // Only unwrap wrappers that are transparent for direct apply. Wrappers with their own
2768
+ // validation or snapshot processing must keep their wrapper identity here.
2769
+ return resolveDirectApplyType(subTypes);
2770
+ }
2771
+ function canUnwrapDirectApplyType(type) {
2772
+ var transparentWrapperFlags = TypeFlags.Optional | TypeFlags.Late;
2773
+ var nonTransparentWrapperFlags = TypeFlags.Refinement | TypeFlags.SnapshotProcessor | TypeFlags.Union;
2774
+ return ((type.flags & transparentWrapperFlags) > 0 &&
2775
+ (type.flags & nonTransparentWrapperFlags) === 0);
2776
+ }
2700
2777
  /**
2701
2778
  * Returns if a given value represents a type.
2702
2779
  *
@@ -3188,9 +3265,10 @@ function runWithActionContext(context, fn) {
3188
3265
  var baseIsRunningAction = node._isRunningAction;
3189
3266
  node._isRunningAction = true;
3190
3267
  var previousContext = currentActionContext;
3268
+ var isRootActionContext = !previousContext;
3191
3269
  currentActionContext = context;
3192
3270
  try {
3193
- return runMiddleWares(node, context, fn);
3271
+ return runMiddleWares(node, context, fn, isRootActionContext);
3194
3272
  }
3195
3273
  finally {
3196
3274
  currentActionContext = previousContext;
@@ -3344,17 +3422,44 @@ var CollectedMiddlewares = /** @class */ (function () {
3344
3422
  });
3345
3423
  return CollectedMiddlewares;
3346
3424
  }());
3347
- function runMiddleWares(node, baseCall, originalFn) {
3425
+ function runMiddleWares(node, baseCall, originalFn, isRootActionContext) {
3426
+ function runInActionScope(call, fn) {
3427
+ var execute = function () {
3428
+ var result;
3429
+ var error;
3430
+ try {
3431
+ result = fn.apply(null, call.args);
3432
+ }
3433
+ catch (e) {
3434
+ error = e;
3435
+ }
3436
+ if (isRootActionContext || !call.parentActionEvent) {
3437
+ try {
3438
+ node.root.flushEndOfActionCallbacks();
3439
+ }
3440
+ catch (flushError) {
3441
+ if (!error) {
3442
+ error = flushError;
3443
+ }
3444
+ }
3445
+ }
3446
+ if (error) {
3447
+ throw error;
3448
+ }
3449
+ return result;
3450
+ };
3451
+ return call.name ? mobx.action(call.name, execute)() : mobx.action(execute)();
3452
+ }
3348
3453
  var middlewares = new CollectedMiddlewares(node, originalFn);
3349
3454
  // Short circuit
3350
3455
  if (middlewares.isEmpty)
3351
- return mobx.action(originalFn).apply(null, baseCall.args);
3456
+ return runInActionScope(baseCall, originalFn);
3352
3457
  var result = null;
3353
3458
  function runNextMiddleware(call) {
3354
3459
  var middleware = middlewares.getNextMiddleware();
3355
3460
  var handler = middleware && middleware.handler;
3356
3461
  if (!handler) {
3357
- return mobx.action(originalFn).apply(null, call.args);
3462
+ return runInActionScope(call, originalFn);
3358
3463
  }
3359
3464
  // skip hooks if asked to
3360
3465
  if (!middleware.includeHooks && Hook[call.name]) {
@@ -3390,6 +3495,9 @@ function runMiddleWares(node, baseCall, originalFn) {
3390
3495
  throw new MstError("The next() and abort() callback within the middleware ".concat(handler.name, " for the action: \"").concat(call.name, "\" on the node: ").concat(node2.type.name, " were invoked."));
3391
3496
  }
3392
3497
  }
3498
+ if (abortInvoked && (isRootActionContext || !call.parentActionEvent)) {
3499
+ return runInActionScope(call, function () { return result; });
3500
+ }
3393
3501
  return result;
3394
3502
  }
3395
3503
  return runNextMiddleware(baseCall);
@@ -4046,6 +4154,7 @@ function isPrimitive(value, includeDate) {
4046
4154
  typeof value === "string" ||
4047
4155
  typeof value === "number" ||
4048
4156
  typeof value === "boolean" ||
4157
+ typeof value === "bigint" ||
4049
4158
  (includeDate && value instanceof Date));
4050
4159
  }
4051
4160
  /**
@@ -4930,6 +5039,8 @@ function proxyNodeTypeMethods(nodeType, snapshotProcessorType) {
4930
5039
  /**
4931
5040
  * `types.snapshotProcessor` - Runs a pre/post snapshot processor before/after serializing a given type.
4932
5041
  *
5042
+ * [See known issue with `applySnapshot` and `preProcessSnapshot`](https://github.com/mobxjs/mobx-state-tree/issues/1317)
5043
+ *
4933
5044
  * Example:
4934
5045
  * ```ts
4935
5046
  * const Todo1 = types.model({ text: types.string })
@@ -5380,23 +5491,33 @@ var MapType = /** @class */ (function (_super) {
5380
5491
  configurable: true,
5381
5492
  writable: true,
5382
5493
  value: function (node, snapshot) {
5383
- typecheckInternal(this, snapshot);
5494
+ if (!isPlainObject(snapshot)) {
5495
+ typecheckInternal(this, snapshot);
5496
+ return;
5497
+ }
5384
5498
  var target = node.storedValue;
5385
- var currentKeys = {};
5499
+ var childType = this.getChildType();
5386
5500
  Array.from(target.keys()).forEach(function (key) {
5387
- currentKeys[key] = false;
5388
- });
5389
- if (snapshot) {
5390
- // Don't use target.replace, as it will throw away all existing items first
5391
- for (var key in snapshot) {
5392
- target.set(key, snapshot[key]);
5393
- currentKeys["" + key] = true;
5394
- }
5395
- }
5396
- Object.keys(currentKeys).forEach(function (key) {
5397
- if (currentKeys[key] === false)
5501
+ if (!Object.prototype.hasOwnProperty.call(snapshot, key)) {
5398
5502
  target.delete(key);
5503
+ return;
5504
+ }
5505
+ var childNode = node.getChildNode(key);
5506
+ var newValue = snapshot[key];
5507
+ if (childNode.snapshot === newValue)
5508
+ return;
5509
+ if (canApplyDirectSnapshot(childType, childNode, newValue)) {
5510
+ childNode.applySnapshot(newValue);
5511
+ }
5512
+ else {
5513
+ target.set(key, newValue);
5514
+ }
5399
5515
  });
5516
+ for (var key in snapshot) {
5517
+ if (!Object.prototype.hasOwnProperty.call(snapshot, key) || target.has(key))
5518
+ continue;
5519
+ target.set(key, snapshot[key]);
5520
+ }
5400
5521
  }
5401
5522
  });
5402
5523
  Object.defineProperty(MapType.prototype, "getChildType", {
@@ -5722,9 +5843,52 @@ var ArrayType = /** @class */ (function (_super) {
5722
5843
  configurable: true,
5723
5844
  writable: true,
5724
5845
  value: function (node, snapshot) {
5725
- typecheckInternal(this, snapshot);
5846
+ if (!isArray(snapshot)) {
5847
+ typecheckInternal(this, snapshot);
5848
+ return;
5849
+ }
5726
5850
  var target = node.storedValue;
5727
- target.replace(snapshot);
5851
+ var childNodes = node.getChildren();
5852
+ var oldLength = childNodes.length;
5853
+ var newLength = snapshot.length;
5854
+ var childType = this.getChildType();
5855
+ var minLength = Math.min(oldLength, newLength);
5856
+ var firstChangedIndex = findFirstChangedIndex(childNodes, snapshot, minLength);
5857
+ // If all array items are the same and the length did not change, there is nothing to do.
5858
+ if (firstChangedIndex === oldLength && firstChangedIndex === newLength) {
5859
+ return;
5860
+ }
5861
+ // Preserve the old "always replace" behavior for length changes and when patches are being
5862
+ // observed, since those cases are more sensitive to patch shape (for example, splice
5863
+ // would otherwise emit add/remove patch sequences) and benchmark variance.
5864
+ if (oldLength !== newLength || node.hasPatchSubscribers()) {
5865
+ target.replace(snapshot);
5866
+ return;
5867
+ }
5868
+ // When every changed entry can reuse its existing child node, update them in place
5869
+ // instead of going through array replacement/splice.
5870
+ if (canApplyDirectSnapshotsInRange(childType, childNodes, snapshot, firstChangedIndex)) {
5871
+ applyDirectSnapshotsInRange(childNodes, snapshot, firstChangedIndex);
5872
+ return;
5873
+ }
5874
+ var oldEnd = oldLength - 1;
5875
+ var newEnd = newLength - 1;
5876
+ while (oldEnd >= firstChangedIndex &&
5877
+ newEnd >= firstChangedIndex &&
5878
+ childNodes[oldEnd].snapshot === snapshot[newEnd]) {
5879
+ oldEnd--;
5880
+ newEnd--;
5881
+ }
5882
+ // Trim the unchanged suffix too, so we only replace the minimal changed window.
5883
+ var replacedCount = oldEnd >= firstChangedIndex ? oldEnd - firstChangedIndex + 1 : 0;
5884
+ var replacementSnapshots = newEnd >= firstChangedIndex
5885
+ ? snapshot.slice(firstChangedIndex, newEnd + 1)
5886
+ : EMPTY_ARRAY;
5887
+ if (replacedCount === 1 && replacementSnapshots.length === 1) {
5888
+ target[firstChangedIndex] = replacementSnapshots[0];
5889
+ return;
5890
+ }
5891
+ target.splice.apply(target, __spreadArray([firstChangedIndex, replacedCount], __read(replacementSnapshots), false));
5728
5892
  }
5729
5893
  });
5730
5894
  Object.defineProperty(ArrayType.prototype, "getChildType", {
@@ -5796,6 +5960,31 @@ function array(subtype) {
5796
5960
  assertIsType(subtype, 1);
5797
5961
  return new ArrayType("".concat(subtype.name, "[]"), subtype);
5798
5962
  }
5963
+ function findFirstChangedIndex(childNodes, snapshot, length) {
5964
+ var index = 0;
5965
+ while (index < length && childNodes[index].snapshot === snapshot[index]) {
5966
+ index++;
5967
+ }
5968
+ return index;
5969
+ }
5970
+ function canApplyDirectSnapshotsInRange(childType, childNodes, snapshot, startIndex) {
5971
+ for (var i = startIndex; i < childNodes.length; i++) {
5972
+ if (childNodes[i].snapshot === snapshot[i])
5973
+ continue;
5974
+ if (!canApplyDirectSnapshot(childType, childNodes[i], snapshot[i])) {
5975
+ return false;
5976
+ }
5977
+ }
5978
+ return true;
5979
+ }
5980
+ function applyDirectSnapshotsInRange(childNodes, snapshot, startIndex) {
5981
+ for (var i = startIndex; i < childNodes.length; i++) {
5982
+ var childNode = childNodes[i];
5983
+ if (childNode.snapshot === snapshot[i])
5984
+ continue;
5985
+ childNode.applySnapshot(snapshot[i]);
5986
+ }
5987
+ }
5799
5988
  function reconcileArrayChildren(parent, childType, oldNodes, newValues, newPaths) {
5800
5989
  var nothingChanged = true;
5801
5990
  for (var i = 0;; i++) {
@@ -6441,10 +6630,25 @@ var ModelType = /** @class */ (function (_super) {
6441
6630
  configurable: true,
6442
6631
  writable: true,
6443
6632
  value: function (node, snapshot) {
6444
- typecheckInternal(this, snapshot);
6445
6633
  var preProcessedSnapshot = this.applySnapshotPreProcessor(snapshot);
6446
- this.forAllProps(function (name) {
6447
- node.storedValue[name] = preProcessedSnapshot[name];
6634
+ var isPreProcessedSnapshotNonPlain = !isPlainObject(preProcessedSnapshot);
6635
+ // Fast-path plain-object snapshots, but still validate when preprocessing is required
6636
+ // or when preprocessing produces an invalid model snapshot.
6637
+ if (!isPlainObject(snapshot) || isPreProcessedSnapshotNonPlain) {
6638
+ typecheckInternal(this, snapshot);
6639
+ if (isPreProcessedSnapshotNonPlain)
6640
+ return;
6641
+ }
6642
+ this.forAllProps(function (name, childType) {
6643
+ var childNode = node.getChildNode(name);
6644
+ var newValue = preProcessedSnapshot[name];
6645
+ if (childNode.snapshot === newValue)
6646
+ return;
6647
+ if (canApplyDirectSnapshot(childType, childNode, newValue)) {
6648
+ childNode.applySnapshot(newValue);
6649
+ return;
6650
+ }
6651
+ node.storedValue[name] = newValue;
6448
6652
  });
6449
6653
  }
6450
6654
  });
@@ -6735,6 +6939,37 @@ var float = new CoreType("float", TypeFlags.Float, function (v) { return isFloat
6735
6939
  */
6736
6940
  // tslint:disable-next-line:variable-name
6737
6941
  var finite = new CoreType("finite", TypeFlags.Finite, function (v) { return isFinite(v); });
6942
+ var _BigIntPrimitive = new CoreType("bigint", TypeFlags.BigInt, function (v) {
6943
+ if (typeof v === "bigint") {
6944
+ return true;
6945
+ }
6946
+ if (typeof v === "string" || typeof v === "number") {
6947
+ try {
6948
+ // BigInt primitive constructor verifies whether the value is a valid integer
6949
+ BigInt(v);
6950
+ return true;
6951
+ }
6952
+ catch (_a) { }
6953
+ }
6954
+ return false;
6955
+ }, function (v) { return (typeof v === "bigint" ? v : BigInt(v)); });
6956
+ _BigIntPrimitive.getSnapshot = function (node) {
6957
+ return String(node.storedValue);
6958
+ };
6959
+ /**
6960
+ * `types.bigint` - Creates a type that can only contain a bigint value.
6961
+ * Snapshots serialize to string (JSON-safe) and deserialize from string, number or bigint.
6962
+ *
6963
+ * Example:
6964
+ * ```ts
6965
+ * const BigId = types.model({
6966
+ * id: types.identifier,
6967
+ * value: types.bigint
6968
+ * })
6969
+ * getSnapshot(store).value // "0" (string, JSON-safe)
6970
+ * ```
6971
+ */
6972
+ var bigint = _BigIntPrimitive;
6738
6973
  /**
6739
6974
  * `types.boolean` - Creates a type that can only contain a boolean value.
6740
6975
  * This type is used for boolean values by default
@@ -6786,6 +7021,8 @@ function getPrimitiveFactoryFromValue(value) {
6786
7021
  return number; // In the future, isInteger(value) ? integer : number would be interesting, but would be too breaking for now
6787
7022
  case "boolean":
6788
7023
  return boolean;
7024
+ case "bigint":
7025
+ return bigint;
6789
7026
  case "object":
6790
7027
  if (value instanceof Date)
6791
7028
  return DatePrimitive;
@@ -6805,7 +7042,8 @@ function isPrimitiveType(type) {
6805
7042
  TypeFlags.Number |
6806
7043
  TypeFlags.Integer |
6807
7044
  TypeFlags.Boolean |
6808
- TypeFlags.Date)) >
7045
+ TypeFlags.Date |
7046
+ TypeFlags.BigInt)) >
6809
7047
  0);
6810
7048
  }
6811
7049
 
@@ -7959,7 +8197,7 @@ var BaseReferenceType = /** @class */ (function (_super) {
7959
8197
  value: function (value, context) {
7960
8198
  return isValidIdentifier(value)
7961
8199
  ? typeCheckSuccess()
7962
- : typeCheckFailure(context, value, "Value is not a valid identifier, which is a string or a number");
8200
+ : typeCheckFailure(context, value, "Value is not a valid identifier, which is a string, number or a bigint");
7963
8201
  }
7964
8202
  });
7965
8203
  Object.defineProperty(BaseReferenceType.prototype, "fireInvalidated", {
@@ -8048,6 +8286,23 @@ var BaseReferenceType = /** @class */ (function (_super) {
8048
8286
  onRefTargetDestroyedHookDisposer();
8049
8287
  }
8050
8288
  });
8289
+ var scheduleRetryAfterReconciliation = function () {
8290
+ var retry = function () {
8291
+ if (!storedRefNode.isAlive) {
8292
+ return;
8293
+ }
8294
+ if (_this.getSnapshot(storedRefNode) !== identifier) {
8295
+ return;
8296
+ }
8297
+ startWatching(false);
8298
+ };
8299
+ if (getCurrentActionContext()) {
8300
+ storedRefNode.root.enqueueEndOfAction(retry);
8301
+ }
8302
+ else {
8303
+ setImmediateWithFallback(retry);
8304
+ }
8305
+ };
8051
8306
  var startWatching = function (sync) {
8052
8307
  // re-create hook in case the stored ref gets reattached
8053
8308
  if (onRefTargetDestroyedHookDisposer) {
@@ -8065,12 +8320,13 @@ var BaseReferenceType = /** @class */ (function (_super) {
8065
8320
  refTargetNodeExists = storedRefNode.root.identifierCache.has(_this.targetType, normalizeIdentifier(identifier));
8066
8321
  }
8067
8322
  if (!refTargetNodeExists) {
8068
- // we cannot change the reference in sync mode
8069
- // since we are in the middle of a reconciliation/instantiation and the change would be overwritten
8070
- // for those cases just let the wrong reference be assigned and fail upon usage
8071
- // (like current references do)
8072
- // this means that effectively this code will only run when it is created from a snapshot
8073
- if (!sync) {
8323
+ // if the tree is already attached we may still be in the middle of a reconcile/applySnapshot,
8324
+ // so wait until the current MST action finishes before deciding whether to invalidate or
8325
+ // attach a watcher to a target that appeared later in the same action.
8326
+ if (sync) {
8327
+ scheduleRetryAfterReconciliation();
8328
+ }
8329
+ else {
8074
8330
  _this.fireInvalidated("invalidSnapshotReference", storedRefNode, identifier, null);
8075
8331
  }
8076
8332
  }
@@ -8420,7 +8676,7 @@ var IdentifierNumberType = /** @class */ (function (_super) {
8420
8676
  * Inside a state tree, for each type can exist only one instance for each given identifier.
8421
8677
  * For example there couldn't be 2 instances of user with id 1. If you need more, consider using references.
8422
8678
  * Identifier can be used only as type property of a model.
8423
- * This type accepts as parameter the value type of the identifier field that can be either string or number.
8679
+ * This type accepts as parameter the value type of the identifier field that can be either string, number or bigint.
8424
8680
  *
8425
8681
  * Example:
8426
8682
  * ```ts
@@ -8447,6 +8703,110 @@ var identifier = new IdentifierType();
8447
8703
  * @returns
8448
8704
  */
8449
8705
  var identifierNumber = new IdentifierNumberType();
8706
+ /**
8707
+ * @internal
8708
+ * @hidden
8709
+ * IdentifierBigintType uses SimpleType<bigint | string | number, string, bigint> so snapshots serialize to string (JSON-safe).
8710
+ */
8711
+ var IdentifierBigintType = /** @class */ (function (_super) {
8712
+ __extends(IdentifierBigintType, _super);
8713
+ function IdentifierBigintType() {
8714
+ var _this = _super.call(this, "identifierBigint") || this;
8715
+ Object.defineProperty(_this, "flags", {
8716
+ enumerable: true,
8717
+ configurable: true,
8718
+ writable: true,
8719
+ value: TypeFlags.Identifier
8720
+ });
8721
+ return _this;
8722
+ }
8723
+ Object.defineProperty(IdentifierBigintType.prototype, "createNewInstance", {
8724
+ enumerable: false,
8725
+ configurable: true,
8726
+ writable: true,
8727
+ value: function (snapshot) {
8728
+ if (typeof snapshot === "bigint")
8729
+ return snapshot;
8730
+ return BigInt(snapshot);
8731
+ }
8732
+ });
8733
+ Object.defineProperty(IdentifierBigintType.prototype, "instantiate", {
8734
+ enumerable: false,
8735
+ configurable: true,
8736
+ writable: true,
8737
+ value: function (parent, subpath, environment, initialValue) {
8738
+ if (!parent || !(parent.type instanceof ModelType))
8739
+ throw new MstError("Identifier types can only be instantiated as direct child of a model type");
8740
+ return createScalarNode(this, parent, subpath, environment, initialValue);
8741
+ }
8742
+ });
8743
+ Object.defineProperty(IdentifierBigintType.prototype, "reconcile", {
8744
+ enumerable: false,
8745
+ configurable: true,
8746
+ writable: true,
8747
+ value: function (current, newValue, parent, subpath) {
8748
+ var currentVal = current.storedValue;
8749
+ var newVal = typeof newValue === "bigint" ? newValue : BigInt(newValue);
8750
+ if (currentVal !== newVal)
8751
+ throw new MstError("Tried to change identifier from '".concat(currentVal, "' to '").concat(newVal, "'. Changing identifiers is not allowed."));
8752
+ current.setParent(parent, subpath);
8753
+ return current;
8754
+ }
8755
+ });
8756
+ Object.defineProperty(IdentifierBigintType.prototype, "isValidSnapshot", {
8757
+ enumerable: false,
8758
+ configurable: true,
8759
+ writable: true,
8760
+ value: function (value, context) {
8761
+ if (typeof value === "bigint") {
8762
+ return typeCheckSuccess();
8763
+ }
8764
+ if (typeof value === "string" || typeof value === "number") {
8765
+ try {
8766
+ // BigInt primitive constructor verifies whether the value is a valid integer
8767
+ BigInt(value);
8768
+ return typeCheckSuccess();
8769
+ }
8770
+ catch (e) {
8771
+ var errorMessage = e instanceof Error ? e.message : String(e);
8772
+ return typeCheckFailure(context, value, "Value is not a valid ".concat(this.describe(), ": ").concat(errorMessage));
8773
+ }
8774
+ }
8775
+ return typeCheckFailure(context, value, "Value is not a valid ".concat(this.describe(), ", expected a bigint, a string or a number"));
8776
+ }
8777
+ });
8778
+ Object.defineProperty(IdentifierBigintType.prototype, "getSnapshot", {
8779
+ enumerable: false,
8780
+ configurable: true,
8781
+ writable: true,
8782
+ value: function (node) {
8783
+ return String(node.storedValue);
8784
+ }
8785
+ });
8786
+ Object.defineProperty(IdentifierBigintType.prototype, "describe", {
8787
+ enumerable: false,
8788
+ configurable: true,
8789
+ writable: true,
8790
+ value: function () {
8791
+ return "identifierBigint";
8792
+ }
8793
+ });
8794
+ return IdentifierBigintType;
8795
+ }(SimpleType));
8796
+ /**
8797
+ * `types.identifierBigint` - Similar to `types.identifier`. Snapshots serialize to string (JSON-safe) and deserialize from string, number or bigint.
8798
+ *
8799
+ * Example:
8800
+ * ```ts
8801
+ * const Todo = types.model("Todo", {
8802
+ * id: types.identifierBigint,
8803
+ * title: types.string
8804
+ * })
8805
+ * ```
8806
+ *
8807
+ * @returns
8808
+ */
8809
+ var identifierBigint = new IdentifierBigintType();
8450
8810
  /**
8451
8811
  * Returns if a given value represents an identifier type.
8452
8812
  *
@@ -8468,14 +8828,14 @@ function normalizeIdentifier(id) {
8468
8828
  * @hidden
8469
8829
  */
8470
8830
  function isValidIdentifier(id) {
8471
- return typeof id === "string" || typeof id === "number";
8831
+ return typeof id === "string" || typeof id === "number" || typeof id === "bigint";
8472
8832
  }
8473
8833
  /**
8474
8834
  * @internal
8475
8835
  * @hidden
8476
8836
  */
8477
8837
  function assertIsValidIdentifier(id, argNumber) {
8478
- assertArg(id, isValidIdentifier, "string or number (identifier)", argNumber);
8838
+ assertArg(id, isValidIdentifier, "string, number or bigint (identifier)", argNumber);
8479
8839
  }
8480
8840
 
8481
8841
  /**
@@ -8636,12 +8996,14 @@ var types = {
8636
8996
  integer: integer,
8637
8997
  float: float,
8638
8998
  finite: finite,
8999
+ bigint: bigint,
8639
9000
  Date: DatePrimitive,
8640
9001
  map: map,
8641
9002
  array: array,
8642
9003
  frozen: frozen,
8643
9004
  identifier: identifier,
8644
9005
  identifierNumber: identifierNumber,
9006
+ identifierBigint: identifierBigint,
8645
9007
  late: late,
8646
9008
  lazy: lazy,
8647
9009
  undefined: undefinedType,