@mmstack/primitives 20.13.4 → 20.14.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.
@@ -4649,8 +4649,11 @@ function toStore(source, { injector, vivify = false, noUnionLeaves = false, ...r
4649
4649
  return idx >= 0 && idx < v.length;
4650
4650
  }
4651
4651
  }
4652
- // nullish node values are routinely descended with vivify on `in` must not throw
4653
- return v == null ? false : Reflect.has(v, prop);
4652
+ // nullish/primitive node values are routinely descended with vivify on or probed
4653
+ // with `in` (e.g. isMutable) `in` must not throw
4654
+ return v == null || (typeof v !== 'object' && typeof v !== 'function')
4655
+ ? false
4656
+ : Reflect.has(v, prop);
4654
4657
  },
4655
4658
  ownKeys() {
4656
4659
  const v = untracked(source);
@@ -6872,6 +6875,9 @@ function stored(fallback, { key, store: providedStore, serialize = JSON.stringif
6872
6875
  writable.key = keySig;
6873
6876
  return writable;
6874
6877
  }
6878
+ function isStored(value) {
6879
+ return 'clear' in value && typeof value.clear === 'function' && 'key' in value;
6880
+ }
6875
6881
 
6876
6882
  /** Op-mode sync for a writable store: hello exchange, then live envelopes. */
6877
6883
  function storeTabSync(sig, opt, bus, injector) {
@@ -7109,6 +7115,122 @@ function tabSync(sig, opt) {
7109
7115
  return sig;
7110
7116
  }
7111
7117
 
7118
+ /**
7119
+ * Wraps any member of the writable-signal family so that every synchronous write
7120
+ * first records an ambient "cause" (via the caller-provided `capture` function)
7121
+ * and then delegates to the original write, preserving the wrapped signal's exact
7122
+ * write semantics. The recorded cause is exposed through a plain {@link Traced.causedBy}
7123
+ * read, letting a downstream consumer attribute a change to whatever caused it —
7124
+ * without any dependency on a particular telemetry system.
7125
+ *
7126
+ * Capture is **synchronous-only** and last-writer-wins: the cause is whatever
7127
+ * `capture()` returns during the `set`/`update`/`mutate`/`inline` call. A write
7128
+ * performed after an `await` (once the ambient cause has been cleared) records
7129
+ * `undefined`; a write while `capture()` returns `undefined` clears the cause.
7130
+ * `causedBy()` is a plain read, not a signal — reading it never subscribes, and
7131
+ * a cause-only change (a write with a different cause but no dependent-visible
7132
+ * value change) never invalidates a consumer.
7133
+ *
7134
+ * The traced twin behaves like the original except for `causedBy`: it carries the
7135
+ * wrapped signal's surface — `asReadonly`, the `mutate`/`inline` methods of a
7136
+ * mutable, and the `from` of a derived — and the underlying write semantics survive
7137
+ * (a traced `derived` still writes through to its source; a traced `toWritable` still
7138
+ * runs its custom `set`). Reads through the twin stay tracked — consumers subscribe
7139
+ * exactly as they would to the source.
7140
+ *
7141
+ * @typeParam S - The wrapped writable-signal type.
7142
+ * @typeParam C - The type of the captured cause.
7143
+ *
7144
+ * @param sig - The writable signal to trace. Any family member is accepted
7145
+ * (`signal`, `mutable`, `derived`, `toWritable`, `stored`, ...).
7146
+ * @param capture - A function invoked synchronously at the start of every write.
7147
+ * Its return value becomes the current cause; returning `undefined`
7148
+ * clears it.
7149
+ * @param opt - Optional configuration.
7150
+ * @param opt.pure - If `true` (the default), the returned twin is a **new** signal
7151
+ * that reads through to `sig`; `sig` itself is left untouched, so
7152
+ * tracing a shared signal never makes the original writable or
7153
+ * alters its behaviour.
7154
+ *
7155
+ * CAUTION: with `pure: false` the write methods are patched
7156
+ * directly onto the `sig` object you passed in — every other
7157
+ * holder of that signal now records causes on write. Only use it
7158
+ * with a signal you created and own exclusively.
7159
+ *
7160
+ * @returns A {@link Traced} twin of `sig` exposing `causedBy()`.
7161
+ *
7162
+ * @example
7163
+ * // A refetch attributing itself to whatever wrote the query.
7164
+ * let activeCause: string | undefined;
7165
+ * const query = traced(signal(''), () => activeCause);
7166
+ *
7167
+ * activeCause = 'user-typed';
7168
+ * query.set('hello');
7169
+ * query.causedBy(); // 'user-typed'
7170
+ *
7171
+ * @example
7172
+ * // Tracing a shared, read-only-exposed signal without making it writable.
7173
+ * const shared = signal(0);
7174
+ * const twin = traced(shared, () => currentInteraction());
7175
+ * twin === shared; // false — the original is untouched
7176
+ */
7177
+ function traced(sig, capture, opt) {
7178
+ const twin = (opt?.pure === false ? sig : facadeOf(sig));
7179
+ let cause;
7180
+ const setOriginal = sig.set.bind(sig);
7181
+ twin.set = (value) => {
7182
+ cause = capture();
7183
+ setOriginal(value);
7184
+ };
7185
+ const updateOriginal = sig.update.bind(sig);
7186
+ twin.update = (updater) => {
7187
+ cause = capture();
7188
+ updateOriginal(updater);
7189
+ };
7190
+ if (isMutable(sig)) {
7191
+ const source = sig;
7192
+ const mutableTwin = twin;
7193
+ const mutateOriginal = source.mutate.bind(source);
7194
+ mutableTwin.mutate = (updater) => {
7195
+ cause = capture();
7196
+ mutateOriginal(updater);
7197
+ };
7198
+ const inlineOriginal = source.inline.bind(source);
7199
+ mutableTwin.inline = (updater) => {
7200
+ cause = capture();
7201
+ inlineOriginal(updater);
7202
+ };
7203
+ }
7204
+ if (isStored(sig)) {
7205
+ const source = sig;
7206
+ const storedTwin = twin;
7207
+ const clearOriginal = source.clear.bind(source);
7208
+ storedTwin.clear = () => {
7209
+ cause = capture();
7210
+ clearOriginal();
7211
+ };
7212
+ }
7213
+ twin.causedBy = () => cause;
7214
+ return twin;
7215
+ }
7216
+ /**
7217
+ * Builds a read-through facade over `sig`: a fresh signal whose reads track `sig`,
7218
+ * carrying `sig`'s non-write surface (`asReadonly`, and `from` on a derived signal)
7219
+ * by explicit delegation. The write methods are attached by {@link traced}. The
7220
+ * facade's `equal` always reports "changed", so it forwards every notification `sig`
7221
+ * emits — including the same-reference `mutate`/`inline` force-notifies that a default
7222
+ * `computed` would swallow (see `mutable`'s docs). The change decision is thereby
7223
+ * delegated entirely to `sig`.
7224
+ */
7225
+ function facadeOf(sig) {
7226
+ const facade = computed(sig, { equal: () => false });
7227
+ facade.asReadonly = sig.asReadonly.bind(sig);
7228
+ if (isDerivation(sig)) {
7229
+ facade.from = sig.from;
7230
+ }
7231
+ return facade;
7232
+ }
7233
+
7112
7234
  function until(sourceSignal, predicate, options = {}) {
7113
7235
  return new Promise((resolve, reject) => {
7114
7236
  let effectRef;
@@ -7306,5 +7428,5 @@ function withHistory(sourceOrValue, opt) {
7306
7428
  * Generated bundle index. Do not edit.
7307
7429
  */
7308
7430
 
7309
- export { CONCURRENCY_INSTRUMENTATION, MmActivity, MmTransition, MmViewTransitionName, OP_PROTO_VERSION, PAUSABLE_OPTIONS, PERSISTED_STORE_OPTIONS, POS_SEGMENT, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, applyOps, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, compareHlc, compareSiblings, compareTotal, createAttributedPending, createConvergingApply, createForwardingScope, createHlcClock, createStoreContext, createTransaction, createTransitionScope, debounce, debounced, defaultFold, deferredValue, derived, diffOps, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, insertElement, invertBatch, isConflicted, isDerivation, isLeaf, isMutable, isOpaque, isStore, keepPrevious, keyArray, keyedArray, latest, lww, map, mapArray, mapObject, mediaQuery, merge3, mergeThree, mousePosition, moveElement, mutable, mutableStore, nestedEffect, networkStatus, opLog, opSync, opaque, orderedEntries, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, perfCustomTracks, persist, persistedStore, pipeable, piped, pointerDrag, policyStrategy, pooled, pooledArray, pooledMap, pooledSet, posBetween, prefersDarkMode, prefersReducedMotion, preserve, projection, provideConcurrencyInstrumentation, provideForwardingTransitionScope, providePausableOptions, providePaused, providePersistedStoreOptions, provideTransitionScope, rebalanceContainer, rebaseOps, reconcile, registerResource, removeElement, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, storeHistory, stored, syncedFork, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, use, validateEnvelope, windowSize, withHistory };
7431
+ export { CONCURRENCY_INSTRUMENTATION, MmActivity, MmTransition, MmViewTransitionName, OP_PROTO_VERSION, PAUSABLE_OPTIONS, PERSISTED_STORE_OPTIONS, POS_SEGMENT, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, applyOps, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, compareHlc, compareSiblings, compareTotal, createAttributedPending, createConvergingApply, createForwardingScope, createHlcClock, createStoreContext, createTransaction, createTransitionScope, debounce, debounced, defaultFold, deferredValue, derived, diffOps, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, insertElement, invertBatch, isConflicted, isDerivation, isLeaf, isMutable, isOpaque, isStore, isStored, keepPrevious, keyArray, keyedArray, latest, lww, map, mapArray, mapObject, mediaQuery, merge3, mergeThree, mousePosition, moveElement, mutable, mutableStore, nestedEffect, networkStatus, opLog, opSync, opaque, orderedEntries, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, perfCustomTracks, persist, persistedStore, pipeable, piped, pointerDrag, policyStrategy, pooled, pooledArray, pooledMap, pooledSet, posBetween, prefersDarkMode, prefersReducedMotion, preserve, projection, provideConcurrencyInstrumentation, provideForwardingTransitionScope, providePausableOptions, providePaused, providePersistedStoreOptions, provideTransitionScope, rebalanceContainer, rebaseOps, reconcile, registerResource, removeElement, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, storeHistory, stored, syncedFork, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, traced, until, use, validateEnvelope, windowSize, withHistory };
7310
7432
  //# sourceMappingURL=mmstack-primitives.mjs.map