mobx-state-tree 7.2.0 → 7.3.1

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";
@@ -3539,30 +3539,207 @@ function isActionContextThisOrChildOf(actionContext, parentOrThis) {
3539
3539
  return _isActionContextThisOrChildOf(actionContext, parentOrThis, true);
3540
3540
  }
3541
3541
 
3542
- 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) {
3543
3589
  try {
3544
- return JSON.stringify(value);
3590
+ return JSON.stringify(value, null, indent);
3545
3591
  }
3546
3592
  catch (e) {
3547
3593
  // istanbul ignore next
3548
3594
  return "<Unserializable: ".concat(e, ">");
3549
3595
  }
3550
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
+ }
3551
3639
  /**
3552
3640
  * @internal
3553
3641
  * @hidden
3554
3642
  */
3555
3643
  function prettyPrintValue(value) {
3556
- return typeof value === "function"
3557
- ? "<function".concat(value.name ? " " + value.name : "", ">")
3558
- : isStateTreeNode(value)
3559
- ? "<".concat(value, ">")
3560
- : "`".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), "`");
3561
3661
  }
3562
- function shortenPrintValue(valueInString) {
3563
- return valueInString.length < 280
3564
- ? valueInString
3565
- : "".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
+ }
3566
3743
  }
3567
3744
  function toErrorString(error) {
3568
3745
  var value = error.value;
@@ -3581,12 +3758,18 @@ function toErrorString(error) {
3581
3758
  ? "value"
3582
3759
  : "snapshot";
3583
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
+ };
3584
3767
  return ("".concat(pathPrefix).concat(currentTypename, " ").concat(prettyPrintValue(value), " is not assignable ").concat(type ? "to type: `".concat(type.name, "`") : "") +
3585
3768
  (error.message ? " (".concat(error.message, ")") : "") +
3586
3769
  (type
3587
3770
  ? isPrimitiveType(type) || isPrimitive(value)
3588
3771
  ? "."
3589
- : ", 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.") +
3590
3773
  (isSnapshotCompatible
3591
3774
  ? " (Note that a snapshot of the provided value is compatible with the targeted type)"
3592
3775
  : "")
@@ -3649,7 +3832,14 @@ function validationErrorsToString(type, value, errors) {
3649
3832
  if (errors.length === 0) {
3650
3833
  return undefined;
3651
3834
  }
3652
- 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 "));
3653
3843
  }
3654
3844
 
3655
3845
  var identifierCacheId = 0;
@@ -5128,7 +5318,7 @@ var MapIdentifierMode;
5128
5318
  var MSTMap = /** @class */ (function (_super) {
5129
5319
  __extends(MSTMap, _super);
5130
5320
  function MSTMap(initialData, name) {
5131
- return _super.call(this, initialData, mobx.observable.ref.enhancer, name) || this;
5321
+ return _super.call(this, initialData, function (v) { return v; }, name) || this;
5132
5322
  }
5133
5323
  Object.defineProperty(MSTMap.prototype, "get", {
5134
5324
  enumerable: false,
@@ -9030,6 +9220,7 @@ exports.escapeJsonPath = escapeJsonPath;
9030
9220
  exports.flow = flow;
9031
9221
  exports.getChildType = getChildType;
9032
9222
  exports.getEnv = getEnv;
9223
+ exports.getErrorFormatting = getErrorFormatting;
9033
9224
  exports.getIdentifier = getIdentifier;
9034
9225
  exports.getLivelinessChecking = getLivelinessChecking;
9035
9226
  exports.getMembers = getMembers;
@@ -9077,6 +9268,7 @@ exports.recordActions = recordActions;
9077
9268
  exports.recordPatches = recordPatches;
9078
9269
  exports.resolveIdentifier = resolveIdentifier;
9079
9270
  exports.resolvePath = resolvePath;
9271
+ exports.setErrorFormatting = setErrorFormatting;
9080
9272
  exports.setLivelinessChecking = setLivelinessChecking;
9081
9273
  exports.setLivelynessChecking = setLivelynessChecking;
9082
9274
  exports.splitJsonPath = splitJsonPath;