mobx-state-tree 7.1.0 → 7.3.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.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Options that control how snapshots/values and type shapes are rendered inside
3
+ * type-checking error messages (see {@link setErrorFormatting}).
4
+ */
5
+ export interface ErrorFormattingOptions {
6
+ /**
7
+ * When `false` (the default), error messages are rendered exactly as they
8
+ * always have been: the offending value is serialized to a single
9
+ * `JSON.stringify` line and the message is capped in length. When `true`,
10
+ * the value is truncated (using the limits below) and, when `indent > 0`,
11
+ * pretty-printed across multiple lines.
12
+ */
13
+ enabled: boolean;
14
+ /**
15
+ * Number of spaces to indent each nesting level by when pretty-printing.
16
+ * Use `0` to keep everything on a single line while still truncating
17
+ * (handy when you only want to bound the message size, not reflow it).
18
+ */
19
+ indent: number;
20
+ /** Strings longer than this are clipped, with a note of how many characters were omitted. */
21
+ maxStringLength: number;
22
+ /** Arrays with more than this many items are clipped, with a note of how many items were omitted. */
23
+ maxArrayLength: number;
24
+ /** Objects with more than this many keys are clipped, with a note of how many keys were omitted. */
25
+ maxPropertyCount: number;
26
+ /** Values nested deeper than this are summarized as `{…}` / `[…]`. */
27
+ maxDepth: number;
28
+ }
29
+ /**
30
+ * Configures how snapshots/values and type shapes are formatted inside
31
+ * type-checking error messages. This is **opt-in**: by default MST keeps its
32
+ * original single-line error formatting, so enabling this does not change
33
+ * behavior for anyone who doesn't call it.
34
+ *
35
+ * The given options are merged over the current ones, so you can set only the
36
+ * fields you care about.
37
+ *
38
+ * @example
39
+ * // pretty-print large snapshots across multiple lines and truncate them
40
+ * setErrorFormatting({ enabled: true })
41
+ *
42
+ * @example
43
+ * // only bound the message size, without reflowing it onto multiple lines
44
+ * setErrorFormatting({ enabled: true, indent: 0 })
45
+ *
46
+ * @example
47
+ * // tweak the truncation limits
48
+ * setErrorFormatting({ enabled: true, maxArrayLength: 3, maxStringLength: 40 })
49
+ *
50
+ * @param options A partial set of {@link ErrorFormattingOptions} to apply.
51
+ */
52
+ export declare function setErrorFormatting(options: Partial<ErrorFormattingOptions>): void;
53
+ /**
54
+ * Returns a copy of the current error formatting options (see
55
+ * {@link setErrorFormatting}). Useful for temporarily overriding and then
56
+ * restoring the configuration.
57
+ *
58
+ * @returns The current {@link ErrorFormattingOptions}.
59
+ */
60
+ export declare function getErrorFormatting(): ErrorFormattingOptions;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { type IModelType, type IAnyModelType, type IDisposer, type IMSTMap, type IMapType, type IMSTArray, type IArrayType, type IType, type IAnyType, type ModelPrimitive, type ISimpleType, type IComplexType, type IAnyComplexType, type IReferenceType, type _CustomCSProcessor, type _CustomOrOther, type _CustomJoin, type _NotCustomized, typecheck, escapeJsonPath, unescapeJsonPath, joinJsonPath, splitJsonPath, type IJsonPatch, type IReversibleJsonPatch, decorate, addMiddleware, type IMiddlewareEvent, type IActionTrackingMiddleware2Call, type IMiddlewareHandler, type IMiddlewareEventType, type IActionTrackingMiddlewareHooks, type IActionTrackingMiddleware2Hooks, process, isStateTreeNode, type IStateTreeNode, type IAnyStateTreeNode, flow, castFlowReturn, applyAction, onAction, type IActionRecorder, type ISerializedActionCall, recordActions, createActionTrackingMiddleware, createActionTrackingMiddleware2, setLivelinessChecking, getLivelinessChecking, type LivelinessMode, setLivelynessChecking, // to be deprecated
1
+ export { type IModelType, type IAnyModelType, type IDisposer, type IMSTMap, type IMapType, type IMSTArray, type IArrayType, type IType, type IAnyType, type ModelPrimitive, type ISimpleType, type IComplexType, type IAnyComplexType, type IReferenceType, type _CustomCSProcessor, type _CustomOrOther, type _CustomJoin, type _NotCustomized, typecheck, escapeJsonPath, unescapeJsonPath, joinJsonPath, splitJsonPath, type IJsonPatch, type IReversibleJsonPatch, decorate, addMiddleware, type IMiddlewareEvent, type IActionTrackingMiddleware2Call, type IMiddlewareHandler, type IMiddlewareEventType, type IActionTrackingMiddlewareHooks, type IActionTrackingMiddleware2Hooks, process, isStateTreeNode, type IStateTreeNode, type IAnyStateTreeNode, flow, castFlowReturn, applyAction, onAction, type IActionRecorder, type ISerializedActionCall, recordActions, createActionTrackingMiddleware, createActionTrackingMiddleware2, setLivelinessChecking, getLivelinessChecking, type LivelinessMode, setErrorFormatting, getErrorFormatting, type ErrorFormattingOptions, setLivelynessChecking, // to be deprecated
2
2
  type LivelynessMode, // to be deprecated
3
3
  type ModelSnapshotType, type ModelCreationType, type ModelSnapshotType2, type ModelCreationType2, type ModelInstanceType, type ModelInstanceTypeProps, type ModelPropertiesDeclarationToProperties, type ModelProperties, type ModelPropertiesDeclaration, type ModelActions, type ITypeUnion, type CustomTypeOptions, type UnionOptions, type Instance, type SnapshotIn, type SnapshotOut, type SnapshotOrInstance, type TypeOrStateTreeNodeToStateTreeNode, type UnionStringArray, getType, getChildType, onPatch, onSnapshot, applyPatch, type IPatchRecorder, recordPatches, protect, unprotect, isProtected, applySnapshot, getSnapshot, hasParent, getParent, hasParentOfType, getParentOfType, getRoot, getPath, getPathParts, isRoot, resolvePath, resolveIdentifier, getIdentifier, tryResolve, getRelativePath, clone, detach, destroy, isAlive, addDisposer, hasEnv, getEnv, walk, type IModelReflectionData, type IModelReflectionPropertiesData, type IMaybeIType, type IMaybe, type IMaybeNull, type IOptionalIType, type OptionalDefaultValueOrFunction, type ValidOptionalValue, type ValidOptionalValues, getMembers, getPropertyMembers, type TypeOfValue, cast, castToSnapshot, castToReferenceSnapshot, isType, isArrayType, isFrozenType, isIdentifierType, isLateType, isLiteralType, isMapType, isModelType, isOptionalType, isPrimitiveType, isReferenceType, isRefinementType, isUnionType, tryReference, isValidReference, type OnReferenceInvalidated, type OnReferenceInvalidatedEvent, type ReferenceOptions, type ReferenceOptionsGetSet, type ReferenceOptionsOnInvalidated, type ReferenceIdentifier, type ISnapshotProcessor, type ISnapshotProcessors, getNodeId, type IActionContext, getRunningActionContext, isActionContextChildOf, isActionContextThisOrChildOf, types, types as t, // We do this as a less ambiguous term for the traditional types module, which sometimes gets confused when discussing "types" in general
4
4
  toGeneratorFunction, toGenerator } from "./internal";
@@ -10,6 +10,7 @@ export * from "./middlewares/createActionTrackingMiddleware2";
10
10
  export * from "./middlewares/on-action";
11
11
  export * from "./core/action";
12
12
  export * from "./core/actionContext";
13
+ export * from "./core/type/errorFormatting";
13
14
  export * from "./core/type/type-checker";
14
15
  export * from "./core/node/identifier-cache";
15
16
  export * from "./core/node/create-node";
@@ -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,
@@ -3232,9 +3265,10 @@ function runWithActionContext(context, fn) {
3232
3265
  var baseIsRunningAction = node._isRunningAction;
3233
3266
  node._isRunningAction = true;
3234
3267
  var previousContext = currentActionContext;
3268
+ var isRootActionContext = !previousContext;
3235
3269
  currentActionContext = context;
3236
3270
  try {
3237
- return runMiddleWares(node, context, fn);
3271
+ return runMiddleWares(node, context, fn, isRootActionContext);
3238
3272
  }
3239
3273
  finally {
3240
3274
  currentActionContext = previousContext;
@@ -3388,17 +3422,44 @@ var CollectedMiddlewares = /** @class */ (function () {
3388
3422
  });
3389
3423
  return CollectedMiddlewares;
3390
3424
  }());
3391
- 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
+ }
3392
3453
  var middlewares = new CollectedMiddlewares(node, originalFn);
3393
3454
  // Short circuit
3394
3455
  if (middlewares.isEmpty)
3395
- return mobx.action(originalFn).apply(null, baseCall.args);
3456
+ return runInActionScope(baseCall, originalFn);
3396
3457
  var result = null;
3397
3458
  function runNextMiddleware(call) {
3398
3459
  var middleware = middlewares.getNextMiddleware();
3399
3460
  var handler = middleware && middleware.handler;
3400
3461
  if (!handler) {
3401
- return mobx.action(originalFn).apply(null, call.args);
3462
+ return runInActionScope(call, originalFn);
3402
3463
  }
3403
3464
  // skip hooks if asked to
3404
3465
  if (!middleware.includeHooks && Hook[call.name]) {
@@ -3434,6 +3495,9 @@ function runMiddleWares(node, baseCall, originalFn) {
3434
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."));
3435
3496
  }
3436
3497
  }
3498
+ if (abortInvoked && (isRootActionContext || !call.parentActionEvent)) {
3499
+ return runInActionScope(call, function () { return result; });
3500
+ }
3437
3501
  return result;
3438
3502
  }
3439
3503
  return runNextMiddleware(baseCall);
@@ -3475,30 +3539,207 @@ function isActionContextThisOrChildOf(actionContext, parentOrThis) {
3475
3539
  return _isActionContextThisOrChildOf(actionContext, parentOrThis, true);
3476
3540
  }
3477
3541
 
3478
- function safeStringify(value) {
3542
+ var defaultOptions = {
3543
+ enabled: false,
3544
+ indent: 2,
3545
+ maxStringLength: 100,
3546
+ maxArrayLength: 10,
3547
+ maxPropertyCount: 30,
3548
+ maxDepth: 5
3549
+ };
3550
+ var currentOptions = __assign({}, defaultOptions);
3551
+ /**
3552
+ * Configures how snapshots/values and type shapes are formatted inside
3553
+ * type-checking error messages. This is **opt-in**: by default MST keeps its
3554
+ * original single-line error formatting, so enabling this does not change
3555
+ * behavior for anyone who doesn't call it.
3556
+ *
3557
+ * The given options are merged over the current ones, so you can set only the
3558
+ * fields you care about.
3559
+ *
3560
+ * @example
3561
+ * // pretty-print large snapshots across multiple lines and truncate them
3562
+ * setErrorFormatting({ enabled: true })
3563
+ *
3564
+ * @example
3565
+ * // only bound the message size, without reflowing it onto multiple lines
3566
+ * setErrorFormatting({ enabled: true, indent: 0 })
3567
+ *
3568
+ * @example
3569
+ * // tweak the truncation limits
3570
+ * setErrorFormatting({ enabled: true, maxArrayLength: 3, maxStringLength: 40 })
3571
+ *
3572
+ * @param options A partial set of {@link ErrorFormattingOptions} to apply.
3573
+ */
3574
+ function setErrorFormatting(options) {
3575
+ currentOptions = __assign(__assign({}, currentOptions), options);
3576
+ }
3577
+ /**
3578
+ * Returns a copy of the current error formatting options (see
3579
+ * {@link setErrorFormatting}). Useful for temporarily overriding and then
3580
+ * restoring the configuration.
3581
+ *
3582
+ * @returns The current {@link ErrorFormattingOptions}.
3583
+ */
3584
+ function getErrorFormatting() {
3585
+ return __assign({}, currentOptions);
3586
+ }
3587
+
3588
+ function safeStringify(value, indent) {
3479
3589
  try {
3480
- return JSON.stringify(value);
3590
+ return JSON.stringify(value, null, indent);
3481
3591
  }
3482
3592
  catch (e) {
3483
3593
  // istanbul ignore next
3484
3594
  return "<Unserializable: ".concat(e, ">");
3485
3595
  }
3486
3596
  }
3597
+ function shortenPrintValue(valueInString) {
3598
+ return valueInString.length < 280
3599
+ ? valueInString
3600
+ : "".concat(valueInString.substring(0, 272), "......").concat(valueInString.substring(valueInString.length - 8));
3601
+ }
3602
+ /**
3603
+ * Returns a clone of `value` in which overly long strings are clipped and large
3604
+ * arrays/objects (or values nested too deeply) are summarized, so the result is
3605
+ * safe to print in an error message without flooding the screen.
3606
+ */
3607
+ function truncateForDisplay(value, depth, options) {
3608
+ if (typeof value === "string") {
3609
+ return value.length > options.maxStringLength
3610
+ ? "".concat(value.slice(0, options.maxStringLength), "\u2026 (").concat(value.length - options.maxStringLength, " more characters)")
3611
+ : value;
3612
+ }
3613
+ if (Array.isArray(value)) {
3614
+ if (depth >= options.maxDepth)
3615
+ return "[…]";
3616
+ var items = value
3617
+ .slice(0, options.maxArrayLength)
3618
+ .map(function (item) { return truncateForDisplay(item, depth + 1, options); });
3619
+ if (value.length > options.maxArrayLength) {
3620
+ items.push("\u2026 ".concat(value.length - options.maxArrayLength, " more items"));
3621
+ }
3622
+ return items;
3623
+ }
3624
+ if (isPlainObject(value)) {
3625
+ if (depth >= options.maxDepth)
3626
+ return "{…}";
3627
+ var result_1 = {};
3628
+ var keys = Object.keys(value);
3629
+ keys.slice(0, options.maxPropertyCount).forEach(function (key) {
3630
+ result_1[key] = truncateForDisplay(value[key], depth + 1, options);
3631
+ });
3632
+ if (keys.length > options.maxPropertyCount) {
3633
+ result_1["…"] = "".concat(keys.length - options.maxPropertyCount, " more keys");
3634
+ }
3635
+ return result_1;
3636
+ }
3637
+ return value;
3638
+ }
3487
3639
  /**
3488
3640
  * @internal
3489
3641
  * @hidden
3490
3642
  */
3491
3643
  function prettyPrintValue(value) {
3492
- return typeof value === "function"
3493
- ? "<function".concat(value.name ? " " + value.name : "", ">")
3494
- : isStateTreeNode(value)
3495
- ? "<".concat(value, ">")
3496
- : "`".concat(safeStringify(value), "`");
3644
+ if (typeof value === "function") {
3645
+ return "<function".concat(value.name ? " " + value.name : "", ">");
3646
+ }
3647
+ if (isStateTreeNode(value)) {
3648
+ return "<".concat(value, ">");
3649
+ }
3650
+ var options = getErrorFormatting();
3651
+ if (!options.enabled) {
3652
+ // Default behavior: serialize the value compactly on a single line.
3653
+ // JSON.stringify returns `undefined` for values like `undefined` itself,
3654
+ // which the template literal coerces back to a string.
3655
+ return "`".concat(safeStringify(value), "`");
3656
+ }
3657
+ // Opt-in behavior: clip long strings, big arrays/objects and deep nesting, and
3658
+ // (when indent > 0) pretty-print the result across multiple lines.
3659
+ var truncated = truncateForDisplay(value, 0, options);
3660
+ return "`".concat(safeStringify(truncated, options.indent || undefined), "`");
3497
3661
  }
3498
- function shortenPrintValue(valueInString) {
3499
- return valueInString.length < 280
3500
- ? valueInString
3501
- : "".concat(valueInString.substring(0, 272), "......").concat(valueInString.substring(valueInString.length - 8));
3662
+ /**
3663
+ * Re-indents a type description (as produced by `IType.describe()`) across
3664
+ * multiple lines, by breaking after the `{`, `}` and `;` separators used in
3665
+ * model shapes (while leaving union `|` and array `[]` parts inline).
3666
+ * Characters inside string literals (e.g. literal types like `"a;b"`) are left
3667
+ * untouched.
3668
+ *
3669
+ * `indentSize` is the number of spaces per nesting level; when it is `0` (or
3670
+ * negative) the description is returned unchanged on a single line. As this runs
3671
+ * while formatting an error that is already being thrown, it must never throw
3672
+ * itself: any unexpected input falls back to the original, unformatted
3673
+ * description.
3674
+ *
3675
+ * @internal
3676
+ * @hidden
3677
+ */
3678
+ function prettyPrintDescription(description, indentSize) {
3679
+ if (indentSize <= 0) {
3680
+ return description;
3681
+ }
3682
+ try {
3683
+ var step_1 = " ".repeat(indentSize);
3684
+ var result_2 = "";
3685
+ var depth_1 = 0;
3686
+ var stringDelimiter = null;
3687
+ var escaped = false;
3688
+ var newline = function () {
3689
+ // drop any trailing spaces (e.g. the "{ " / "; " separators) before breaking,
3690
+ // and never let a malformed (over-closed) shape produce a negative indent
3691
+ result_2 = result_2.replace(/[ \t]+$/, "");
3692
+ result_2 += "\n" + step_1.repeat(Math.max(0, depth_1));
3693
+ };
3694
+ for (var i = 0; i < description.length; i++) {
3695
+ var char = description[i];
3696
+ if (stringDelimiter) {
3697
+ result_2 += char;
3698
+ if (escaped) {
3699
+ escaped = false;
3700
+ }
3701
+ else if (char === "\\") {
3702
+ escaped = true;
3703
+ }
3704
+ else if (char === stringDelimiter) {
3705
+ stringDelimiter = null;
3706
+ }
3707
+ continue;
3708
+ }
3709
+ switch (char) {
3710
+ case '"':
3711
+ case "'":
3712
+ stringDelimiter = char;
3713
+ result_2 += char;
3714
+ break;
3715
+ case "{":
3716
+ depth_1++;
3717
+ result_2 += "{";
3718
+ newline();
3719
+ while (description[i + 1] === " ")
3720
+ i++;
3721
+ break;
3722
+ case "}":
3723
+ depth_1--;
3724
+ newline();
3725
+ result_2 += "}";
3726
+ break;
3727
+ case ";":
3728
+ result_2 += ";";
3729
+ newline();
3730
+ while (description[i + 1] === " ")
3731
+ i++;
3732
+ break;
3733
+ default:
3734
+ result_2 += char;
3735
+ }
3736
+ }
3737
+ return result_2;
3738
+ }
3739
+ catch (e) {
3740
+ // istanbul ignore next - defensive: never let formatting hide the real error
3741
+ return description;
3742
+ }
3502
3743
  }
3503
3744
  function toErrorString(error) {
3504
3745
  var value = error.value;
@@ -3517,12 +3758,18 @@ function toErrorString(error) {
3517
3758
  ? "value"
3518
3759
  : "snapshot";
3519
3760
  var isSnapshotCompatible = type && isStateTreeNode(value) && type.is(getStateTreeNode(value).snapshot);
3761
+ // When error formatting is enabled, the type shape is re-indented using the
3762
+ // same indent setting as values; otherwise it's left on a single line.
3763
+ var formatting = getErrorFormatting();
3764
+ var describeType = function (t) {
3765
+ return formatting.enabled ? prettyPrintDescription(t.describe(), formatting.indent) : t.describe();
3766
+ };
3520
3767
  return ("".concat(pathPrefix).concat(currentTypename, " ").concat(prettyPrintValue(value), " is not assignable ").concat(type ? "to type: `".concat(type.name, "`") : "") +
3521
3768
  (error.message ? " (".concat(error.message, ")") : "") +
3522
3769
  (type
3523
3770
  ? isPrimitiveType(type) || isPrimitive(value)
3524
3771
  ? "."
3525
- : ", expected an instance of `".concat(type.name, "` or a snapshot like `").concat(type.describe(), "` instead.") +
3772
+ : ", expected an instance of `".concat(type.name, "` or a snapshot like `").concat(describeType(type), "` instead.") +
3526
3773
  (isSnapshotCompatible
3527
3774
  ? " (Note that a snapshot of the provided value is compatible with the targeted type)"
3528
3775
  : "")
@@ -3585,7 +3832,14 @@ function validationErrorsToString(type, value, errors) {
3585
3832
  if (errors.length === 0) {
3586
3833
  return undefined;
3587
3834
  }
3588
- return ("Error while converting ".concat(shortenPrintValue(prettyPrintValue(value)), " to `").concat(type.name, "`:\n\n ") + errors.map(toErrorString).join("\n "));
3835
+ // When formatting is disabled, keep the original behavior of capping the
3836
+ // header value's length; when enabled, truncation already bounds its size.
3837
+ var printedValue = prettyPrintValue(value);
3838
+ var headerValue = getErrorFormatting().enabled
3839
+ ? printedValue
3840
+ : shortenPrintValue(printedValue);
3841
+ return ("Error while converting ".concat(headerValue, " to `").concat(type.name, "`:\n\n ") +
3842
+ errors.map(toErrorString).join("\n "));
3589
3843
  }
3590
3844
 
3591
3845
  var identifierCacheId = 0;
@@ -8133,7 +8387,7 @@ var BaseReferenceType = /** @class */ (function (_super) {
8133
8387
  value: function (value, context) {
8134
8388
  return isValidIdentifier(value)
8135
8389
  ? typeCheckSuccess()
8136
- : typeCheckFailure(context, value, "Value is not a valid identifier, which is a string or a number");
8390
+ : typeCheckFailure(context, value, "Value is not a valid identifier, which is a string, number or a bigint");
8137
8391
  }
8138
8392
  });
8139
8393
  Object.defineProperty(BaseReferenceType.prototype, "fireInvalidated", {
@@ -8222,6 +8476,23 @@ var BaseReferenceType = /** @class */ (function (_super) {
8222
8476
  onRefTargetDestroyedHookDisposer();
8223
8477
  }
8224
8478
  });
8479
+ var scheduleRetryAfterReconciliation = function () {
8480
+ var retry = function () {
8481
+ if (!storedRefNode.isAlive) {
8482
+ return;
8483
+ }
8484
+ if (_this.getSnapshot(storedRefNode) !== identifier) {
8485
+ return;
8486
+ }
8487
+ startWatching(false);
8488
+ };
8489
+ if (getCurrentActionContext()) {
8490
+ storedRefNode.root.enqueueEndOfAction(retry);
8491
+ }
8492
+ else {
8493
+ setImmediateWithFallback(retry);
8494
+ }
8495
+ };
8225
8496
  var startWatching = function (sync) {
8226
8497
  // re-create hook in case the stored ref gets reattached
8227
8498
  if (onRefTargetDestroyedHookDisposer) {
@@ -8239,12 +8510,13 @@ var BaseReferenceType = /** @class */ (function (_super) {
8239
8510
  refTargetNodeExists = storedRefNode.root.identifierCache.has(_this.targetType, normalizeIdentifier(identifier));
8240
8511
  }
8241
8512
  if (!refTargetNodeExists) {
8242
- // we cannot change the reference in sync mode
8243
- // since we are in the middle of a reconciliation/instantiation and the change would be overwritten
8244
- // for those cases just let the wrong reference be assigned and fail upon usage
8245
- // (like current references do)
8246
- // this means that effectively this code will only run when it is created from a snapshot
8247
- if (!sync) {
8513
+ // if the tree is already attached we may still be in the middle of a reconcile/applySnapshot,
8514
+ // so wait until the current MST action finishes before deciding whether to invalidate or
8515
+ // attach a watcher to a target that appeared later in the same action.
8516
+ if (sync) {
8517
+ scheduleRetryAfterReconciliation();
8518
+ }
8519
+ else {
8248
8520
  _this.fireInvalidated("invalidSnapshotReference", storedRefNode, identifier, null);
8249
8521
  }
8250
8522
  }
@@ -8594,7 +8866,7 @@ var IdentifierNumberType = /** @class */ (function (_super) {
8594
8866
  * Inside a state tree, for each type can exist only one instance for each given identifier.
8595
8867
  * For example there couldn't be 2 instances of user with id 1. If you need more, consider using references.
8596
8868
  * Identifier can be used only as type property of a model.
8597
- * This type accepts as parameter the value type of the identifier field that can be either string or number.
8869
+ * This type accepts as parameter the value type of the identifier field that can be either string, number or bigint.
8598
8870
  *
8599
8871
  * Example:
8600
8872
  * ```ts
@@ -8621,6 +8893,110 @@ var identifier = new IdentifierType();
8621
8893
  * @returns
8622
8894
  */
8623
8895
  var identifierNumber = new IdentifierNumberType();
8896
+ /**
8897
+ * @internal
8898
+ * @hidden
8899
+ * IdentifierBigintType uses SimpleType<bigint | string | number, string, bigint> so snapshots serialize to string (JSON-safe).
8900
+ */
8901
+ var IdentifierBigintType = /** @class */ (function (_super) {
8902
+ __extends(IdentifierBigintType, _super);
8903
+ function IdentifierBigintType() {
8904
+ var _this = _super.call(this, "identifierBigint") || this;
8905
+ Object.defineProperty(_this, "flags", {
8906
+ enumerable: true,
8907
+ configurable: true,
8908
+ writable: true,
8909
+ value: TypeFlags.Identifier
8910
+ });
8911
+ return _this;
8912
+ }
8913
+ Object.defineProperty(IdentifierBigintType.prototype, "createNewInstance", {
8914
+ enumerable: false,
8915
+ configurable: true,
8916
+ writable: true,
8917
+ value: function (snapshot) {
8918
+ if (typeof snapshot === "bigint")
8919
+ return snapshot;
8920
+ return BigInt(snapshot);
8921
+ }
8922
+ });
8923
+ Object.defineProperty(IdentifierBigintType.prototype, "instantiate", {
8924
+ enumerable: false,
8925
+ configurable: true,
8926
+ writable: true,
8927
+ value: function (parent, subpath, environment, initialValue) {
8928
+ if (!parent || !(parent.type instanceof ModelType))
8929
+ throw new MstError("Identifier types can only be instantiated as direct child of a model type");
8930
+ return createScalarNode(this, parent, subpath, environment, initialValue);
8931
+ }
8932
+ });
8933
+ Object.defineProperty(IdentifierBigintType.prototype, "reconcile", {
8934
+ enumerable: false,
8935
+ configurable: true,
8936
+ writable: true,
8937
+ value: function (current, newValue, parent, subpath) {
8938
+ var currentVal = current.storedValue;
8939
+ var newVal = typeof newValue === "bigint" ? newValue : BigInt(newValue);
8940
+ if (currentVal !== newVal)
8941
+ throw new MstError("Tried to change identifier from '".concat(currentVal, "' to '").concat(newVal, "'. Changing identifiers is not allowed."));
8942
+ current.setParent(parent, subpath);
8943
+ return current;
8944
+ }
8945
+ });
8946
+ Object.defineProperty(IdentifierBigintType.prototype, "isValidSnapshot", {
8947
+ enumerable: false,
8948
+ configurable: true,
8949
+ writable: true,
8950
+ value: function (value, context) {
8951
+ if (typeof value === "bigint") {
8952
+ return typeCheckSuccess();
8953
+ }
8954
+ if (typeof value === "string" || typeof value === "number") {
8955
+ try {
8956
+ // BigInt primitive constructor verifies whether the value is a valid integer
8957
+ BigInt(value);
8958
+ return typeCheckSuccess();
8959
+ }
8960
+ catch (e) {
8961
+ var errorMessage = e instanceof Error ? e.message : String(e);
8962
+ return typeCheckFailure(context, value, "Value is not a valid ".concat(this.describe(), ": ").concat(errorMessage));
8963
+ }
8964
+ }
8965
+ return typeCheckFailure(context, value, "Value is not a valid ".concat(this.describe(), ", expected a bigint, a string or a number"));
8966
+ }
8967
+ });
8968
+ Object.defineProperty(IdentifierBigintType.prototype, "getSnapshot", {
8969
+ enumerable: false,
8970
+ configurable: true,
8971
+ writable: true,
8972
+ value: function (node) {
8973
+ return String(node.storedValue);
8974
+ }
8975
+ });
8976
+ Object.defineProperty(IdentifierBigintType.prototype, "describe", {
8977
+ enumerable: false,
8978
+ configurable: true,
8979
+ writable: true,
8980
+ value: function () {
8981
+ return "identifierBigint";
8982
+ }
8983
+ });
8984
+ return IdentifierBigintType;
8985
+ }(SimpleType));
8986
+ /**
8987
+ * `types.identifierBigint` - Similar to `types.identifier`. Snapshots serialize to string (JSON-safe) and deserialize from string, number or bigint.
8988
+ *
8989
+ * Example:
8990
+ * ```ts
8991
+ * const Todo = types.model("Todo", {
8992
+ * id: types.identifierBigint,
8993
+ * title: types.string
8994
+ * })
8995
+ * ```
8996
+ *
8997
+ * @returns
8998
+ */
8999
+ var identifierBigint = new IdentifierBigintType();
8624
9000
  /**
8625
9001
  * Returns if a given value represents an identifier type.
8626
9002
  *
@@ -8642,14 +9018,14 @@ function normalizeIdentifier(id) {
8642
9018
  * @hidden
8643
9019
  */
8644
9020
  function isValidIdentifier(id) {
8645
- return typeof id === "string" || typeof id === "number";
9021
+ return typeof id === "string" || typeof id === "number" || typeof id === "bigint";
8646
9022
  }
8647
9023
  /**
8648
9024
  * @internal
8649
9025
  * @hidden
8650
9026
  */
8651
9027
  function assertIsValidIdentifier(id, argNumber) {
8652
- assertArg(id, isValidIdentifier, "string or number (identifier)", argNumber);
9028
+ assertArg(id, isValidIdentifier, "string, number or bigint (identifier)", argNumber);
8653
9029
  }
8654
9030
 
8655
9031
  /**
@@ -8817,6 +9193,7 @@ var types = {
8817
9193
  frozen: frozen,
8818
9194
  identifier: identifier,
8819
9195
  identifierNumber: identifierNumber,
9196
+ identifierBigint: identifierBigint,
8820
9197
  late: late,
8821
9198
  lazy: lazy,
8822
9199
  undefined: undefinedType,
@@ -8843,6 +9220,7 @@ exports.escapeJsonPath = escapeJsonPath;
8843
9220
  exports.flow = flow;
8844
9221
  exports.getChildType = getChildType;
8845
9222
  exports.getEnv = getEnv;
9223
+ exports.getErrorFormatting = getErrorFormatting;
8846
9224
  exports.getIdentifier = getIdentifier;
8847
9225
  exports.getLivelinessChecking = getLivelinessChecking;
8848
9226
  exports.getMembers = getMembers;
@@ -8890,6 +9268,7 @@ exports.recordActions = recordActions;
8890
9268
  exports.recordPatches = recordPatches;
8891
9269
  exports.resolveIdentifier = resolveIdentifier;
8892
9270
  exports.resolvePath = resolvePath;
9271
+ exports.setErrorFormatting = setErrorFormatting;
8893
9272
  exports.setLivelinessChecking = setLivelinessChecking;
8894
9273
  exports.setLivelynessChecking = setLivelynessChecking;
8895
9274
  exports.splitJsonPath = splitJsonPath;