@jbrowse/mobx-state-tree 5.12.0 → 6.0.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.
@@ -1,4 +1,4 @@
1
- import { isComputedProp, isObservableProp, createAtom, action, computed, _allowStateChangesInsideComputed, reaction, runInAction, observable, values, entries, isObservableArray, _getGlobalState, isObservableObject, defineProperty as defineProperty$1, _interceptReads, intercept, observe, ObservableMap, _getAdministration, set, makeObservable, getAtom, when } from 'mobx';
1
+ import { isComputedProp, isObservableProp, createAtom, action, computed, _allowStateChangesInsideComputed, reaction, runInAction, observable, values, entries, isObservableArray, isObservableObject, defineProperty as defineProperty$1, _interceptReads, intercept, observe, ObservableMap, _getAdministration, set, makeObservable, getAtom, when } from 'mobx';
2
2
 
3
3
  let livelinessChecking = "warn";
4
4
  /**
@@ -1137,6 +1137,10 @@ const snapshotReactionOptions = {
1137
1137
  throw e;
1138
1138
  }
1139
1139
  };
1140
+ // keepAlive lets the snapshot computed memoize its value even with no observer,
1141
+ // so getSnapshot() stays referentially stable without an eager snapshot
1142
+ // reaction serializing the whole tree at create time. Shared: mobx only reads it.
1143
+ const snapshotComputedOptions = { keepAlive: true };
1140
1144
  /**
1141
1145
  * @internal
1142
1146
  * @hidden
@@ -1169,9 +1173,18 @@ class ObjectNode extends BaseNode {
1169
1173
  _cachedInitialSnapshot;
1170
1174
  _cachedInitialSnapshotCreated = false;
1171
1175
  _snapshotComputed;
1176
+ // whether _snapshotComputed has ever run — see createObservableInstance
1177
+ _snapshotComputedEvaluated = false;
1172
1178
  constructor(complexType, parent, subpath, environment, initialValue) {
1173
1179
  super(complexType, parent, subpath, environment);
1174
- this._snapshotComputed = computed(() => freeze(this.getSnapshot()));
1180
+ // keepAlive: memoize the snapshot after the first read even with no
1181
+ // observer, so getSnapshot() is referentially stable (and reconcile-by-
1182
+ // snapshot works) without eagerly serializing the whole tree at create
1183
+ // time — the previous cost, driven by the eager root reaction below.
1184
+ this._snapshotComputed = computed(() => {
1185
+ this._snapshotComputedEvaluated = true;
1186
+ return freeze(this.getSnapshot());
1187
+ }, snapshotComputedOptions);
1175
1188
  this.unbox = this.unbox.bind(this);
1176
1189
  this._initialSnapshot = freeze(initialValue);
1177
1190
  this.identifierAttribute = complexType.identifierAttribute;
@@ -1255,10 +1268,17 @@ class ObjectNode extends BaseNode {
1255
1268
  this._isRunningAction = false;
1256
1269
  }
1257
1270
  this._observableInstanceState = ObservableInstanceLifecycle.CREATED;
1258
- this._snapshotComputed.trackAndCompute();
1259
- if (this.isRoot) {
1260
- this._addSnapshotReaction();
1261
- }
1271
+ // The snapshot computed branches on the non-observable
1272
+ // "_observableInstanceState" flag we just flipped, so a value already
1273
+ // memoized from the initial snapshot is now stale (mobx can't see the
1274
+ // change) — refresh it. When it was never read there is nothing to refresh,
1275
+ // and forcing it here would serialize the whole subtree (the dominant cost
1276
+ // of creating a root) for a value nobody has asked for yet, so we skip it.
1277
+ this.refreshMemoizedSnapshot();
1278
+ // The root's snapshot reaction only drives onSnapshot; set it up lazily
1279
+ // (onSnapshot already does) rather than eagerly here, so a root nobody
1280
+ // subscribes to never pays for a full-tree snapshot at creation. keepAlive
1281
+ // on _snapshotComputed preserves snapshot referential stability without it.
1262
1282
  this._childNodes = EMPTY_OBJECT;
1263
1283
  this.state = NodeLifeCycle.CREATED;
1264
1284
  if (fireHooks) {
@@ -1363,6 +1383,21 @@ class ObjectNode extends BaseNode {
1363
1383
  }
1364
1384
  return this._snapshotComputed.get();
1365
1385
  }
1386
+ /**
1387
+ * @internal
1388
+ * @hidden
1389
+ * Recompute+retrack the keepAlive snapshot computed if it has already run.
1390
+ * Needed whenever something changes what the snapshot would produce without
1391
+ * an observable mobx would track: flipping the (non-observable) observable-
1392
+ * instance state, or SnapshotProcessor rewriting getSnapshot after
1393
+ * construction (see snapshotProcessor._fixNode). If it never ran, there is
1394
+ * nothing cached to go stale, so this is a no-op.
1395
+ */
1396
+ refreshMemoizedSnapshot() {
1397
+ if (this._snapshotComputedEvaluated) {
1398
+ this._snapshotComputed.trackAndCompute();
1399
+ }
1400
+ }
1366
1401
  // NOTE: we use this method to get snapshot without creating @computed overhead
1367
1402
  getSnapshot() {
1368
1403
  if (!this.isAlive) {
@@ -3044,9 +3079,7 @@ const EMPTY_OBJECT = Object.freeze({});
3044
3079
  * @internal
3045
3080
  * @hidden
3046
3081
  */
3047
- const mobxShallow = _getGlobalState().useProxies
3048
- ? { deep: false }
3049
- : { deep: false, proxy: false };
3082
+ const mobxShallow = { deep: false };
3050
3083
  Object.freeze(mobxShallow);
3051
3084
  /**
3052
3085
  * @internal
@@ -3310,6 +3343,11 @@ let _typeChecking;
3310
3343
  function setTypeChecking(enabled) {
3311
3344
  _typeChecking = enabled;
3312
3345
  }
3346
+ // the ENABLE_TYPE_CHECK env var is fixed at process start, so read it once:
3347
+ // process.env access is a comparatively expensive lookup and isTypeCheckingEnabled
3348
+ // runs on every create() / typed write. The setTypeChecking() override and
3349
+ // dev-mode default stay live below.
3350
+ const _envTypeCheck = typeof process !== "undefined" && process.env?.ENABLE_TYPE_CHECK === "true";
3313
3351
  /**
3314
3352
  * @internal
3315
3353
  * @hidden
@@ -3317,10 +3355,7 @@ function setTypeChecking(enabled) {
3317
3355
  function isTypeCheckingEnabled() {
3318
3356
  // an explicit setTypeChecking() override (incl. `false`) wins over the
3319
3357
  // dev-mode / env-var default, hence ?? rather than ||
3320
- return (_typeChecking ??
3321
- (devMode() ||
3322
- (typeof process !== "undefined" &&
3323
- process.env?.ENABLE_TYPE_CHECK === "true")));
3358
+ return _typeChecking ?? (devMode() || _envTypeCheck);
3324
3359
  }
3325
3360
  let _devMode = process.env.NODE_ENV !== "production";
3326
3361
  /**
@@ -3723,6 +3758,11 @@ class SnapshotProcessor extends BaseType {
3723
3758
  }
3724
3759
  const oldGetSnapshot = node.getSnapshot;
3725
3760
  node.getSnapshot = () => this.postProcessSnapshot(oldGetSnapshot.call(node), node);
3761
+ // getSnapshot was just rewritten; refresh any snapshot already memoized for
3762
+ // this node (e.g. it was serialized before being moved under this processor)
3763
+ if (node instanceof ObjectNode) {
3764
+ node.refreshMemoizedSnapshot();
3765
+ }
3726
3766
  if (!isUnionType(this._subtype)) {
3727
3767
  node.getReconciliationType = () => {
3728
3768
  return this;
@@ -3867,7 +3907,11 @@ var MapIdentifierMode;
3867
3907
  })(MapIdentifierMode || (MapIdentifierMode = {}));
3868
3908
  class MSTMap extends ObservableMap {
3869
3909
  constructor(initialData, name) {
3870
- super(initialData, observable.ref.enhancer, name);
3910
+ // mobx's default (deep) enhancer. The old `observable.ref.enhancer` arg
3911
+ // read undefined ever since mobx 6 renamed the field to `options_.enhancer`,
3912
+ // so deep has been the effective behavior all along; mobx 7 dropped
3913
+ // `observable.ref` entirely.
3914
+ super(initialData, undefined, name);
3871
3915
  }
3872
3916
  get(key) {
3873
3917
  // maybe this is over-enthousiastic? normalize numeric keys to strings
@@ -4645,11 +4689,27 @@ class ModelType extends ComplexType {
4645
4689
  constructor(opts) {
4646
4690
  super(opts.name || defaultObjectOptions.name);
4647
4691
  Object.assign(this, defaultObjectOptions, opts);
4648
- // ensures that any default value gets converted to its related type
4649
- this.properties = toPropertiesObject(this.properties);
4650
- freeze(this.properties); // make sure nobody messes with it
4651
- this.propertyNames = Object.keys(this.properties);
4652
- this.identifierAttribute = this._getIdentifierAttribute();
4692
+ if (opts.propertiesArePreProcessed) {
4693
+ // `properties` is a parent type's already-converted + frozen output
4694
+ // (chain step with no new props), so its derived propertyNames and
4695
+ // identifierAttribute are identical to the parent's — reuse them verbatim
4696
+ // (cloneAndEnhance passed them in) instead of re-running Object.keys and
4697
+ // the per-prop identifier scan, both O(props), on every step.
4698
+ this.propertyNames = opts.propertyNames;
4699
+ this.identifierAttribute = opts.identifierAttribute;
4700
+ }
4701
+ else {
4702
+ // `propertiesAreConverted` (set by cloneAndEnhance when props are added)
4703
+ // means every value is already a type — the parent's converted bag merged
4704
+ // with a freshly converted delta — so skip re-converting. Only raw entry
4705
+ // points (`model()`) still need the full toPropertiesObject pass.
4706
+ if (!opts.propertiesAreConverted) {
4707
+ this.properties = toPropertiesObject(this.properties);
4708
+ }
4709
+ freeze(this.properties); // make sure nobody messes with it
4710
+ this.propertyNames = Object.keys(this.properties);
4711
+ this.identifierAttribute = this._getIdentifierAttribute();
4712
+ }
4653
4713
  }
4654
4714
  _getIdentifierAttribute() {
4655
4715
  let identifierAttribute = undefined;
@@ -4664,9 +4724,35 @@ class ModelType extends ComplexType {
4664
4724
  return identifierAttribute;
4665
4725
  }
4666
4726
  cloneAndEnhance(opts) {
4727
+ // Fast path: a chain step that adds no new properties (.actions/.views/
4728
+ // .volatile/.named/pre-postProcessor) reuses this type's already-converted +
4729
+ // frozen properties (and their derived names/identifier) verbatim.
4730
+ const hasNewProps = opts.properties !== undefined && Object.keys(opts.properties).length > 0;
4731
+ if (!hasNewProps) {
4732
+ return new ModelType({
4733
+ name: opts.name || this.name,
4734
+ properties: this.properties,
4735
+ propertiesArePreProcessed: true,
4736
+ // safe to share: propertyNames is never mutated after construction
4737
+ propertyNames: this.propertyNames,
4738
+ identifierAttribute: this.identifierAttribute,
4739
+ initializers: this.initializers.concat(opts.initializers || []),
4740
+ preProcessor: opts.preProcessor || this.preProcessor,
4741
+ postProcessor: opts.postProcessor || this.postProcessor
4742
+ });
4743
+ }
4744
+ // Adding props: this type's `properties` is already converted+frozen, so only
4745
+ // the delta needs conversion. compose passes already-converted props
4746
+ // (cur.properties) and flags them; `.props()` passes a raw declaration. Either
4747
+ // way the merged bag is fully converted, so the constructor skips re-converting
4748
+ // the (potentially large) inherited set — the previous hot spot in compose.
4749
+ const convertedNewProps = opts.propertiesAreConverted
4750
+ ? opts.properties
4751
+ : toPropertiesObject(opts.properties);
4667
4752
  return new ModelType({
4668
4753
  name: opts.name || this.name,
4669
- properties: Object.assign({}, this.properties, opts.properties),
4754
+ properties: Object.assign({}, this.properties, convertedNewProps),
4755
+ propertiesAreConverted: true,
4670
4756
  initializers: this.initializers.concat(opts.initializers || []),
4671
4757
  preProcessor: opts.preProcessor || this.preProcessor,
4672
4758
  postProcessor: opts.postProcessor || this.postProcessor
@@ -4763,6 +4849,29 @@ class ModelType extends ComplexType {
4763
4849
  };
4764
4850
  return this.cloneAndEnhance({ initializers: [viewInitializer] });
4765
4851
  }
4852
+ /**
4853
+ * @internal
4854
+ * @hidden
4855
+ * Materializes an additional actions/views/state extension onto an
4856
+ * already-created instance, using the same machinery as `.extend()` runs at
4857
+ * creation time. Powers {@link extendInstance}; callers must ensure the writes
4858
+ * are permitted (see extendInstance, which runs this in an action context).
4859
+ */
4860
+ applyExtensionToInstance(self, extension) {
4861
+ const { actions, views, state, ...rest } = extension;
4862
+ for (const key in rest) {
4863
+ throw fail(`extendInstance should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '${key}'`);
4864
+ }
4865
+ if (state) {
4866
+ this.instantiateVolatileState(self, state);
4867
+ }
4868
+ if (views) {
4869
+ this.instantiateViews(self, views);
4870
+ }
4871
+ if (actions) {
4872
+ this.instantiateActions(self, actions);
4873
+ }
4874
+ }
4766
4875
  instantiateViews(self, views) {
4767
4876
  // check views return
4768
4877
  if (!isPlainObject(views)) {
@@ -5023,6 +5132,8 @@ function compose(...args) {
5023
5132
  .reduce((prev, cur) => prev.cloneAndEnhance({
5024
5133
  name: `${prev.name}_${cur.name}`,
5025
5134
  properties: cur.properties,
5135
+ // cur.properties is another ModelType's already-converted+frozen bag
5136
+ propertiesAreConverted: true,
5026
5137
  initializers: cur.initializers,
5027
5138
  preProcessor: (snapshot) => cur.applySnapshotPreProcessor(prev.applySnapshotPreProcessor(snapshot)),
5028
5139
  postProcessor: (snapshot) => cur.applySnapshotPostProcessor(prev.applySnapshotPostProcessor(snapshot))
@@ -5038,6 +5149,46 @@ function compose(...args) {
5038
5149
  function isModelType(type) {
5039
5150
  return isType(type) && (type.flags & TypeFlags.Object) > 0;
5040
5151
  }
5152
+ /**
5153
+ * `extendInstance` - attaches additional actions, views and volatile state to an
5154
+ * already-created model instance, using the same instantiation machinery as
5155
+ * `.extend()`. This enables lazily loading a model's views/actions chain: create
5156
+ * the model with only its base props (plus any critical-path members), then attach
5157
+ * the rest at runtime — e.g. from a dynamically imported module — without rebuilding
5158
+ * the type or re-hydrating the tree.
5159
+ *
5160
+ * The extension is applied inside an action context, so it works on protected trees.
5161
+ * Attached views are computeds (reactive, memoized) and attached actions get a full
5162
+ * MST action context, exactly like members declared in the original chain.
5163
+ *
5164
+ * Note: the attached members are NOT part of the instance's *static* type. If you
5165
+ * need them typed, declare the augmented shape separately (an `import type` of the
5166
+ * chain's return type is erased at build time, so it costs nothing in the bundle).
5167
+ *
5168
+ * @param instance a live model instance
5169
+ * @param fn receives the instance and returns `{ actions?, views?, state? }`
5170
+ * @returns the same instance
5171
+ */
5172
+ function extendInstance(instance, fn) {
5173
+ if (!isStateTreeNode(instance)) {
5174
+ throw fail("extendInstance expects a mobx-state-tree node");
5175
+ }
5176
+ const type = getStateTreeNode(instance).type;
5177
+ if (!isModelType(type)) {
5178
+ throw fail("extendInstance can only be used on model instances");
5179
+ }
5180
+ // Views/actions/volatile are installed via defineProperty + makeObservable — the
5181
+ // same "add" operations the initializers perform at creation, before the
5182
+ // write-protection interceptor is attached (see finalizeNewInstance). On a live
5183
+ // instance that interceptor is already active, so run the attach inside an action
5184
+ // context: isRunningAction() then short-circuits assertWritable.
5185
+ const modelType = type;
5186
+ const attach = createActionInvoker(instance, "@@extendInstance", (() => {
5187
+ modelType.applyExtensionToInstance(instance, fn(instance));
5188
+ }));
5189
+ attach();
5190
+ return instance;
5191
+ }
5041
5192
 
5042
5193
  // TODO: implement CoreType using types.custom ?
5043
5194
  /**
@@ -5466,7 +5617,24 @@ class Union extends BaseType {
5466
5617
  }
5467
5618
  return `${baseWithDiscriminator}:\n ${formatValidationErrorLines(errors).join("\n ")}`;
5468
5619
  }
5620
+ // Memoizes the discriminator -> member scan below. Union membership is fixed
5621
+ // at construction, so the result for a given `type` string never changes.
5622
+ // Without this, validating a config with many elements drawn from a wide
5623
+ // pluggable union (e.g. jbrowse's 30+ track/adapter types) re-scans every
5624
+ // member — and calls resolveModelType + literal.is() on each — once per
5625
+ // element. With it, each distinct discriminator scans once; the rest are
5626
+ // O(1) map hits. `undefined` (no match OR ambiguous) is cached too.
5627
+ _discriminatorCache;
5469
5628
  _findCandidateByTypeDiscriminator(discriminator) {
5629
+ const cache = (this._discriminatorCache ??= new Map());
5630
+ if (cache.has(discriminator)) {
5631
+ return cache.get(discriminator);
5632
+ }
5633
+ const found = this._scanForTypeDiscriminator(discriminator);
5634
+ cache.set(discriminator, found);
5635
+ return found;
5636
+ }
5637
+ _scanForTypeDiscriminator(discriminator) {
5470
5638
  let found;
5471
5639
  for (const t of this._types) {
5472
5640
  const model = resolveModelType(t);
@@ -6987,5 +7155,5 @@ const types = {
6987
7155
  resilient
6988
7156
  };
6989
7157
 
6990
- 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, getUnionSubtypes, 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, protect, recordActions, recordPatches, resolveIdentifier, resolvePath, setDevMode, setLivelinessChecking, setLivelynessChecking, setTypeChecking, splitJsonPath, types as t, toGenerator, toGeneratorFunction, tryReference, tryResolve, typecheck, types, unescapeJsonPath, unprotect, walk };
7158
+ export { addDisposer, addMiddleware, applyAction, applyPatch, applySnapshot, cast, castFlowReturn, castToReferenceSnapshot, castToSnapshot, clone, createActionTrackingMiddleware, createActionTrackingMiddleware2, decorate, destroy, detach, escapeJsonPath, extendInstance, flow, getChildType, getEnv, getIdentifier, getLivelinessChecking, getMembers, getNodeId, getParent, getParentOfType, getPath, getPathParts, getPropertyMembers, getRelativePath, getRoot, getRunningActionContext, getSnapshot, getType, getUnionSubtypes, 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, protect, recordActions, recordPatches, resolveIdentifier, resolvePath, setDevMode, setLivelinessChecking, setLivelynessChecking, setTypeChecking, splitJsonPath, types as t, toGenerator, toGeneratorFunction, tryReference, tryResolve, typecheck, types, unescapeJsonPath, unprotect, walk };
6991
7159
  //# sourceMappingURL=mobx-state-tree.mjs.map