@mmstack/primitives 22.4.1 → 22.5.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.
@@ -1,11 +1,11 @@
1
1
  import * as i0 from '@angular/core';
2
- import { isDevMode, inject, Injector, untracked, effect, DestroyRef, InjectionToken, TemplateRef, ViewContainerRef, PLATFORM_ID, input, computed, Directive, signal, runInInjectionContext, linkedSignal, afterNextRender, Component, isWritableSignal as isWritableSignal$2, isSignal, ElementRef, Injectable } from '@angular/core';
2
+ import { isDevMode, inject, Injector, untracked, effect, DestroyRef, InjectionToken, TemplateRef, ViewContainerRef, PLATFORM_ID, input, computed, Directive, signal, runInInjectionContext, linkedSignal, afterNextRender, PendingTasks, Component, ElementRef, isWritableSignal as isWritableSignal$2, isSignal, Injectable } from '@angular/core';
3
3
  import { isPlatformServer } from '@angular/common';
4
4
  import { SIGNAL } from '@angular/core/primitives/signals';
5
5
 
6
- const frameStack = [];
6
+ const frameStack$1 = [];
7
7
  function currentFrame() {
8
- return frameStack.at(-1) ?? null;
8
+ return frameStack$1.at(-1) ?? null;
9
9
  }
10
10
  function clearFrame(frame, userCleanups) {
11
11
  frame.parent = null;
@@ -31,10 +31,10 @@ function clearFrame(frame, userCleanups) {
31
31
  frame.children.clear();
32
32
  }
33
33
  function pushFrame(frame) {
34
- return frameStack.push(frame);
34
+ return frameStack$1.push(frame);
35
35
  }
36
36
  function popFrame() {
37
- return frameStack.pop();
37
+ return frameStack$1.pop();
38
38
  }
39
39
 
40
40
  /**
@@ -446,6 +446,81 @@ function chunked(source, options) {
446
446
  return internal.asReadonly();
447
447
  }
448
448
 
449
+ /**
450
+ * `useDeferredValue` for signals: returns a signal that HOLDS its previous value when
451
+ * `source` changes and catches up at lower priority (after paint / on idle), so an
452
+ * expensive subtree keyed off the deferred value never blocks the urgent update that
453
+ * caused the change — type into a filter, the input echoes instantly, the big list
454
+ * re-renders a beat later.
455
+ *
456
+ * ```ts
457
+ * const query = signal('');
458
+ * const deferredQuery = deferredValue(query);
459
+ * const results = computed(() => expensiveFilter(items(), deferredQuery()));
460
+ * // template: <input [(ngModel)]="query" /> stays responsive; results lag one paint
461
+ * // deferredQuery.pending() → dim the stale list while it catches up
462
+ * ```
463
+ *
464
+ * Rapid changes coalesce: each change reschedules the catch-up, so only the LATEST
465
+ * source value is ever applied (no intermediate churn in the expensive subtree).
466
+ * On the server this is a synchronous pass-through — SSR renders once, so deferral
467
+ * would just mean rendering stale content.
468
+ *
469
+ * This is a scheduling tool, not an async one — for async work compose `latest()`;
470
+ * for coordinated multi-resource reveals use a transition scope.
471
+ */
472
+ function deferredValue(source, opt) {
473
+ const injector = opt?.injector ?? inject(Injector);
474
+ const equal = opt?.equal ?? Object.is;
475
+ if (injector.get(PLATFORM_ID) === 'server') {
476
+ const passthrough = computed(() => source());
477
+ passthrough.pending = computed(() => false, /* @ts-ignore */
478
+ ...(ngDevMode ? [{ debugName: "pending" }] : /* istanbul ignore next */ []));
479
+ return passthrough;
480
+ }
481
+ const schedule = resolveScheduler(opt?.strategy ?? 'afterRender', injector);
482
+ const out = signal(untracked(source), { ...(ngDevMode ? { debugName: "out" } : /* istanbul ignore next */ {}), equal });
483
+ let cancel = null;
484
+ const watch = effect(() => {
485
+ const v = source();
486
+ cancel?.(); // latest wins: rapid changes coalesce into one catch-up
487
+ cancel = schedule(() => {
488
+ cancel = null;
489
+ out.set(v);
490
+ });
491
+ }, { ...(ngDevMode ? { debugName: "watch" } : /* istanbul ignore next */ {}), injector });
492
+ injector.get(DestroyRef).onDestroy(() => {
493
+ watch.destroy();
494
+ cancel?.();
495
+ cancel = null;
496
+ });
497
+ const result = computed(() => out());
498
+ // "behind" is a value comparison, not a schedule flag: an equal-valued catch-up
499
+ // (e.g. type a char, delete it before the deferred view caught up) is not pending
500
+ result.pending = computed(() => !equal(out(), source()), /* @ts-ignore */
501
+ ...(ngDevMode ? [{ debugName: "pending" }] : /* istanbul ignore next */ []));
502
+ return result;
503
+ }
504
+ function resolveScheduler(strategy, injector) {
505
+ if (typeof strategy === 'function')
506
+ return strategy;
507
+ if (strategy === 'idle') {
508
+ return (cb) => {
509
+ const ric = globalThis.requestIdleCallback;
510
+ if (ric) {
511
+ const id = ric(() => cb());
512
+ return () => globalThis.cancelIdleCallback?.(id);
513
+ }
514
+ const id = setTimeout(cb, 0);
515
+ return () => clearTimeout(id);
516
+ };
517
+ }
518
+ return (cb) => {
519
+ const ref = afterNextRender({ read: cb }, { injector });
520
+ return () => ref.destroy();
521
+ };
522
+ }
523
+
449
524
  /**
450
525
  * Structural hold-and-swap as a signal. Given a `target` (the desired value — e.g. the
451
526
  * subtree/def/key you want to show) and a `ready` predicate, returns a signal that keeps
@@ -545,6 +620,17 @@ function createTransitionScope() {
545
620
  source: () => ({ v: value(), settled: !pending() }),
546
621
  computation: (curr, prev) => curr.settled || prev === undefined ? curr.v : prev.value,
547
622
  }),
623
+ abortPending: () => untracked(() => {
624
+ let aborted = 0;
625
+ for (const { ref } of list()) {
626
+ const s = ref.status();
627
+ if ((s === 'loading' || s === 'reloading') && ref.abort) {
628
+ ref.abort();
629
+ aborted++;
630
+ }
631
+ }
632
+ return aborted;
633
+ }),
548
634
  holding,
549
635
  beginHold: () => untracked(() => holdCount.update((c) => c + 1)),
550
636
  endHold: () => untracked(() => holdCount.update((c) => (c > 0 ? c - 1 : 0))),
@@ -566,6 +652,7 @@ function createNoopScope() {
566
652
  // noop
567
653
  },
568
654
  commit: (value) => value,
655
+ abortPending: () => 0,
569
656
  holding: computed(() => false),
570
657
  beginHold: () => {
571
658
  // noop
@@ -577,9 +664,49 @@ function createNoopScope() {
577
664
  };
578
665
  }
579
666
  const TRANSITION_SCOPE = new InjectionToken('@mmstack/primitives:transition-scope');
667
+ /**
668
+ * The scope→`PendingTasks` bridge: while `scope.pending()` is true, hold an Angular
669
+ * pending task so SSR serialization waits for the scope's in-flight loads — HTTP loads
670
+ * already do this via HttpClient, but CUSTOM loaders (a `latest()` over a hand-rolled
671
+ * promise, a non-HTTP resource) would otherwise let the server render a boundary
672
+ * mid-load. Wired automatically by `provideTransitionScope` /
673
+ * `provideForwardingTransitionScope`; call it yourself only for scopes you construct
674
+ * directly with `createTransitionScope()`.
675
+ *
676
+ * Server-only by design: on the browser, tying `ApplicationRef.isStable` to every load
677
+ * would stall stability-gated machinery (testability, hydration timing) for no benefit.
678
+ */
679
+ function bridgeScopeToPendingTasks(scope, injector) {
680
+ const run = (fn) => injector ? runInInjectionContext(injector, fn) : fn();
681
+ run(() => {
682
+ if (inject(PLATFORM_ID) !== 'server')
683
+ return;
684
+ const tasks = inject(PendingTasks);
685
+ let done = null;
686
+ effect(() => {
687
+ if (scope.pending())
688
+ done ??= tasks.add();
689
+ else {
690
+ done?.();
691
+ done = null;
692
+ }
693
+ });
694
+ inject(DestroyRef).onDestroy(() => {
695
+ done?.();
696
+ done = null;
697
+ });
698
+ });
699
+ }
580
700
  /** Provide a fresh transition scope at a boundary so its subtree's resources are tracked independently. */
581
701
  function provideTransitionScope() {
582
- return { provide: TRANSITION_SCOPE, useFactory: createTransitionScope };
702
+ return {
703
+ provide: TRANSITION_SCOPE,
704
+ useFactory: () => {
705
+ const scope = createTransitionScope();
706
+ bridgeScopeToPendingTasks(scope);
707
+ return scope;
708
+ },
709
+ };
583
710
  }
584
711
  function injectTransitionScope() {
585
712
  const scope = inject(TRANSITION_SCOPE, { optional: true });
@@ -616,6 +743,7 @@ function createForwardingScope() {
616
743
  source: () => ({ v: value(), settled: !eff().pending() }),
617
744
  computation: (curr, prev) => curr.settled || prev === undefined ? curr.v : prev.value,
618
745
  }),
746
+ abortPending: () => (untracked(target) ?? own).abortPending(),
619
747
  holding: computed(() => eff().holding()),
620
748
  beginHold: () => (untracked(target) ?? own).beginHold(),
621
749
  endHold: () => (untracked(target) ?? own).endHold(),
@@ -627,7 +755,14 @@ function createForwardingScope() {
627
755
  }
628
756
  /** Provide a forwarding transition scope at a boundary (used by the transition outlet). */
629
757
  function provideForwardingTransitionScope() {
630
- return { provide: TRANSITION_SCOPE, useFactory: createForwardingScope };
758
+ return {
759
+ provide: TRANSITION_SCOPE,
760
+ useFactory: () => {
761
+ const scope = createForwardingScope();
762
+ bridgeScopeToPendingTasks(scope);
763
+ return scope;
764
+ },
765
+ };
631
766
  }
632
767
  /** Read the transition scope reachable from `injector`, or null if none is provided there. */
633
768
  function getTransitionScope(injector) {
@@ -684,6 +819,138 @@ function registerResource(res, opt) {
684
819
  return injectRegisterResource()(res, opt);
685
820
  }
686
821
 
822
+ const frameStack = [];
823
+ /**
824
+ * Thrown by `use()` to short-circuit a computation whose input has no value yet; caught
825
+ * by the owning `latest()`. Identity-compared, so user code must not swallow it — avoid
826
+ * broad `try/catch` around `use()` calls.
827
+ */
828
+ const BLOCKED = new Error('[mmstack/primitives] latest() blocked — internal sentinel, do not catch');
829
+ /**
830
+ * Reads a resource inside a `latest()` computation: returns its value and reports it to
831
+ * the enclosing collector, so the derivation's aggregate `pending`/`status`/`error`
832
+ * include it. When the resource has no value yet (first load) or is in an error state,
833
+ * the computation short-circuits — code after this call simply doesn't run this round —
834
+ * which is what lets you write the happy path with no `undefined` checks:
835
+ *
836
+ * ```ts
837
+ * const fullName = latest(() => {
838
+ * const u = use(user); // waterfalls compose:
839
+ * const org = use(orgFor(u)); // orgFor(u) is only read once `user` has a value
840
+ * return `${u.name} @ ${org.name}`;
841
+ * });
842
+ * ```
843
+ *
844
+ * Must be called synchronously within `latest()` — like `inject()`, it throws elsewhere.
845
+ */
846
+ function use(res) {
847
+ const frame = frameStack.at(-1);
848
+ if (!frame) {
849
+ throw new Error('[mmstack/primitives] use() must be called synchronously within a latest() computation');
850
+ }
851
+ if (!frame.seen.has(res)) {
852
+ frame.seen.add(res);
853
+ frame.deps.push(res);
854
+ }
855
+ // status() is read tracked even on the short-circuit paths, so the owning computed
856
+ // re-evaluates when the load settles / the error clears.
857
+ if (res.status() === 'error') {
858
+ frame.errors.push(res.error?.());
859
+ throw BLOCKED;
860
+ }
861
+ if (!res.hasValue())
862
+ throw BLOCKED;
863
+ return res.value();
864
+ }
865
+ /**
866
+ * An async derivation over resources: evaluates `fn` inside a collector frame so that
867
+ * every `use()` read registers as a member, and exposes the result with resource
868
+ * semantics — the value holds its previous state while anything it read is in flight
869
+ * (never flashing empty), `pending` aggregates the members' in-flight state, and the
870
+ * whole thing is itself a `UseSource`, so `latest`s nest and propagate.
871
+ *
872
+ * ```ts
873
+ * const fullName = latest(() => `${use(user).name} @ ${use(org).name}`);
874
+ * fullName(); // held value — undefined only before the first successful run
875
+ * fullName.pending(); // true while user OR org (re)loads
876
+ * ```
877
+ *
878
+ * Evaluation is a plain `computed` under the hood: lazy, pure, no effects, usable
879
+ * outside any injection context (`register` is the only DI-touching option).
880
+ */
881
+ function latest(fn, opt) {
882
+ const evaluation = computed(() => {
883
+ const frame = { deps: [], seen: new Set(), errors: [] };
884
+ frameStack.push(frame);
885
+ try {
886
+ const value = fn();
887
+ return { kind: 'value', value, deps: frame.deps, errors: frame.errors };
888
+ }
889
+ catch (e) {
890
+ if (e === BLOCKED)
891
+ return { kind: 'blocked', deps: frame.deps, errors: frame.errors };
892
+ return {
893
+ kind: 'thrown',
894
+ thrown: e,
895
+ deps: frame.deps,
896
+ errors: frame.errors,
897
+ };
898
+ }
899
+ finally {
900
+ frameStack.pop();
901
+ }
902
+ }, opt?.debugName ? { debugName: `${opt.debugName}:evaluation` } : undefined);
903
+ const equal = opt?.equal ?? Object.is;
904
+ // The stale-while-revalidate atom: holds the last successful result through blocked /
905
+ // errored rounds. `equal` gates notification, so an in-flight cycle that lands on an
906
+ // equal value never ripples to consumers — while `pending` (independent) still cycles.
907
+ const held = linkedSignal({ ...(ngDevMode ? { debugName: "held" } : /* istanbul ignore next */ {}), source: evaluation,
908
+ computation: (ev, prev) => ev.kind === 'value'
909
+ ? { has: true, v: ev.value }
910
+ : (prev?.value ?? { has: false, v: undefined }),
911
+ equal: (a, b) => a.has === b.has && (!a.has || equal(a.v, b.v)) });
912
+ const value = computed(() => held().v, opt?.debugName ? { debugName: opt.debugName } : undefined);
913
+ const pending = computed(() => evaluation().deps.some((d) => {
914
+ const s = d.status();
915
+ return s === 'loading' || s === 'reloading';
916
+ }), /* @ts-ignore */
917
+ ...(ngDevMode ? [{ debugName: "pending" }] : /* istanbul ignore next */ []));
918
+ const status = computed(() => {
919
+ const ev = evaluation();
920
+ if (ev.kind === 'thrown' || ev.errors.length > 0)
921
+ return 'error';
922
+ if (pending())
923
+ return held().has ? 'reloading' : 'loading';
924
+ return ev.kind === 'value' ? 'resolved' : 'idle';
925
+ }, /* @ts-ignore */
926
+ ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
927
+ const error = computed(() => {
928
+ const ev = evaluation();
929
+ return ev.kind === 'thrown' ? ev.thrown : ev.errors.at(0);
930
+ }, /* @ts-ignore */
931
+ ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
932
+ const result = Object.assign(value, {
933
+ value,
934
+ status,
935
+ pending,
936
+ isLoading: pending,
937
+ error,
938
+ hasValue: () => held().has,
939
+ });
940
+ if (opt?.register) {
941
+ const register = () => {
942
+ const scope = injectTransitionScope();
943
+ scope.add(result, { suspends: opt.register === 'suspend' });
944
+ inject(DestroyRef).onDestroy(() => scope.remove(result));
945
+ };
946
+ if (opt.injector)
947
+ runInInjectionContext(opt.injector, register);
948
+ else
949
+ register();
950
+ }
951
+ return result;
952
+ }
953
+
687
954
  /**
688
955
  * Returns a `startTransition(fn)` bound to the nearest transition scope. `fn` runs its state
689
956
  * mutations (which commit immediately); any resource that reloads as a result holds its value
@@ -1109,6 +1376,58 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.2", ngImpor
1109
1376
  }]
1110
1377
  }], ctorParameters: () => [], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "mmTransition", required: true }] }], immediate: [{ type: i0.Input, args: [{ isSignal: true, alias: "mmTransitionImmediate", required: false }] }], viewTransition: [{ type: i0.Input, args: [{ isSignal: true, alias: "mmTransitionViewTransition", required: false }] }] } });
1111
1378
 
1379
+ /**
1380
+ * Per-element morphs on held swaps: assigns `view-transition-name` reactively, so when
1381
+ * a swap wrapped in `document.startViewTransition` flips views (`*mmTransition`'s
1382
+ * `mmTransitionViewTransition`, or the transition outlet's view-transition option), the
1383
+ * browser pairs same-named elements across the outgoing and incoming views and MORPHS
1384
+ * them instead of cross-fading the whole boundary.
1385
+ *
1386
+ * ```html
1387
+ * <!-- outgoing view (list) and incoming view (detail) both name the hero image: -->
1388
+ * <img [mmViewTransitionName]="'hero-' + item().id" [src]="item().img" />
1389
+ * ```
1390
+ *
1391
+ * Why this works with holds: both views coexist in the DOM during a hold, but the
1392
+ * incoming one is `display: none` — elements without boxes aren't captured, so the
1393
+ * same name on both sides is legal at each capture point (old visible at snapshot,
1394
+ * new visible after the swap). No arming/cleanup dance needed.
1395
+ *
1396
+ * The name is normalized to a valid CSS custom-ident (invalid characters → `-`, a
1397
+ * leading digit gets a `_` prefix). An empty string / `'none'` clears the name — use
1398
+ * that to opt an element out conditionally. One rule remains YOURS to keep: a name
1399
+ * must be unique among elements VISIBLE at capture time (two rendered instances of the
1400
+ * same named element make the browser skip the whole transition) — derive names from
1401
+ * ids for anything that can repeat.
1402
+ */
1403
+ class MmViewTransitionName {
1404
+ mmViewTransitionName = input.required(/* @ts-ignore */
1405
+ ...(ngDevMode ? [{ debugName: "mmViewTransitionName" }] : /* istanbul ignore next */ []));
1406
+ constructor() {
1407
+ const el = inject(ElementRef).nativeElement;
1408
+ effect(() => {
1409
+ const name = normalizeIdent(this.mmViewTransitionName());
1410
+ if (name)
1411
+ el.style.setProperty('view-transition-name', name);
1412
+ else
1413
+ el.style.removeProperty('view-transition-name');
1414
+ });
1415
+ }
1416
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.2", ngImport: i0, type: MmViewTransitionName, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1417
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.0.2", type: MmViewTransitionName, isStandalone: true, selector: "[mmViewTransitionName]", inputs: { mmViewTransitionName: { classPropertyName: "mmViewTransitionName", publicName: "mmViewTransitionName", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0 });
1418
+ }
1419
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.2", ngImport: i0, type: MmViewTransitionName, decorators: [{
1420
+ type: Directive,
1421
+ args: [{ selector: '[mmViewTransitionName]' }]
1422
+ }], ctorParameters: () => [], propDecorators: { mmViewTransitionName: [{ type: i0.Input, args: [{ isSignal: true, alias: "mmViewTransitionName", required: true }] }] } });
1423
+ /** @internal `''`/`'none'` clear; otherwise coerce into a valid custom-ident. */
1424
+ function normalizeIdent(raw) {
1425
+ if (!raw || raw === 'none')
1426
+ return null;
1427
+ const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, '-');
1428
+ return /^\d/.test(cleaned) ? `_${cleaned}` : cleaned;
1429
+ }
1430
+
1112
1431
  /**
1113
1432
  * @internal
1114
1433
  */
@@ -3977,7 +4296,11 @@ function buildChildNode(target, prop, isMutableSource, options) {
3977
4296
  function toStore(source, { injector, vivify = false, noUnionLeaves = false, ...rest } = {}) {
3978
4297
  if (isStore(source))
3979
4298
  return source;
3980
- if (!injector)
4299
+ // injector is needed ONLY to resolve the two proxy-globals tokens; if a caller supplies the
4300
+ // globals directly (createStoreContext — the worker-side seam with no DI), skip inject entirely
4301
+ const sharedGlobals = rest[STORE_SHARED_GLOBALS];
4302
+ const hasSharedGlobals = !!(sharedGlobals?.cache && sharedGlobals?.registry);
4303
+ if (!injector && !hasSharedGlobals)
3981
4304
  injector = inject(Injector);
3982
4305
  const writableSource = isWritableSignal(source)
3983
4306
  ? source
@@ -3996,13 +4319,18 @@ function toStore(source, { injector, vivify = false, noUnionLeaves = false, ...r
3996
4319
  }, /* @ts-ignore */
3997
4320
  ...(ngDevMode ? [{ debugName: "kind" }] : /* istanbul ignore next */ []));
3998
4321
  const STORE_OPTIONS = {
3999
- injector,
4322
+ // may be undefined in worker/DI-less mode; unused downstream once globals are resolved
4323
+ // (children thread the resolved globals via STORE_SHARED_OPTIONS, derived needs no injector)
4324
+ injector: injector,
4000
4325
  vivify,
4001
4326
  noUnionLeaves,
4002
4327
  [STORE_SHARED_GLOBALS]: {
4003
- cache: rest[STORE_SHARED_GLOBALS]?.cache ?? injector.get(PROXY_CACHE_TOKEN),
4004
- registry: rest[STORE_SHARED_GLOBALS]?.registry ??
4005
- injector.get(PROXY_CLEANUP_TOKEN),
4328
+ // the `injector!` reads run only when a global is absent, which (per hasSharedGlobals) means
4329
+ // an injector was resolved above
4330
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
4331
+ cache: sharedGlobals?.cache ?? injector.get(PROXY_CACHE_TOKEN),
4332
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
4333
+ registry: sharedGlobals?.registry ?? injector.get(PROXY_CLEANUP_TOKEN),
4006
4334
  },
4007
4335
  };
4008
4336
  // built lazily so non-array nodes never allocate it
@@ -4074,7 +4402,14 @@ function toStore(source, { injector, vivify = false, noUnionLeaves = false, ...r
4074
4402
  return () => {
4075
4403
  if (!isWritableSource)
4076
4404
  return s;
4077
- return untracked(() => toStore(source.asReadonly(), { injector, vivify, noUnionLeaves }));
4405
+ return untracked(() => toStore(source.asReadonly(), {
4406
+ injector,
4407
+ vivify,
4408
+ noUnionLeaves,
4409
+ // forward the resolved globals — re-resolving from the injector both re-injects
4410
+ // needlessly and breaks in DI-less (worker) mode where injector is undefined
4411
+ [STORE_SHARED_GLOBALS]: STORE_OPTIONS[STORE_SHARED_GLOBALS],
4412
+ }));
4078
4413
  };
4079
4414
  const k = untracked(kind);
4080
4415
  if (prop === 'extend' && k !== 'array')
@@ -4240,6 +4575,40 @@ function mutableStore(value, opt) {
4240
4575
  ...opt,
4241
4576
  });
4242
4577
  }
4578
+ /**
4579
+ * Builds a DI-less store context — the shared proxy-cache and cleanup registry that {@link toStore}
4580
+ * normally resolves from the injector — so a `store`/`toStore`/`opLog` graph can run with NO Angular
4581
+ * injection context. Spread the result into the options:
4582
+ *
4583
+ * ```ts
4584
+ * import { microtaskOpLogDriver } from '@mmstack/worker/host';
4585
+ * const ctx = createStoreContext();
4586
+ * const s = store({ todos: [] }, ctx);
4587
+ * const log = opLog(s, { driver: microtaskOpLogDriver(), origin: 'worker' }); // no injector anywhere
4588
+ * ```
4589
+ *
4590
+ * **This is a worker-only fallback — do NOT use it on the main thread.** DI is the default and
4591
+ * correct path in an app: the injector scopes the proxy-cache/cleanup singletons per app instance,
4592
+ * which on the SERVER keeps one request's store identity from bleeding into another's (the exact
4593
+ * hazard a module-scope singleton would reintroduce). A Web Worker is safe because it is a single
4594
+ * store graph per thread and never runs during SSR (spawn is a `PLATFORM_ID === 'server'` no-op),
4595
+ * so there is no cross-request scope to contaminate. Never hoist a `createStoreContext()` to module
4596
+ * scope on a shared/main thread.
4597
+ *
4598
+ * **Share ONE context across every store in a worker** — the same way `providedIn: 'root'` shares
4599
+ * one cache across all of an app's stores. `@mmstack/worker/host` memoizes this per worker
4600
+ * (`workerStoreContext()`); reach for `createStoreContext()` directly only in a bare
4601
+ * (non-worker-host) DI-less setup, and hold the single instance yourself.
4602
+ */
4603
+ function createStoreContext() {
4604
+ const cache = new WeakMap();
4605
+ const registry = new FinalizationRegistry(({ target, prop }) => {
4606
+ const entry = cache.get(target);
4607
+ if (entry)
4608
+ entry.delete(prop);
4609
+ });
4610
+ return { [STORE_SHARED_GLOBALS]: { cache, registry } };
4611
+ }
4243
4612
 
4244
4613
  function isPlainRecord(value) {
4245
4614
  if (value === null || typeof value !== 'object')
@@ -4314,6 +4683,323 @@ function forkStore(base, opt) {
4314
4683
  };
4315
4684
  }
4316
4685
 
4686
+ function generateOrigin() {
4687
+ if (globalThis.crypto?.randomUUID)
4688
+ return globalThis.crypto.randomUUID();
4689
+ return Math.random().toString(36).substring(2);
4690
+ }
4691
+ const isPlainArray$1 = (v) => Array.isArray(v) && !isOpaque(v);
4692
+ /**
4693
+ * Reference-identity-pruned structural diff — the same short-circuit discipline as `merge3`:
4694
+ * an untouched subtree kept its reference (the store's copy-on-write contract), so the walk
4695
+ * descends only where refs differ. O(changed paths), not O(tree).
4696
+ */
4697
+ function diffNode(prev, next, path, ops) {
4698
+ if (Object.is(prev, next))
4699
+ return;
4700
+ if (isRecord(prev) && isRecord(next)) {
4701
+ for (const key of Object.keys(prev)) {
4702
+ if (!Object.hasOwn(next, key))
4703
+ ops.push({ kind: 'delete', path: [...path, key], prev: prev[key] });
4704
+ }
4705
+ for (const key of Object.keys(next)) {
4706
+ if (!Object.hasOwn(prev, key)) {
4707
+ // added key: deliberately NO `prev` property (absent ≠ undefined)
4708
+ ops.push({ kind: 'set', path: [...path, key], next: next[key] });
4709
+ }
4710
+ else {
4711
+ diffNode(prev[key], next[key], [...path, key], ops);
4712
+ }
4713
+ }
4714
+ return;
4715
+ }
4716
+ if (isPlainArray$1(prev) && isPlainArray$1(next)) {
4717
+ // same length → per-index descent (matches `arr[i].x.set(...)` writes); a length
4718
+ // change is a whole unit — index attribution lies under insert/remove/reorder
4719
+ if (prev.length === next.length) {
4720
+ for (let i = 0; i < next.length; i++)
4721
+ diffNode(prev[i], next[i], [...path, i], ops);
4722
+ return;
4723
+ }
4724
+ ops.push({ kind: 'set', path, prev, next });
4725
+ return;
4726
+ }
4727
+ // leaf / type change / opaque — one unit, prev present (the slot existed)
4728
+ ops.push({ kind: 'set', path, prev, next });
4729
+ }
4730
+ /** Immutably applies one op along its path, vivifying missing containers `'auto'`-style. */
4731
+ function applyAt(container, path, idx, op) {
4732
+ const seg = path[idx];
4733
+ const base = isPlainArray$1(container)
4734
+ ? container.slice()
4735
+ : isRecord(container)
4736
+ ? { ...container }
4737
+ : typeof seg === 'number'
4738
+ ? []
4739
+ : {};
4740
+ if (idx === path.length - 1) {
4741
+ if (op.kind === 'delete') {
4742
+ // arrays never receive deletes (length changes travel as whole-array sets)
4743
+ delete base[seg];
4744
+ }
4745
+ else {
4746
+ base[seg] = op.next;
4747
+ }
4748
+ return base;
4749
+ }
4750
+ base[seg] = applyAt(base[seg], path, idx + 1, op);
4751
+ return base;
4752
+ }
4753
+ /**
4754
+ * Pure, store-free application of ops onto a plain root value, returning the next immutable root
4755
+ * (structural-sharing along op paths, missing containers vivified `'auto'`-style). This is the
4756
+ * same transform {@link OpLog.apply} runs, extracted so a replica can fold a received batch into
4757
+ * a value WITHOUT owning a diffing {@link opLog} — e.g. the worker-graph read-replica seam.
4758
+ * Accepts a batch or a bare op list.
4759
+ */
4760
+ function applyOps(root, ops) {
4761
+ const list = Array.isArray(ops) ? ops : ops.ops;
4762
+ let next = root;
4763
+ for (const op of list) {
4764
+ if (op.path.length === 0) {
4765
+ if (op.kind === 'set')
4766
+ next = op.next;
4767
+ continue; // a root delete is meaningless — ignore (mirrors OpLog.apply)
4768
+ }
4769
+ next = applyAt(next, op.path, 0, op);
4770
+ }
4771
+ return next;
4772
+ }
4773
+ /**
4774
+ * Pure reference-pruned structural diff of two roots into minimal ops (the emission core of
4775
+ * {@link opLog}, exported so code outside a log can produce a batch — e.g. diffing a scratch
4776
+ * draft against a replica's current value to route a write to its owner). Trusts the
4777
+ * copy-on-write contract: an untouched subtree that kept its reference is skipped.
4778
+ */
4779
+ function diffOps(prev, next) {
4780
+ const ops = [];
4781
+ diffNode(prev, next, [], ops);
4782
+ return ops;
4783
+ }
4784
+ /**
4785
+ * Inverts a batch for undo: reversed order, `set`↔its own inverse (an add — a `set` with no
4786
+ * `prev` — inverts to a `delete`; a `delete` inverts to a `set` restoring `prev`). Feed the
4787
+ * result to {@link OpLog.apply}. Requires the ops' `prev`s, which in-memory batches always
4788
+ * carry — a wire-serialized batch that stripped them is not invertible.
4789
+ */
4790
+ function invertBatch(batch) {
4791
+ const ops = Array.isArray(batch) ? batch : batch.ops;
4792
+ const inverted = [];
4793
+ for (let i = ops.length - 1; i >= 0; i--) {
4794
+ const op = ops[i];
4795
+ if (op.kind === 'delete') {
4796
+ inverted.push({
4797
+ kind: 'set',
4798
+ path: op.path,
4799
+ next: op.prev,
4800
+ prev: undefined,
4801
+ });
4802
+ continue;
4803
+ }
4804
+ if (!Object.hasOwn(op, 'prev')) {
4805
+ inverted.push({ kind: 'delete', path: op.path, prev: op.next });
4806
+ }
4807
+ else {
4808
+ inverted.push({
4809
+ kind: 'set',
4810
+ path: op.path,
4811
+ next: op.prev,
4812
+ prev: op.next,
4813
+ });
4814
+ }
4815
+ }
4816
+ return inverted;
4817
+ }
4818
+ /**
4819
+ * Observes a copy-on-write signal (a `store`'s root, or any `WritableSignal` holding
4820
+ * immutably-updated objects) and emits its changes as minimal structural op batches — the
4821
+ * shared substrate for sync (ship batches, `apply` remote ones), persistence (journal
4822
+ * batches, replay on boot), undo ({@link invertBatch}), and devtools (`latest`).
4823
+ *
4824
+ * Zero store-core involvement and zero cost when unused: emission is a reference-pruned diff
4825
+ * of the root value per tick (structural sharing makes it O(changed paths)), driven by one
4826
+ * effect. A batch therefore coalesces everything written in one tick — for coarser,
4827
+ * intentional units, stage writes on a `forkStore` and `commit()` (one set → one batch).
4828
+ *
4829
+ * NOT supported on mutable stores/signals: in-place mutation keeps reference identity, which
4830
+ * defeats the diff (same reason `forkStore`'s `'fine'` strategy refuses them) — a dev-mode
4831
+ * warning fires and nothing emits.
4832
+ *
4833
+ * ```ts
4834
+ * const s = store({ todos: [{ done: false }] });
4835
+ * const log = opLog(s, { origin: 'tab-a' });
4836
+ * log.subscribe((b) => channel.postMessage(encode(b))); // ship
4837
+ * channel.onmessage = (m) => log.apply(decode(m.data)); // apply — echo-free
4838
+ * s.todos[0].done.set(true); // → { kind: 'set', path: ['todos', 0, 'done'], … }
4839
+ * ```
4840
+ */
4841
+ function opLog(source, opt) {
4842
+ const origin = opt?.origin ?? generateOrigin();
4843
+ // a store proxy's `has` trap answers for the VALUE's keys, so `isMutable`'s `'mutate' in`
4844
+ // probe can't see the brand — ask the store's own kind symbol first
4845
+ const storeKind = source[STORE_KIND];
4846
+ const mutableSource = storeKind ? storeKind === 'mutable' : isMutable(source);
4847
+ if (isDevMode() && mutableSource) {
4848
+ console.warn('[@mmstack/primitives] opLog observes copy-on-write updates via reference identity — a MUTABLE store/signal mutates in place, so changes are invisible to it. Use an immutable store, or set whole values.');
4849
+ }
4850
+ let prevRoot = untracked(source);
4851
+ let version = 0;
4852
+ let destroyed = false;
4853
+ const subscribers = new Set();
4854
+ const latest = signal(null, /* @ts-ignore */
4855
+ ...(ngDevMode ? [{ debugName: "latest" }] : /* istanbul ignore next */ []));
4856
+ /** Diff now, emit if there's a delta, advance the baseline. */
4857
+ const flush = () => {
4858
+ if (destroyed)
4859
+ return;
4860
+ const next = untracked(source);
4861
+ if (Object.is(prevRoot, next))
4862
+ return;
4863
+ const ops = [];
4864
+ diffNode(prevRoot, next, [], ops);
4865
+ prevRoot = next;
4866
+ if (!ops.length)
4867
+ return; // fresh refs, equal values — spurious-write tolerance
4868
+ const batch = { origin, version: ++version, ops };
4869
+ latest.set(batch);
4870
+ for (const cb of [...subscribers])
4871
+ cb(batch);
4872
+ };
4873
+ const run = () => {
4874
+ source(); // track every commit…
4875
+ untracked(flush); // …and emit the delta since the last flush
4876
+ };
4877
+ // default driver is an Angular effect (needs an injector); a supplied driver runs injector-free
4878
+ // (the worker-side seam, e.g. microtaskOpLogDriver from @mmstack/worker/host)
4879
+ const ref = opt?.driver
4880
+ ? opt.driver(run)
4881
+ : effect(run, { injector: opt?.injector ?? inject(Injector) });
4882
+ return {
4883
+ latest: latest.asReadonly(),
4884
+ subscribe: (cb) => {
4885
+ subscribers.add(cb);
4886
+ return () => subscribers.delete(cb);
4887
+ },
4888
+ // the emission core, callable on demand — reads the source untracked, so it never disturbs the
4889
+ // driver's subscription; a subsequent scheduled run just finds the baseline already advanced
4890
+ flush: () => flush(),
4891
+ apply: (batchOrOps) => {
4892
+ const ops = Array.isArray(batchOrOps)
4893
+ ? batchOrOps
4894
+ : batchOrOps.ops;
4895
+ if (!ops.length)
4896
+ return;
4897
+ // pending local writes must emit BEFORE the baseline advances past them
4898
+ flush();
4899
+ const root = applyOps(untracked(source), ops); // one atomic root, structural-shared
4900
+ source.set(root);
4901
+ prevRoot = root; // baseline advance: an applied batch never echoes
4902
+ },
4903
+ destroy: () => {
4904
+ destroyed = true;
4905
+ subscribers.clear();
4906
+ ref.destroy();
4907
+ },
4908
+ };
4909
+ }
4910
+
4911
+ const isPlainArray = (v) => Array.isArray(v) && !isOpaque(v);
4912
+ function keyOf(item, key) {
4913
+ if (typeof key === 'function')
4914
+ return key(item);
4915
+ return isRecord(item) ? item[key] : item;
4916
+ }
4917
+ /**
4918
+ * Produces a value equal to `next` but sharing as much of `prev`'s reference structure as possible:
4919
+ * an object subtree that did not change keeps its `prev` reference, and array items are matched by
4920
+ * `key` so a surviving item keeps its identity across a reorder/insert/remove (only added items are
4921
+ * new, only removed items are dropped). This is what lets a derived store recompute without tearing
4922
+ * down every downstream `computed` that reads an unchanged part of it.
4923
+ */
4924
+ function reconcile(prev, next, key = 'id') {
4925
+ return reconcileValue(prev, next, key);
4926
+ }
4927
+ function reconcileValue(prev, next, key) {
4928
+ if (Object.is(prev, next))
4929
+ return prev;
4930
+ if (isPlainArray(prev) && isPlainArray(next)) {
4931
+ const byKey = new Map();
4932
+ for (const item of prev)
4933
+ byKey.set(keyOf(item, key), item);
4934
+ let changed = prev.length !== next.length;
4935
+ const out = next.map((item, i) => {
4936
+ const match = byKey.get(keyOf(item, key));
4937
+ const rv = match !== undefined ? reconcileValue(match, item, key) : item;
4938
+ if (rv !== prev[i])
4939
+ changed = true;
4940
+ return rv;
4941
+ });
4942
+ return changed ? out : prev;
4943
+ }
4944
+ if (isRecord(prev) && isRecord(next)) {
4945
+ const nextKeys = Object.keys(next);
4946
+ let changed = Object.keys(prev).length !== nextKeys.length;
4947
+ const out = {};
4948
+ for (const k of nextKeys) {
4949
+ const rv = Object.hasOwn(prev, k)
4950
+ ? reconcileValue(prev[k], next[k], key)
4951
+ : next[k];
4952
+ out[k] = rv;
4953
+ if (rv !== prev[k])
4954
+ changed = true;
4955
+ }
4956
+ return changed ? out : prev;
4957
+ }
4958
+ return next;
4959
+ }
4960
+ /**
4961
+ * A derived STORE, the store-shaped counterpart to `computed`. `fn` receives a mutable draft seeded
4962
+ * with the current value and either mutates it in place or returns a new value; whichever it does,
4963
+ * the result is reconciled against the previous value (see {@link reconcile}) so unchanged subtrees
4964
+ * keep reference identity and keyed array items keep their proxy identity. Reading through the
4965
+ * returned store is fine-grained: a `computed` over one field only recomputes when that field
4966
+ * actually changes, even though the whole projection re-ran.
4967
+ *
4968
+ * Recompute is pull-based, exactly like `computed`: the projection is memoized and re-runs on the
4969
+ * first read after a signal `fn` depends on changes, so reads are always coherent (no waiting on an
4970
+ * effect flush) and nothing recomputes while nobody reads. `fn` must be pure, it runs inside the
4971
+ * reactive computation. Prefer `computed` for a plain value; reach for `projection` when you want
4972
+ * the per-property tracking of a store on top of a derivation.
4973
+ *
4974
+ * ```ts
4975
+ * const active = projection<User[]>(() => users().filter((u) => u.active), [], { key: 'id' });
4976
+ * // active[0].name(); — surviving users keep identity across recomputes
4977
+ * ```
4978
+ *
4979
+ * Needs an injection context (or an explicit `injector`) for the store layer's cleanup on the main
4980
+ * thread; with an explicit store context (`createStoreContext()`) it is injector-free, so it also
4981
+ * runs on a worker host.
4982
+ *
4983
+ * @param fn receives the current draft; mutate it, or return new data.
4984
+ * @param seed the initial value, held before the first run.
4985
+ */
4986
+ function projection(fn, seed, opt) {
4987
+ const { key = 'id', ...storeOpt } = opt ?? {};
4988
+ // linkedSignal rather than an effect-driven signal: the computation runs in the tracked
4989
+ // context (fn's reads are dependencies) and `previous` hands back the last emitted value for
4990
+ // the reconcile, so the projection is glitch-free, lazy, and needs no effect scheduler.
4991
+ const root = linkedSignal({ ...(ngDevMode ? { debugName: "root" } : /* istanbul ignore next */ {}), source: () => undefined,
4992
+ computation: (_, previous) => {
4993
+ const base = previous ? previous.value : seed;
4994
+ // a plain mutable scratch seeded with the current value; fn mutates it or returns new data
4995
+ const draft = structuredClone(base);
4996
+ const returned = fn(draft);
4997
+ const next = (returned === undefined ? draft : returned);
4998
+ return reconcile(base, next, key);
4999
+ } });
5000
+ return toStore(root, storeOpt).asReadonlyStore();
5001
+ }
5002
+
4317
5003
  /**
4318
5004
  * @internal The plain-`effect` sibling of the public {@link pausableEffect} (which is built on
4319
5005
  * `nestedEffect`). For infra utilities that own a single top-level effect/subscription and don't
@@ -4842,5 +5528,5 @@ function withHistory(sourceOrValue, opt) {
4842
5528
  * Generated bundle index. Do not edit.
4843
5529
  */
4844
5530
 
4845
- export { MmActivity, MmTransition, PAUSABLE_OPTIONS, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, batteryStatus, chunked, clipboard, combineWith, createAttributedPending, createForwardingScope, createTransaction, createTransitionScope, debounce, debounced, derived, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, isDerivation, isLeaf, isMutable, isOpaque, isStore, keepPrevious, keyArray, map, mapArray, mapObject, mediaQuery, merge3, mousePosition, mutable, mutableStore, nestedEffect, networkStatus, opaque, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, pipeable, piped, pointerDrag, pooled, pooledArray, pooledMap, pooledSet, prefersDarkMode, prefersReducedMotion, provideForwardingTransitionScope, providePausableOptions, providePaused, provideTransitionScope, registerResource, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, stored, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, windowSize, withHistory };
5531
+ export { MmActivity, MmTransition, MmViewTransitionName, PAUSABLE_OPTIONS, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, applyOps, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, createAttributedPending, createForwardingScope, createStoreContext, createTransaction, createTransitionScope, debounce, debounced, deferredValue, derived, diffOps, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, invertBatch, isDerivation, isLeaf, isMutable, isOpaque, isStore, keepPrevious, keyArray, latest, map, mapArray, mapObject, mediaQuery, merge3, mousePosition, mutable, mutableStore, nestedEffect, networkStatus, opLog, opaque, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, pipeable, piped, pointerDrag, pooled, pooledArray, pooledMap, pooledSet, prefersDarkMode, prefersReducedMotion, projection, provideForwardingTransitionScope, providePausableOptions, providePaused, provideTransitionScope, reconcile, registerResource, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, stored, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, use, windowSize, withHistory };
4846
5532
  //# sourceMappingURL=mmstack-primitives.mjs.map