@directive-run/react 0.5.0 → 0.8.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.
- package/README.md +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -10
- package/dist/index.d.ts +11 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -104,7 +104,7 @@ function Summary() {
|
|
|
104
104
|
| `useExplain(system, reqId)` | `string \| null` | Human-readable requirement explanation |
|
|
105
105
|
| `useConstraintStatus(system)` | `ConstraintInfo[]` | All constraint states |
|
|
106
106
|
| `useOptimisticUpdate(system)` | `{ mutate, isPending, error, rollback }` | Optimistic mutation with auto-rollback |
|
|
107
|
-
| `
|
|
107
|
+
| `useHistory(system)` | `HistoryState \| null` | Undo/redo navigation |
|
|
108
108
|
|
|
109
109
|
### React-Specific
|
|
110
110
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils'),react=require('react'),jsxRuntime=require('react/jsx-runtime');var h=Symbol("directive.uninitialized");function Re(e,t){return adapterUtils.assertSystem("useFact",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useFact() received a function. Did you mean useSelector()? useFact() takes a string key or array of keys, not a selector function."),Array.isArray(t)?ne(e,t):te(e,t)}function te(e,t){process.env.NODE_ENV!=="production"&&(t in e.facts.$store.toObject()||console.warn(`[Directive] useFact("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`));let r=react.useCallback(n=>e.facts.$store.subscribe([t],n),[e,t]),u=react.useCallback(()=>e.facts[t],[e,t]);return react.useSyncExternalStore(r,u,u)}function ne(e,t){let r=react.useRef(h),u=react.useCallback(o=>e.facts.$store.subscribe(t,o),[e,...t]),n=react.useCallback(()=>{let o={};for(let s of t)o[s]=e.facts[s];if(r.current!==h){let s=true;for(let i of t)if(!Object.is(r.current[i],o[i])){s=false;break}if(s)return r.current}return r.current=o,o},[e,...t]);return react.useSyncExternalStore(u,n,n)}function be(e,t){return adapterUtils.assertSystem("useDerived",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useDerived() received a function. Did you mean useSelector()? useDerived() takes a string key or array of keys, not a selector function."),Array.isArray(t)?se(e,t):re(e,t)}function re(e,t){process.env.NODE_ENV!=="production"&&(t in e.derive||console.warn(`[Directive] useDerived("${t}") \u2014 derivation not found. Check that "${t}" is defined in your module's derive property.`));let r=react.useCallback(n=>e.subscribe([t],n),[e,t]),u=react.useCallback(()=>e.read(t),[e,t]);return react.useSyncExternalStore(r,u,u)}function se(e,t){let r=react.useRef(h),u=react.useCallback(o=>e.subscribe(t,o),[e,...t]),n=react.useCallback(()=>{let o={};for(let s of t)o[s]=e.read(s);if(r.current!==h){let s=true;for(let i of t)if(!Object.is(r.current[i],o[i])){s=false;break}if(s)return r.current}return r.current=o,o},[e,...t]);return react.useSyncExternalStore(u,n,n)}function he(e,t,r,u){if(e&&e._mode==="namespaced")return ue(e,t,r,u);let n=e,o,s=false,i=u??adapterUtils.defaultEquality;r!==void 0&&(o=r,s=true),process.env.NODE_ENV!=="production"&&!n&&!s&&console.error("[Directive] useSelector() received a null/undefined system without a default value. Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)");let f=react.useRef(t),d=react.useRef(i),c=react.useRef(o);f.current=t,d.current=i,c.current=o;let g=react.useRef([]),v=react.useRef([]),M=react.useRef(h),y=react.useRef([]),x=react.useMemo(()=>n?new Set(Object.keys(n.derive)):new Set,[n]),R=react.useCallback(()=>n?adapterUtils.runTrackedSelector(n,x,f.current):{value:c.current,factKeys:[],deriveKeys:[]},[n,x]),F=react.useCallback(m=>{if(!n)return ()=>{};let k=()=>{for(let S of y.current)S();y.current=[];let{factKeys:I,deriveKeys:p}=R();g.current=I,v.current=p,I.length>0?y.current.push(n.facts.$store.subscribe(I,()=>{let S=R();adapterUtils.depsChanged(g.current,S.factKeys,v.current,S.deriveKeys)&&k(),m();})):p.length===0&&y.current.push(n.facts.$store.subscribeAll(m)),p.length>0&&y.current.push(n.subscribe(p,()=>{let S=R();adapterUtils.depsChanged(g.current,S.factKeys,v.current,S.deriveKeys)&&k(),m();}));};return k(),()=>{for(let I of y.current)I();y.current=[];}},[n,R]),N=react.useCallback(()=>{let m;if(!n)m=c.current;else {let{value:k}=R();m=k===void 0&&s?c.current:k;}return M.current!==h&&d.current(M.current,m)?M.current:(M.current=m,m)},[R,n,s]);return react.useSyncExternalStore(F,N,N)}function ue(e,t,r,u){let n=r!==void 0,o=u??adapterUtils.defaultEquality,s=react.useRef(t),i=react.useRef(o),f=react.useRef(r);s.current=t,i.current=o,f.current=r;let d=react.useRef(h),c=react.useMemo(()=>Object.keys(e.facts),[e]),g=react.useCallback(M=>{let y=c.map(x=>`${x}.*`);return e.subscribe(y,M)},[e,c]),v=react.useCallback(()=>{let M=s.current(e),y=M===void 0&&n?f.current:M;return d.current!==h&&i.current(d.current,y)?d.current:(d.current=y,y)},[e,n]);return react.useSyncExternalStore(g,v,v)}function Me(e){return adapterUtils.assertSystem("useDispatch",e),react.useCallback(t=>{e.dispatch(t);},[e])}function De(e,t,r){adapterUtils.assertSystem("useWatch",e);let u=react.useRef(r);u.current=r,react.useEffect(()=>e.watch(t,(n,o)=>{u.current(n,o);}),[e,t]);}function oe(e,t){adapterUtils.assertSystem("useInspect",e);let r=ce(e),u=t?.throttleMs,[n,o]=react.useState(r),s=react.useRef(null);return react.useEffect(()=>{if(!u||u<=0){s.current?.cleanup(),s.current=null;return}return s.current?.cleanup(),s.current=adapterUtils.createThrottle((...i)=>{o(i[0]);},u),()=>{s.current?.cleanup(),s.current=null;}},[u]),react.useEffect(()=>{s.current&&s.current.throttled(r);},[r]),!u||u<=0?r:n}function ie(e){return adapterUtils.computeInspectState(e)}function ce(e){let t=react.useRef(null),r=react.useRef([]),u=react.useRef([]),n=react.useRef(null),o=react.useCallback(i=>{let f=e.facts.$store.subscribeAll(i),d=e.onSettledChange(i);return ()=>{f(),d();}},[e]),s=react.useCallback(()=>{let i=ie(e),f=i.unmet.length===r.current.length&&i.unmet.every((g,v)=>g.id===r.current[v]),d=i.inflight.length===u.current.length&&i.inflight.every((g,v)=>g.id===u.current[v]),c=i.isSettled===n.current;return f&&d&&c&&t.current?t.current:(t.current=i,r.current=i.unmet.map(g=>g.id),u.current=i.inflight.map(g=>g.id),n.current=i.isSettled,i)},[e]);return react.useSyncExternalStore(o,s,s)}function xe(e){adapterUtils.assertSystem("useTimeTravel",e);let t=react.useRef(null),r=react.useCallback(n=>e.onTimeTravelChange(n),[e]),u=react.useCallback(()=>{let n=adapterUtils.buildTimeTravelState(e);return n?(t.current&&t.current.canUndo===n.canUndo&&t.current.canRedo===n.canRedo&&t.current.currentIndex===n.currentIndex&&t.current.totalSnapshots===n.totalSnapshots&&t.current.isPaused===n.isPaused||(t.current=n),t.current):null},[e]);return react.useSyncExternalStore(r,u,u)}function ke(e,t){return Array.isArray(t)?le(e,t):ae(e,t)}function ae(e,t){let r=react.useRef(h),u=react.useCallback(o=>e.subscribe(o),[e]),n=react.useCallback(()=>{let o=e.getStatus(t);if(r.current!==h){let s=r.current;if(s.pending===o.pending&&s.inflight===o.inflight&&s.failed===o.failed&&s.isLoading===o.isLoading&&s.hasError===o.hasError&&s.lastError===o.lastError)return r.current}return r.current=o,o},[e,t]);return react.useSyncExternalStore(u,n,n)}function le(e,t){let r=react.useRef(null),u=react.useRef(""),n=react.useCallback(s=>e.subscribe(s),[e]),o=react.useCallback(()=>{let s={},i=[];for(let d of t){let c=e.getStatus(d);s[d]=c,i.push(`${d}:${c.pending}:${c.inflight}:${c.failed}:${c.hasError}:${c.lastError?.message??""}`);}let f=i.join("|");return f!==u.current&&(u.current=f,r.current=s),r.current??s},[e,...t]);return react.useSyncExternalStore(n,o,o)}var _=new WeakMap;function j(e){let t=_.get(e);return t||(t=new Map,_.set(e,t)),t}function Ie(e,t){return Array.isArray(t)?fe(e,t):de(e,t)}function de(e,t){let r=e.getStatus(t);if(r.hasError&&r.lastError)throw r.lastError;if(r.isLoading){let u=j(e),n=u.get(t);throw n||(n=new Promise(o=>{let s=e.subscribe(()=>{e.getStatus(t).isLoading||(u.delete(t),s(),o());});}),u.set(t,n)),n}return r}function fe(e,t){let r={},u=false,n=null;for(let o of t){let s=e.getStatus(o);r[o]=s,s.hasError&&s.lastError&&!n&&(n=s.lastError),s.isLoading&&(u=true);}if(n)throw n;if(u){let o=j(e),s=t.slice().sort().join(","),i=o.get(s);throw i||(i=new Promise(f=>{let d=e.subscribe(()=>{t.every(g=>!e.getStatus(g).isLoading)&&(o.delete(s),d(),f());});}),o.set(s,i)),i}return r}function V(e,t){let r=react.useRef(null),u=react.useRef(null),n=react.useRef(null),o=t?.status===true,s="modules"in e;return r.current||(n.current=()=>{if(s){let{modules:N,...m}=e,k=t?.plugins??m.plugins??[],I=t?.debug??m.debug,p=t?.errorBoundary??m.errorBoundary,S=t?.tickMs??m.tickMs,E=t?.zeroConfig??m.zeroConfig,q=t?.initialFacts??m.initialFacts,w=core.createSystem({modules:N,plugins:k.length>0?k:void 0,debug:I,errorBoundary:p,tickMs:S,zeroConfig:E,initialFacts:q});return w.initialize(),typeof window<"u"&&w.start(),w}let i="id"in e&&"schema"in e,f=i?e:e.module,d=i?{}:e,c=t?.plugins??d.plugins??[],g=t?.debug??d.debug,v=t?.errorBoundary??d.errorBoundary,M=t?.tickMs??d.tickMs,y=t?.zeroConfig??d.zeroConfig,x=t?.initialFacts??d.initialFacts,R=[...c];o&&(u.current=core.createRequirementStatusPlugin(),R=[...R,u.current.plugin]);let F=core.createSystem({module:f,plugins:R.length>0?R:void 0,debug:g,errorBoundary:v,tickMs:M,zeroConfig:y,initialFacts:x});return F.initialize(),typeof window<"u"&&F.start(),F},r.current=n.current()),react.useEffect(()=>(!r.current&&n.current&&(r.current=n.current()),()=>{r.current?.destroy(),r.current=null,u.current=null;}),[]),o&&!s?{system:r.current,statusPlugin:u.current}:r.current}function we(e,t,r){let u=react.useRef(t);u.current=t;let n=react.useRef(r);n.current=r;let o=react.useCallback(i=>e.subscribe(u.current,i),[e]),s=react.useCallback(()=>n.current(e),[e]);return react.useSyncExternalStore(o,s,s)}function Ke(e,t={}){let{facts:r,derived:u,status:n,...o}=t,s=r??[],i=u??[],f=s.length===0&&i.length===0,d=n?V(e,{status:true,...o}):V(e,o),c=n?d.system:d,g=n?d.statusPlugin:void 0,v=react.useMemo(()=>f?Object.keys(c.derive):[],[c,f]),M=react.useCallback(p=>{let S=[];return f?(S.push(c.facts.$store.subscribeAll(p)),v.length>0&&S.push(c.subscribe(v,p))):(s.length>0&&S.push(c.facts.$store.subscribe(s,p)),i.length>0&&S.push(c.subscribe(i,p))),()=>{for(let E of S)E();}},[c,f,...s,...i,...v]),y=react.useRef(h),x=react.useRef(h),R=react.useRef(null),F=react.useCallback(()=>{let p,S,E,q;if(f){p=c.facts.$store.toObject(),E=Object.keys(p),S={};for(let b of v)S[b]=c.read(b);q=v;}else {p={};for(let b of s)p[b]=c.facts[b];E=s,S={};for(let b of i)S[b]=c.read(b);q=i;}let w=y.current!==h;if(w){let b=y.current;if(Object.keys(b).length!==E.length)w=false;else for(let T of E)if(!Object.is(b[T],p[T])){w=false;break}}let C=x.current!==h;if(C){let b=x.current;if(Object.keys(b).length!==q.length)C=false;else for(let T of q)if(!Object.is(b[T],S[T])){C=false;break}}let z=w?y.current:p,W=C?x.current:S;return w||(y.current=p),C||(x.current=S),w&&C&&R.current||(R.current={facts:z,derived:W}),R.current},[c,f,...s,...i,...v]),N=react.useSyncExternalStore(M,F,F),m=react.useCallback(p=>c.dispatch(p),[c]),k=Se(c),I={system:c,dispatch:m,events:k,facts:N.facts,derived:N.derived};return n&&g?{...I,statusPlugin:g}:I}function Se(e){return adapterUtils.assertSystem("useEvents",e),react.useMemo(()=>e.events,[e])}function Fe(e,t){adapterUtils.assertSystem("useExplain",e);let r=react.useCallback(n=>{let o=e.facts.$store.subscribeAll(n),s=e.onSettledChange(n);return ()=>{o(),s();}},[e]),u=react.useCallback(()=>e.explain(t),[e,t]);return react.useSyncExternalStore(r,u,u)}function Ee(e,t){adapterUtils.assertSystem("useConstraintStatus",e);let r=oe(e);return react.useMemo(()=>{let u=e.inspect();return t?u.constraints.find(n=>n.id===t)??null:u.constraints},[e,t,r])}function Ne(e,t,r){adapterUtils.assertSystem("useOptimisticUpdate",e);let[u,n]=react.useState(false),[o,s]=react.useState(null),i=react.useRef(null),f=react.useCallback(()=>{i.current&&(e.restore(i.current),i.current=null),n(false),s(null);},[e]),d=react.useCallback(c=>{i.current=e.getSnapshot(),n(true),s(null),e.batch(c);},[e]);return react.useEffect(()=>{if(!(!t||!r||!u))return t.subscribe(()=>{let c=t.getStatus(r);!c.isLoading&&!c.hasError?(i.current=null,n(false)):c.hasError&&(s(c.lastError),f());})},[t,r,u,f]),{mutate:d,isPending:u,error:o,rollback:f}}var A=react.createContext(null);function qe({snapshot:e,children:t}){return jsxRuntime.jsx(A.Provider,{value:e,children:t})}function Ce(e,t){let r=react.useContext(A),u=react.useMemo(()=>r?.data?{...t??{},initialFacts:{...t?.initialFacts??{},...r.data}}:t??{},[r,t]);return V(e,u)}Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return adapterUtils.shallowEqual}});exports.DirectiveHydrator=qe;exports.useConstraintStatus=Ee;exports.useDerived=be;exports.useDirective=Ke;exports.useDirectiveRef=V;exports.useDispatch=Me;exports.useEvents=Se;exports.useExplain=Fe;exports.useFact=Re;exports.useHydratedSystem=Ce;exports.useInspect=oe;exports.useNamespacedSelector=we;exports.useOptimisticUpdate=Ne;exports.useRequirementStatus=ke;exports.useSelector=he;exports.useSuspenseRequirement=Ie;exports.useTimeTravel=xe;exports.useWatch=De;//# sourceMappingURL=index.cjs.map
|
|
1
|
+
'use strict';var core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils'),react=require('react'),jsxRuntime=require('react/jsx-runtime');var h=Symbol("directive.uninitialized");function me(e,t){return adapterUtils.assertSystem("useFact",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useFact() received a function. Did you mean useSelector()? useFact() takes a string key or array of keys, not a selector function."),Array.isArray(t)?ne(e,t):te(e,t)}function te(e,t){process.env.NODE_ENV!=="production"&&(t in e.facts.$store.toObject()||console.warn(`[Directive] useFact("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`));let r=react.useCallback(n=>e.facts.$store.subscribe([t],n),[e,t]),o=react.useCallback(()=>e.facts.$store.get(t),[e,t]);return react.useSyncExternalStore(r,o,o)}function ne(e,t){let r=react.useRef(h),o=react.useCallback(u=>e.facts.$store.subscribe(t,u),[e,...t]),n=react.useCallback(()=>{let u={};for(let s of t)u[s]=e.facts.$store.get(s);if(r.current!==h){let s=true;for(let i of t)if(!Object.is(r.current[i],u[i])){s=false;break}if(s)return r.current}return r.current=u,u},[e,...t]);return react.useSyncExternalStore(o,n,n)}function he(e,t){return adapterUtils.assertSystem("useDerived",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useDerived() received a function. Did you mean useSelector()? useDerived() takes a string key or array of keys, not a selector function."),Array.isArray(t)?se(e,t):re(e,t)}function re(e,t){process.env.NODE_ENV!=="production"&&(t in e.derive||console.warn(`[Directive] useDerived("${t}") \u2014 derivation not found. Check that "${t}" is defined in your module's derive property.`));let r=react.useCallback(n=>e.subscribe([t],n),[e,t]),o=react.useCallback(()=>e.read(t),[e,t]);return react.useSyncExternalStore(r,o,o)}function se(e,t){let r=react.useRef(h),o=react.useCallback(u=>e.subscribe(t,u),[e,...t]),n=react.useCallback(()=>{let u={};for(let s of t)u[s]=e.read(s);if(r.current!==h){let s=true;for(let i of t)if(!Object.is(r.current[i],u[i])){s=false;break}if(s)return r.current}return r.current=u,u},[e,...t]);return react.useSyncExternalStore(o,n,n)}function be(e,t,r,o){if(e&&e._mode==="namespaced")return oe(e,t,r,o);let n=e,u,s=false,i=o??adapterUtils.defaultEquality;r!==void 0&&(u=r,s=true),process.env.NODE_ENV!=="production"&&!n&&!s&&console.error("[Directive] useSelector() received a null/undefined system without a default value. Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)");let f=react.useRef(t),l=react.useRef(i),c=react.useRef(u);f.current=t,l.current=i,c.current=u;let g=react.useRef([]),v=react.useRef([]),b=react.useRef(h),y=react.useRef([]),k=react.useMemo(()=>n?new Set(Object.keys(n.derive)):new Set,[n]),M=react.useCallback(()=>n?adapterUtils.runTrackedSelector(n,k,f.current):{value:c.current,factKeys:[],deriveKeys:[]},[n,k]),K=react.useCallback(D=>{if(!n)return ()=>{};let R=()=>{for(let S of y.current)S();y.current=[];let{factKeys:I,deriveKeys:p}=M();g.current=I,v.current=p,I.length>0?y.current.push(n.facts.$store.subscribe(I,()=>{let S=M();adapterUtils.depsChanged(g.current,S.factKeys,v.current,S.deriveKeys)&&R(),D();})):p.length===0&&y.current.push(n.facts.$store.subscribeAll(D)),p.length>0&&y.current.push(n.subscribe(p,()=>{let S=M();adapterUtils.depsChanged(g.current,S.factKeys,v.current,S.deriveKeys)&&R(),D();}));};return R(),()=>{for(let I of y.current)I();y.current=[];}},[n,M]),F=react.useCallback(()=>{let D;if(!n)D=c.current;else {let{value:R}=M();D=R===void 0&&s?c.current:R;}return b.current!==h&&l.current(b.current,D)?b.current:(b.current=D,D)},[M,n,s]);return react.useSyncExternalStore(K,F,F)}function oe(e,t,r,o){let n=r!==void 0,u=o??adapterUtils.defaultEquality,s=react.useRef(t),i=react.useRef(u),f=react.useRef(r);s.current=t,i.current=u,f.current=r;let l=react.useRef(h),c=react.useMemo(()=>Object.keys(e.facts),[e]),g=react.useCallback(b=>{let y=c.map(k=>`${k}.*`);return e.subscribe(y,b)},[e,c]),v=react.useCallback(()=>{let b=s.current(e),y=b===void 0&&n?f.current:b;return l.current!==h&&i.current(l.current,y)?l.current:(l.current=y,y)},[e,n]);return react.useSyncExternalStore(g,v,v)}function Me(e){return adapterUtils.assertSystem("useDispatch",e),react.useCallback(t=>{e.dispatch(t);},[e])}function De(e,t,r){adapterUtils.assertSystem("useWatch",e);let o=react.useRef(r);o.current=r,react.useEffect(()=>e.watch(t,(n,u)=>{o.current(n,u);}),[e,t]);}function ue(e,t){adapterUtils.assertSystem("useInspect",e);let r=ce(e),o=t?.throttleMs,[n,u]=react.useState(r),s=react.useRef(null);return react.useEffect(()=>{if(!o||o<=0){s.current?.cleanup(),s.current=null;return}return s.current?.cleanup(),s.current=adapterUtils.createThrottle((...i)=>{u(i[0]);},o),()=>{s.current?.cleanup(),s.current=null;}},[o]),react.useEffect(()=>{s.current&&s.current.throttled(r);},[r]),!o||o<=0?r:n}function ie(e){return adapterUtils.computeInspectState(e)}function ce(e){let t=react.useRef(null),r=react.useRef([]),o=react.useRef([]),n=react.useRef(null),u=react.useCallback(i=>{let f=e.facts.$store.subscribeAll(i),l=e.onSettledChange(i);return ()=>{f(),l();}},[e]),s=react.useCallback(()=>{let i=ie(e),f=i.unmet.length===r.current.length&&i.unmet.every((g,v)=>g.id===r.current[v]),l=i.inflight.length===o.current.length&&i.inflight.every((g,v)=>g.id===o.current[v]),c=i.isSettled===n.current;return f&&l&&c&&t.current?t.current:(t.current=i,r.current=i.unmet.map(g=>g.id),o.current=i.inflight.map(g=>g.id),n.current=i.isSettled,i)},[e]);return react.useSyncExternalStore(u,s,s)}function xe(e){adapterUtils.assertSystem("useHistory",e);let t=react.useRef(null),r=react.useCallback(n=>e.onHistoryChange(n),[e]),o=react.useCallback(()=>{let n=adapterUtils.buildHistoryState(e);return n?(t.current&&t.current.canGoBack===n.canGoBack&&t.current.canGoForward===n.canGoForward&&t.current.currentIndex===n.currentIndex&&t.current.totalSnapshots===n.totalSnapshots&&t.current.isPaused===n.isPaused||(t.current=n),t.current):null},[e]);return react.useSyncExternalStore(r,o,o)}function ke(e,t){return Array.isArray(t)?le(e,t):ae(e,t)}function ae(e,t){let r=react.useRef(h),o=react.useCallback(u=>e.subscribe(u),[e]),n=react.useCallback(()=>{let u=e.getStatus(t);if(r.current!==h){let s=r.current;if(s.pending===u.pending&&s.inflight===u.inflight&&s.failed===u.failed&&s.isLoading===u.isLoading&&s.hasError===u.hasError&&s.lastError===u.lastError)return r.current}return r.current=u,u},[e,t]);return react.useSyncExternalStore(o,n,n)}function le(e,t){let r=react.useRef(null),o=react.useRef(""),n=react.useCallback(s=>e.subscribe(s),[e]),u=react.useCallback(()=>{let s={},i=[];for(let l of t){let c=e.getStatus(l);s[l]=c,i.push(`${l}:${c.pending}:${c.inflight}:${c.failed}:${c.hasError}:${c.lastError?.message??""}`);}let f=i.join("|");return f!==o.current&&(o.current=f,r.current=s),r.current??s},[e,...t]);return react.useSyncExternalStore(n,u,u)}var H=new WeakMap;function j(e){let t=H.get(e);return t||(t=new Map,H.set(e,t)),t}function Ie(e,t){return Array.isArray(t)?fe(e,t):de(e,t)}function de(e,t){let r=e.getStatus(t);if(r.hasError&&r.lastError)throw r.lastError;if(r.isLoading){let o=j(e),n=o.get(t);throw n||(n=new Promise(u=>{let s=e.subscribe(()=>{e.getStatus(t).isLoading||(o.delete(t),s(),u());});}),o.set(t,n)),n}return r}function fe(e,t){let r={},o=false,n=null;for(let u of t){let s=e.getStatus(u);r[u]=s,s.hasError&&s.lastError&&!n&&(n=s.lastError),s.isLoading&&(o=true);}if(n)throw n;if(o){let u=j(e),s=t.slice().sort().join(","),i=u.get(s);throw i||(i=new Promise(f=>{let l=e.subscribe(()=>{t.every(g=>!e.getStatus(g).isLoading)&&(u.delete(s),l(),f());});}),u.set(s,i)),i}return r}function $(e,t){let r=react.useRef(null),o=react.useRef(null),n=react.useRef(null),u=t?.status===true,s="modules"in e;return r.current||(n.current=()=>{if(s){let{modules:D,...R}=e,I=t?.plugins??R.plugins??[],p=t?.history??R.history,S=t?.trace??R.trace,E=t?.errorBoundary??R.errorBoundary,P=t?.tickMs??R.tickMs,N=t?.zeroConfig??R.zeroConfig,q=t?.initialFacts??R.initialFacts,U=core.createSystem({modules:D,plugins:I.length>0?I:void 0,history:p,trace:S,errorBoundary:E,tickMs:P,zeroConfig:N,initialFacts:q});return U.initialize(),typeof window<"u"&&U.start(),U}let i="id"in e&&"schema"in e,f=i?e:e.module,l=i?{}:e,c=t?.plugins??l.plugins??[],g=t?.history??l.history,v=t?.trace??l.trace,b=t?.errorBoundary??l.errorBoundary,y=t?.tickMs??l.tickMs,k=t?.zeroConfig??l.zeroConfig,M=t?.initialFacts??l.initialFacts,K=[...c];u&&(o.current=core.createRequirementStatusPlugin(),K=[...K,o.current.plugin]);let F=core.createSystem({module:f,plugins:K.length>0?K:void 0,history:g,trace:v,errorBoundary:b,tickMs:y,zeroConfig:k,initialFacts:M});return F.initialize(),typeof window<"u"&&F.start(),F},r.current=n.current()),react.useEffect(()=>(!r.current&&n.current&&(r.current=n.current()),()=>{r.current?.destroy(),r.current=null,o.current=null;}),[]),u&&!s?{system:r.current,statusPlugin:o.current}:r.current}function we(e,t,r){let o=react.useRef(t);o.current=t;let n=react.useRef(r);n.current=r;let u=react.useCallback(i=>e.subscribe(o.current,i),[e]),s=react.useCallback(()=>n.current(e),[e]);return react.useSyncExternalStore(u,s,s)}function Ke(e,t={}){let{facts:r,derived:o,status:n,...u}=t,s=r??[],i=o??[],f=s.length===0&&i.length===0,l=n?$(e,{status:true,...u}):$(e,u),c=n?l.system:l,g=n?l.statusPlugin:void 0,v=react.useMemo(()=>f?Object.keys(c.derive):[],[c,f]),b=react.useCallback(p=>{let S=[];return f?(S.push(c.facts.$store.subscribeAll(p)),v.length>0&&S.push(c.subscribe(v,p))):(s.length>0&&S.push(c.facts.$store.subscribe(s,p)),i.length>0&&S.push(c.subscribe(i,p))),()=>{for(let E of S)E();}},[c,f,...s,...i,...v]),y=react.useRef(h),k=react.useRef(h),M=react.useRef(null),K=react.useCallback(()=>{let p,S,E,P;if(f){p=c.facts.$store.toObject(),E=Object.keys(p),S={};for(let m of v)S[m]=c.read(m);P=v;}else {p={};for(let m of s)p[m]=c.facts[m];E=s,S={};for(let m of i)S[m]=c.read(m);P=i;}let N=y.current!==h;if(N){let m=y.current;if(Object.keys(m).length!==E.length)N=false;else for(let O of E)if(!Object.is(m[O],p[O])){N=false;break}}let q=k.current!==h;if(q){let m=k.current;if(Object.keys(m).length!==P.length)q=false;else for(let O of P)if(!Object.is(m[O],S[O])){q=false;break}}let U=N?y.current:p,z=q?k.current:S;return N||(y.current=p),q||(k.current=S),N&&q&&M.current||(M.current={facts:U,derived:z}),M.current},[c,f,...s,...i,...v]),F=react.useSyncExternalStore(b,K,K),D=react.useCallback(p=>c.dispatch(p),[c]),R=Se(c),I={system:c,dispatch:D,events:R,facts:F.facts,derived:F.derived};return n&&g?{...I,statusPlugin:g}:I}function Se(e){return adapterUtils.assertSystem("useEvents",e),react.useMemo(()=>e.events,[e])}function Fe(e,t){adapterUtils.assertSystem("useExplain",e);let r=react.useCallback(n=>{let u=e.facts.$store.subscribeAll(n),s=e.onSettledChange(n);return ()=>{u(),s();}},[e]),o=react.useCallback(()=>e.explain(t),[e,t]);return react.useSyncExternalStore(r,o,o)}function Ee(e,t){adapterUtils.assertSystem("useConstraintStatus",e);let r=ue(e);return react.useMemo(()=>{let o=e.inspect();return t?o.constraints.find(n=>n.id===t)??null:o.constraints},[e,t,r])}function Ne(e,t,r){adapterUtils.assertSystem("useOptimisticUpdate",e);let[o,n]=react.useState(false),[u,s]=react.useState(null),i=react.useRef(null),f=react.useCallback(()=>{i.current&&(e.restore(i.current),i.current=null),n(false),s(null);},[e]),l=react.useCallback(c=>{i.current=e.getSnapshot(),n(true),s(null),e.batch(c);},[e]);return react.useEffect(()=>{if(!(!t||!r||!o))return t.subscribe(()=>{let c=t.getStatus(r);!c.isLoading&&!c.hasError?(i.current=null,n(false)):c.hasError&&(s(c.lastError),f());})},[t,r,o,f]),{mutate:l,isPending:o,error:u,rollback:f}}var A=react.createContext(null);function qe({snapshot:e,children:t}){return jsxRuntime.jsx(A.Provider,{value:e,children:t})}function Pe(e,t){let r=react.useContext(A),o=react.useMemo(()=>r?.data?{...t??{},initialFacts:{...t?.initialFacts??{},...r.data}}:t??{},[r,t]);return $(e,o)}Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return adapterUtils.shallowEqual}});exports.DirectiveHydrator=qe;exports.useConstraintStatus=Ee;exports.useDerived=he;exports.useDirective=Ke;exports.useDirectiveRef=$;exports.useDispatch=Me;exports.useEvents=Se;exports.useExplain=Fe;exports.useFact=me;exports.useHistory=xe;exports.useHydratedSystem=Pe;exports.useInspect=ue;exports.useNamespacedSelector=we;exports.useOptimisticUpdate=Ne;exports.useRequirementStatus=ke;exports.useSelector=be;exports.useSuspenseRequirement=Ie;exports.useWatch=De;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.tsx"],"names":["UNINITIALIZED","useFact","system","keyOrKeys","assertSystem","_useFacts","_useSingleFact","factKey","subscribe","useCallback","onStoreChange","getSnapshot","useSyncExternalStore","factKeys","cachedValue","useRef","result","key","same","useDerived","_useDerivedMulti","_useSingleDerived","derivationId","derivationIds","id","useSelector","systemArg","selector","defaultValueArg","equalityFnArg","_useNamespacedSelectorImpl","defaultValue","hasDefault","equalityFn","defaultEquality","selectorRef","eqRef","defaultValueRef","trackedFactKeysRef","trackedDeriveKeysRef","unsubsRef","deriveKeys","useMemo","runWithTracking","runTrackedSelector","resubscribe","unsub","derivedKeys","updated","depsChanged","effectiveValue","newValue","moduleNames","wildcardKeys","ns","useDispatch","event","useWatch","callback","callbackRef","useEffect","prevValue","useInspect","options","syncState","_useInspectSync","throttleMs","deferredState","setDeferredState","useState","throttleRef","createThrottle","args","_buildInspectState","computeInspectState","cachedSnapshot","cachedUnmetIds","cachedInflightIds","cachedIsSettled","unsubFacts","unsubSettled","state","unmetSame","u","i","inflightSame","f","settledSame","useTimeTravel","cachedRef","buildTimeTravelState","useRequirementStatus","statusPlugin","typeOrTypes","_useRequirementStatusMulti","_useRequirementStatusSingle","type","status","prev","types","cachedKey","parts","suspenseCacheMap","getSuspenseCache","plugin","cache","useSuspenseRequirement","_useSuspenseRequirementMulti","_useSuspenseRequirementSingle","promise","resolve","unsubscribe","hasLoading","firstError","cacheKey","t","useDirectiveRef","config","systemRef","statusPluginRef","factoryRef","wantStatus","isNamespaced","modules","rest","plugins","debug","errorBoundary","tickMs","zeroConfig","initialFacts","sys","createSystem","isModule","mod","baseOpts","allPlugins","createRequirementStatusPlugin","useNamespacedSelector","keys","keysRef","useDirective","moduleOrOptions","selections","factKeysOpt","derivedKeysOpt","configRest","subscribeAll","refResult","allDerivationKeys","unsubs","cachedFacts","cachedDerived","cachedWrapper","factsResult","derivedResult","effectiveFactKeys","effectiveDerivedKeys","factsSame","derivedSame","stableFacts","stableDerived","values","dispatch","events","useEvents","base","useExplain","requirementId","useConstraintStatus","constraintId","inspectState","inspection","c","useOptimisticUpdate","requirementType","isPending","setIsPending","error","setError","snapshotRef","rollback","mutate","updateFn","HydrationContext","createContext","DirectiveHydrator","snapshot","children","jsx","useHydratedSystem","moduleDef","useContext","mergedConfig"],"mappings":"8KA0FA,IAAMA,CAAAA,CAAgB,OAAO,yBAAyB,CAAA,CAmB/C,SAASC,EAAAA,CAEdC,CAAAA,CACAC,CAAAA,CACS,CAaT,OAZAC,yBAAAA,CAAa,SAAA,CAAWF,CAAM,CAAA,CAE5B,OAAA,CAAQ,IAAI,QAAA,GAAa,YAAA,EACzB,OAAOC,CAAAA,EAAc,YAErB,OAAA,CAAQ,KAAA,CACN,gJAEF,CAAA,CAIE,KAAA,CAAM,QAAQA,CAAS,CAAA,CAClBE,EAAAA,CAAUH,CAAAA,CAAQC,CAAS,CAAA,CAI7BG,EAAAA,CAAeJ,EAAQC,CAAS,CACzC,CAEA,SAASG,EAAAA,CAEPJ,CAAAA,CACAK,CAAAA,CACS,CACL,OAAA,C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AAC,CAQtC,CAACsE,CAAAA,CAAUtE,CAAM,CAAC,CAAA,CAErB,OAAOD,CAAAA,CAAgB2E,CAAAA,CAAWE,CAAY,CAChD","file":"index.cjs","sourcesContent":["/**\n * React Adapter - Consolidated hooks for React integration\n *\n * 18 public exports: useFact, useDerived, useDispatch, useDirective,\n * useDirectiveRef, useSelector, useWatch, useInspect, useRequirementStatus,\n * useSuspenseRequirement, useEvents, useExplain, useConstraintStatus,\n * useOptimisticUpdate, DirectiveHydrator, useHydratedSystem,\n * useTimeTravel, shallowEqual\n *\n * @example\n * ```tsx\n * import { useFact, useDerived, useEvents } from '@directive-run/react';\n *\n * const system = createSystem({ module: counterModule });\n * system.start();\n *\n * function Counter() {\n * const count = useFact(system, \"count\");\n * const doubled = useDerived(system, \"doubled\");\n * const events = useEvents(system);\n *\n * return (\n * <div>\n * <p>Count: {count}</p>\n * <p>Doubled: {doubled}</p>\n * <button onClick={() => events.increment()}>+</button>\n * </div>\n * );\n * }\n * ```\n */\n\nimport type {\n DebugConfig,\n DistributableSnapshot,\n ErrorBoundaryConfig,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemSnapshot,\n TimeTravelState,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildTimeTravelState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport type { ReactNode } from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/** Sentinel value for uninitialized selector cache */\nconst UNINITIALIZED = Symbol(\"directive.uninitialized\");\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;\n\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;\n\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFacts(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return _useSingleFact(system, keyOrKeys);\n}\n\nfunction _useSingleFact(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKey: string,\n): unknown {\n if (process.env.NODE_ENV !== \"production\") {\n if (!(factKey in system.facts.$store.toObject())) {\n console.warn(\n `[Directive] useFact(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe([factKey], onStoreChange);\n },\n [system, factKey],\n );\n\n const getSnapshot = useCallback(() => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n return (system.facts as any)[factKey];\n }, [system, factKey]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useFacts(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe(factKeys, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...factKeys],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n result[key] = (system.facts as any)[key];\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const key of factKeys) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[key],\n result[key],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...factKeys]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];\n\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Pick<InferDerivations<S>, K>;\n\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useDerived\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(keyOrKeys)) {\n return _useDerivedMulti(system, keyOrKeys);\n }\n\n // Single key path\n return _useSingleDerived(system, keyOrKeys);\n}\n\nfunction _useSingleDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationId: string,\n): unknown {\n if (process.env.NODE_ENV !== \"production\") {\n if (!(derivationId in system.derive)) {\n console.warn(\n `[Directive] useDerived(\"${derivationId}\") — derivation not found. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe([derivationId], onStoreChange);\n },\n [system, derivationId],\n );\n\n const getSnapshot = useCallback(() => {\n return system.read(derivationId);\n }, [system, derivationId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useDerivedMulti(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe(derivationIds, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...derivationIds],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const id of derivationIds) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[id],\n result[id],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...derivationIds]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSelector — Zustand-style selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations (Zustand-style).\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys. Falls back to subscribeAll\n * if no keys are detected.\n *\n * Supports an optional default value as the 3rd parameter, used when\n * the system is null/undefined or the selector returns undefined.\n * When a default value is provided, the system parameter may be\n * null | undefined — the hook returns the default and recomputes\n * when the system becomes available.\n *\n * An optional equality function can be passed as the 4th parameter\n * to customize when the selector result is considered \"changed\".\n * Defaults to `Object.is`. Use `shallowEqual` (exported from this\n * package) when your selector returns a new object/array each time.\n *\n * @example\n * ```tsx\n * // Basic usage\n * const count = useSelector(system, (s) => s.count);\n *\n * // With default value (allows nullable system)\n * const count = useSelector(system, (s) => s.count, 0);\n *\n * // With default value + custom equality\n * const coords = useSelector(system, (s) => ({ x: s.x, y: s.y }), { x: 0, y: 0 }, shallowEqual);\n * ```\n */\n\n// Non-null system, no default\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n): R;\n\n// Non-null system, with default value and optional equality\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable system, default REQUIRED\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S> | null | undefined,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Namespaced system overloads ---\n\n// Namespaced system, no default\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n): R;\n\n// Namespaced system, with default value and optional equality\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable namespaced system, default REQUIRED\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules> | null | undefined,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Generic fallbacks ---\n\n// Generic fallback: non-null system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue?: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Generic fallback: nullable system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature accepts both system types\n systemArg: SingleModuleSystem<any> | NamespacedSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n // Route to namespaced implementation if system is a NamespacedSystem\n // biome-ignore lint/suspicious/noExplicitAny: Runtime type check\n if (systemArg && (systemArg as any)._mode === \"namespaced\") {\n // biome-ignore lint/suspicious/noExplicitAny: Delegate to namespaced impl\n return _useNamespacedSelectorImpl(\n systemArg as NamespacedSystem<any>,\n selector,\n defaultValueArg,\n equalityFnArg,\n );\n }\n\n // After the namespaced check, system is a SingleModuleSystem\n const system = systemArg as SingleModuleSystem<any> | null | undefined;\n let defaultValue: unknown;\n let hasDefault = false;\n const equalityFn: (a: unknown, b: unknown) => boolean =\n equalityFnArg ?? defaultEquality;\n\n if (defaultValueArg !== undefined) {\n defaultValue = defaultValueArg;\n hasDefault = true;\n }\n\n // Dev-mode warning: null system without a default value\n if (process.env.NODE_ENV !== \"production\") {\n if (!system && !hasDefault) {\n console.error(\n \"[Directive] useSelector() received a null/undefined system without a default value. \" +\n \"Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)\",\n );\n }\n }\n\n // Store selector/eq/default in refs to avoid resubscription churn\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValue);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValue;\n\n const trackedFactKeysRef = useRef<string[]>([]);\n const trackedDeriveKeysRef = useRef<string[]>([]);\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n const unsubsRef = useRef<Array<() => void>>([]);\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const deriveKeys = useMemo(\n () => (system ? new Set(Object.keys(system.derive)) : new Set<string>()),\n [system],\n );\n\n const runWithTracking = useCallback(() => {\n if (!system) {\n return {\n value: defaultValueRef.current,\n factKeys: [] as string[],\n deriveKeys: [] as string[],\n };\n }\n\n return runTrackedSelector(system, deriveKeys, selectorRef.current);\n }, [system, deriveKeys]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!system) {\n // No system — return noop unsubscribe\n return () => {};\n }\n\n const resubscribe = () => {\n // Cleanup previous subscriptions\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n\n // Run selector with tracking to detect accessed keys\n const { factKeys, deriveKeys: derivedKeys } = runWithTracking();\n trackedFactKeysRef.current = factKeys;\n trackedDeriveKeysRef.current = derivedKeys;\n\n // Subscribe to accessed fact keys\n if (factKeys.length > 0) {\n unsubsRef.current.push(\n system.facts.$store.subscribe(factKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n } else if (derivedKeys.length === 0) {\n // No deps at all — subscribe to everything\n unsubsRef.current.push(\n system.facts.$store.subscribeAll(onStoreChange),\n );\n }\n\n // Subscribe to accessed derivation keys\n if (derivedKeys.length > 0) {\n unsubsRef.current.push(\n system.subscribe(derivedKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n };\n },\n [system, runWithTracking],\n );\n\n const getSnapshot = useCallback(() => {\n let effectiveValue: unknown;\n\n if (!system) {\n effectiveValue = defaultValueRef.current;\n } else {\n const { value: newValue } = runWithTracking();\n\n // When selector returns undefined and we have a default, use it\n effectiveValue =\n newValue === undefined && hasDefault\n ? defaultValueRef.current\n : newValue;\n }\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [runWithTracking, system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// _useNamespacedSelectorImpl — internal namespaced useSelector\n// ============================================================================\n\n/**\n * Internal implementation for useSelector with NamespacedSystem.\n * Subscribes to all module namespaces and runs the selector against the system.\n * Uses equality comparison to prevent unnecessary re-renders.\n */\nfunction _useNamespacedSelectorImpl(\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n system: NamespacedSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n const hasDefault = defaultValueArg !== undefined;\n const equalityFn = equalityFnArg ?? defaultEquality;\n\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValueArg);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValueArg;\n\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n\n // Get all module namespace names for wildcard subscription\n const moduleNames = useMemo(() => Object.keys(system.facts), [system]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n // Subscribe to all modules using wildcard keys\n const wildcardKeys = moduleNames.map((ns) => `${ns}.*`);\n\n return system.subscribe(wildcardKeys, onStoreChange);\n },\n [system, moduleNames],\n );\n\n const getSnapshot = useCallback(() => {\n const newValue = selectorRef.current(system);\n const effectiveValue =\n newValue === undefined && hasDefault ? defaultValueRef.current : newValue;\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return useCallback(\n (event: InferEvents<S>) => {\n system.dispatch(event);\n },\n [system],\n );\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect (no re-render)\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n prevValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n prevValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n callback: (newValue: any, prevValue: any) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n useEffect(() => {\n return system.watch(key, (newValue, prevValue) => {\n callbackRef.current(newValue, prevValue);\n });\n }, [system, key]);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n// InspectState is imported from ./shared.js and re-exported above\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n /** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */\n throttleMs?: number;\n}\n\n/**\n * Hook to get consolidated system inspection data reactively.\n *\n * Merges isSettled, unmet/inflight requirements, and working state\n * into a single subscription. Optionally throttle updates.\n *\n * @example\n * ```tsx\n * const { isSettled, isWorking, hasUnmet } = useInspect(system);\n * const throttled = useInspect(system, { throttleMs: 200 });\n * ```\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): InspectState {\n assertSystem(\"useInspect\", system);\n // Always call the sync version (useSyncExternalStore path) — no conditional hooks\n const syncState = _useInspectSync(system);\n\n const throttleMs = options?.throttleMs;\n const [deferredState, setDeferredState] = useState(syncState);\n const throttleRef = useRef<{\n throttled: (...args: unknown[]) => void;\n cleanup: () => void;\n } | null>(null);\n\n // Create/recreate throttle when throttleMs changes\n useEffect(() => {\n if (!throttleMs || throttleMs <= 0) {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n return;\n }\n // Clean up old throttle before creating new one\n throttleRef.current?.cleanup();\n throttleRef.current = createThrottle((...args: unknown[]) => {\n setDeferredState(args[0] as InspectState);\n }, throttleMs);\n return () => {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n };\n }, [throttleMs]);\n\n // Feed sync state through throttle after each render\n useEffect(() => {\n if (throttleRef.current) {\n throttleRef.current.throttled(syncState);\n }\n }, [syncState]);\n\n if (!throttleMs || throttleMs <= 0) return syncState;\n return deferredState;\n}\n\nfunction _buildInspectState(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n return computeInspectState(system);\n}\n\nfunction _useInspectSync(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n const cachedSnapshot = useRef<InspectState | null>(null);\n const cachedUnmetIds = useRef<string[]>([]);\n const cachedInflightIds = useRef<string[]>([]);\n const cachedIsSettled = useRef<boolean | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = _buildInspectState(system);\n\n const unmetSame =\n state.unmet.length === cachedUnmetIds.current.length &&\n state.unmet.every((u, i) => u.id === cachedUnmetIds.current[i]);\n const inflightSame =\n state.inflight.length === cachedInflightIds.current.length &&\n state.inflight.every((f, i) => f.id === cachedInflightIds.current[i]);\n const settledSame = state.isSettled === cachedIsSettled.current;\n\n if (unmetSame && inflightSame && settledSame && cachedSnapshot.current) {\n return cachedSnapshot.current;\n }\n\n cachedSnapshot.current = state;\n cachedUnmetIds.current = state.unmet.map((u) => u.id);\n cachedInflightIds.current = state.inflight.map((f) => f.id);\n cachedIsSettled.current = state.isSettled;\n\n return state;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useTimeTravel — reactive time-travel state\n// ============================================================================\n\n/**\n * Reactive time-travel hook. Returns null when time-travel is disabled.\n * Re-renders when snapshots are taken or navigation occurs.\n *\n * @example\n * ```tsx\n * const tt = useTimeTravel(system);\n * if (tt) {\n * return (\n * <div>\n * <button disabled={!tt.canUndo} onClick={tt.undo}>Undo</button>\n * <button disabled={!tt.canRedo} onClick={tt.redo}>Redo</button>\n * <span>{tt.currentIndex + 1} / {tt.totalSnapshots}</span>\n * </div>\n * );\n * }\n * ```\n */\nexport function useTimeTravel(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): TimeTravelState | null {\n assertSystem(\"useTimeTravel\", system);\n const cachedRef = useRef<TimeTravelState | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => system.onTimeTravelChange(onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = buildTimeTravelState(system);\n if (!state) return null;\n\n // Return stable reference when values haven't changed\n if (\n cachedRef.current &&\n cachedRef.current.canUndo === state.canUndo &&\n cachedRef.current.canRedo === state.canRedo &&\n cachedRef.current.currentIndex === state.currentIndex &&\n cachedRef.current.totalSnapshots === state.totalSnapshots &&\n cachedRef.current.isPaused === state.isPaused\n ) {\n return cachedRef.current;\n }\n\n cachedRef.current = state;\n return cachedRef.current;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useRequirementStatusMulti(statusPlugin, typeOrTypes);\n }\n return _useRequirementStatusSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useRequirementStatusSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const cachedRef = useRef<RequirementTypeStatus | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const status = statusPlugin.getStatus(type);\n\n if (cachedRef.current !== UNINITIALIZED) {\n const prev = cachedRef.current;\n if (\n prev.pending === status.pending &&\n prev.inflight === status.inflight &&\n prev.failed === status.failed &&\n prev.isLoading === status.isLoading &&\n prev.hasError === status.hasError &&\n prev.lastError === status.lastError\n ) {\n return cachedRef.current;\n }\n }\n\n cachedRef.current = status;\n return status;\n }, [statusPlugin, type]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useRequirementStatusMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const cachedRef = useRef<Record<string, RequirementTypeStatus> | null>(null);\n const cachedKey = useRef<string>(\"\");\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, RequirementTypeStatus> = {};\n const parts: string[] = [];\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n parts.push(\n `${type}:${status.pending}:${status.inflight}:${status.failed}:${status.hasError}:${status.lastError?.message ?? \"\"}`,\n );\n }\n const key = parts.join(\"|\");\n\n if (key !== cachedKey.current) {\n cachedKey.current = key;\n cachedRef.current = result;\n }\n\n return cachedRef.current ?? result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [statusPlugin, ...types]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSuspenseRequirement — single or multi\n// ============================================================================\n\n// Cache for pending promises, scoped per statusPlugin to prevent cross-system leaks.\nconst suspenseCacheMap = new WeakMap<\n StatusPlugin,\n Map<string, Promise<void>>\n>();\n\nfunction getSuspenseCache(plugin: StatusPlugin): Map<string, Promise<void>> {\n let cache = suspenseCacheMap.get(plugin);\n if (!cache) {\n cache = new Map();\n suspenseCacheMap.set(plugin, cache);\n }\n return cache;\n}\n\n/** Single type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useSuspenseRequirementMulti(statusPlugin, typeOrTypes);\n }\n return _useSuspenseRequirementSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useSuspenseRequirementSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const status = statusPlugin.getStatus(type);\n\n if (status.hasError && status.lastError) {\n throw status.lastError;\n }\n\n if (status.isLoading) {\n const cache = getSuspenseCache(statusPlugin);\n let promise = cache.get(type);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const currentStatus = statusPlugin.getStatus(type);\n if (!currentStatus.isLoading) {\n cache.delete(type);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(type, promise);\n }\n\n throw promise;\n }\n\n return status;\n}\n\nfunction _useSuspenseRequirementMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const result: Record<string, RequirementTypeStatus> = {};\n let hasLoading = false;\n let firstError: Error | null = null;\n\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n\n if (status.hasError && status.lastError && !firstError) {\n firstError = status.lastError;\n }\n if (status.isLoading) {\n hasLoading = true;\n }\n }\n\n if (firstError) {\n throw firstError;\n }\n\n if (hasLoading) {\n const cache = getSuspenseCache(statusPlugin);\n const cacheKey = types.slice().sort().join(\",\");\n let promise = cache.get(cacheKey);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const allDone = types.every(\n (t) => !statusPlugin.getStatus(t).isLoading,\n );\n if (allDone) {\n cache.delete(cacheKey);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(cacheKey, promise);\n }\n\n throw promise;\n }\n\n return result;\n}\n\n// ============================================================================\n// useDirectiveRef — scoped system lifecycle\n// ============================================================================\n\n/** Base options for creating a scoped system */\ninterface DirectiveRefBaseConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n debug?: DebugConfig;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n}\n\n/** Options for useDirectiveRef: module directly, or config object */\nexport type UseDirectiveRefOptions<M extends ModuleSchema> =\n | ModuleDef<M>\n | (DirectiveRefBaseConfig & { module: ModuleDef<M> });\n\n/** Options for useDirectiveRef with namespaced modules */\nexport type UseDirectiveRefNamespacedOptions<Modules extends ModulesMap> =\n DirectiveRefBaseConfig & { modules: { [K in keyof Modules]: Modules[K] } };\n\n// --- Single-module overloads ---\n\n/** Without status (no config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n): SingleModuleSystem<M>;\n\n/** Without status (with config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: DirectiveRefBaseConfig,\n): SingleModuleSystem<M>;\n\n/** With status: returns { system, statusPlugin } */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: { status: true } & DirectiveRefBaseConfig,\n): { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin };\n\n// --- Namespaced (multi-module) overloads ---\n\n/** Namespaced: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n): NamespacedSystem<Modules>;\n\n/** Namespaced with config: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n config: DirectiveRefBaseConfig,\n): NamespacedSystem<Modules>;\n\n/** Implementation */\nexport function useDirectiveRef(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature handles both modes\n options: any,\n config?: { status?: boolean } & DirectiveRefBaseConfig,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation return varies by overload\n): any {\n // biome-ignore lint/suspicious/noExplicitAny: System ref holds either system type\n const systemRef = useRef<any>(null);\n const statusPluginRef = useRef<StatusPlugin | null>(null);\n // Factory ref for strict mode re-creation (effects unmount then re-mount)\n // biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\n const factoryRef = useRef<(() => any) | null>(null);\n const wantStatus = config?.status === true;\n const isNamespaced = \"modules\" in options;\n\n if (!systemRef.current) {\n // Build a factory that creates + starts the system.\n // Called once during render and again on strict-mode re-mount.\n factoryRef.current = () => {\n if (isNamespaced) {\n // --- Namespaced mode: { modules: { ... } } ---\n const { modules, ...rest } = options;\n const plugins = config?.plugins ?? rest.plugins ?? [];\n const debug = config?.debug ?? rest.debug;\n const errorBoundary = config?.errorBoundary ?? rest.errorBoundary;\n const tickMs = config?.tickMs ?? rest.tickMs;\n const zeroConfig = config?.zeroConfig ?? rest.zeroConfig;\n const initialFacts = config?.initialFacts ?? rest.initialFacts;\n\n const sys = createSystem({\n modules,\n plugins: plugins.length > 0 ? plugins : undefined,\n debug,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n }\n\n // --- Single-module mode ---\n const isModule = \"id\" in options && \"schema\" in options;\n const mod = isModule ? options : options.module;\n const baseOpts = isModule ? {} : (options as DirectiveRefBaseConfig);\n const plugins = config?.plugins ?? baseOpts.plugins ?? [];\n const debug = config?.debug ?? baseOpts.debug;\n const errorBoundary = config?.errorBoundary ?? baseOpts.errorBoundary;\n const tickMs = config?.tickMs ?? baseOpts.tickMs;\n const zeroConfig = config?.zeroConfig ?? baseOpts.zeroConfig;\n const initialFacts = config?.initialFacts ?? baseOpts.initialFacts;\n\n let allPlugins = [...plugins];\n\n if (wantStatus) {\n statusPluginRef.current = createRequirementStatusPlugin();\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins = [\n ...allPlugins,\n statusPluginRef.current.plugin as Plugin<any>,\n ];\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const sys = createSystem({\n module: mod,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n debug,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n };\n\n // Start synchronously so facts are initialized before the first render\n systemRef.current = factoryRef.current();\n }\n\n useEffect(() => {\n // Strict mode re-mount: system was destroyed in cleanup, recreate it\n if (!systemRef.current && factoryRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n return () => {\n systemRef.current?.destroy();\n systemRef.current = null;\n statusPluginRef.current = null;\n };\n }, []);\n\n if (wantStatus && !isNamespaced) {\n return {\n system: systemRef.current!,\n statusPlugin: statusPluginRef.current!,\n };\n }\n\n return systemRef.current!;\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem with useSyncExternalStore\n// ============================================================================\n\n/**\n * React hook to select derived values from a NamespacedSystem.\n * Uses useSyncExternalStore for tear-free reads.\n *\n * @param system - The namespaced system to read from\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```tsx\n * const system = useDirectiveRef({ modules: { auth, data } });\n * const token = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * const count = useNamespacedSelector(system, [\"data.*\"], (s) => s.derive.data.total);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): R {\n const keysRef = useRef(keys);\n keysRef.current = keys;\n const selectorRef = useRef(selector);\n selectorRef.current = selector;\n\n const subscribe = useCallback(\n (onStoreChange: () => void) =>\n system.subscribe(keysRef.current, onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => selectorRef.current(system), [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDirective — scoped system with selected values in containers\n// ============================================================================\n\n/** Options for useDirective hook */\nexport interface UseDirectiveOptions<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n> extends DirectiveRefBaseConfig {\n /** Fact keys to subscribe to */\n facts?: FK[];\n /** Derivation keys to subscribe to */\n derived?: DK[];\n /** Enable status plugin */\n status?: boolean;\n}\n\n/** Return type for useDirective hook (without status) */\nexport type UseDirectiveReturn<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = {\n system: SingleModuleSystem<S>;\n dispatch: (event: InferEvents<S>) => void;\n events: SingleModuleSystem<S>[\"events\"];\n facts: Pick<InferFacts<S>, FK>;\n derived: Pick<InferDerivations<S>, DK>;\n};\n\n/** Return type for useDirective hook (with status) */\nexport type UseDirectiveReturnWithStatus<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = UseDirectiveReturn<S, FK, DK> & {\n statusPlugin: StatusPlugin;\n};\n\n/**\n * Convenience hook that creates a scoped system and reads selected facts/derivations\n * into container objects. When no `facts` or `derived` keys are specified, subscribes\n * to ALL facts and derivations (replacing the former `useModule` hook).\n *\n * @example\n * ```tsx\n * // Selective subscription\n * const { dispatch, facts: { count }, derived: { doubled } } = useDirective(counterModule, {\n * facts: [\"count\"],\n * derived: [\"doubled\"],\n * });\n *\n * // Subscribe to everything (no keys = all facts + all derivations)\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n * ```\n */\nexport function useDirective<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n>(\n moduleOrOptions: UseDirectiveRefOptions<S>,\n selections: UseDirectiveOptions<S, FK, DK> = {} as UseDirectiveOptions<\n S,\n FK,\n DK\n >,\n): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK> {\n const {\n facts: factKeysOpt,\n derived: derivedKeysOpt,\n status,\n ...configRest\n } = selections;\n const factKeys = (factKeysOpt ?? []) as FK[];\n const derivedKeys = (derivedKeysOpt ?? []) as DK[];\n\n // When no keys are specified, subscribe to everything\n const subscribeAll = factKeys.length === 0 && derivedKeys.length === 0;\n\n // Create system via useDirectiveRef (handles lifecycle)\n // biome-ignore lint/suspicious/noExplicitAny: Conditional overload dispatch\n const refResult: any = status\n ? useDirectiveRef(moduleOrOptions, { status: true as const, ...configRest })\n : useDirectiveRef(moduleOrOptions, configRest);\n\n const system: SingleModuleSystem<S> = status ? refResult.system : refResult;\n\n const statusPlugin = status\n ? (\n refResult as {\n system: SingleModuleSystem<S>;\n statusPlugin: StatusPlugin;\n }\n ).statusPlugin\n : undefined;\n\n // For subscribe-all mode, get all derivation keys\n const allDerivationKeys = useMemo(\n () => (subscribeAll ? Object.keys(system.derive) : []),\n [system, subscribeAll],\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubs: Array<() => void> = [];\n if (subscribeAll) {\n // Subscribe to ALL facts and ALL derivations\n unsubs.push(system.facts.$store.subscribeAll(onStoreChange));\n if (allDerivationKeys.length > 0) {\n unsubs.push(system.subscribe(allDerivationKeys, onStoreChange));\n }\n } else {\n if (factKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(factKeys, onStoreChange));\n }\n if (derivedKeys.length > 0) {\n unsubs.push(system.subscribe(derivedKeys, onStoreChange));\n }\n }\n return () => {\n for (const unsub of unsubs) unsub();\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys],\n );\n\n const cachedFacts = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedDerived = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedWrapper = useRef<{\n facts: Record<string, unknown>;\n derived: Record<string, unknown>;\n } | null>(null);\n\n const getSnapshot = useCallback(() => {\n let factsResult: Record<string, unknown>;\n let derivedResult: Record<string, unknown>;\n let effectiveFactKeys: readonly string[];\n let effectiveDerivedKeys: readonly string[];\n\n if (subscribeAll) {\n // Read ALL facts and ALL derivations\n factsResult = system.facts.$store.toObject();\n effectiveFactKeys = Object.keys(factsResult);\n derivedResult = {};\n for (const key of allDerivationKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = allDerivationKeys;\n } else {\n // Read selected keys only\n factsResult = {};\n for (const key of factKeys) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n factsResult[key] = (system.facts as any)[key];\n }\n effectiveFactKeys = factKeys;\n derivedResult = {};\n for (const key of derivedKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = derivedKeys;\n }\n\n // Check facts stability\n let factsSame = cachedFacts.current !== UNINITIALIZED;\n if (factsSame) {\n const prev = cachedFacts.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveFactKeys.length) {\n factsSame = false;\n } else {\n for (const key of effectiveFactKeys) {\n if (!Object.is(prev[key], factsResult[key])) {\n factsSame = false;\n break;\n }\n }\n }\n }\n\n // Check derived stability\n let derivedSame = cachedDerived.current !== UNINITIALIZED;\n if (derivedSame) {\n const prev = cachedDerived.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveDerivedKeys.length) {\n derivedSame = false;\n } else {\n for (const key of effectiveDerivedKeys) {\n if (!Object.is(prev[key], derivedResult[key])) {\n derivedSame = false;\n break;\n }\n }\n }\n }\n\n const stableFacts = factsSame\n ? (cachedFacts.current as Record<string, unknown>)\n : factsResult;\n const stableDerived = derivedSame\n ? (cachedDerived.current as Record<string, unknown>)\n : derivedResult;\n\n if (!factsSame) cachedFacts.current = factsResult;\n if (!derivedSame) cachedDerived.current = derivedResult;\n\n // Return same wrapper reference when both containers are unchanged\n if (factsSame && derivedSame && cachedWrapper.current) {\n return cachedWrapper.current;\n }\n\n cachedWrapper.current = { facts: stableFacts, derived: stableDerived };\n return cachedWrapper.current;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys]);\n\n const values = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const dispatch = useCallback(\n (event: InferEvents<S>) => system.dispatch(event),\n [system],\n );\n\n const events = useEvents(system);\n\n const base = {\n system,\n dispatch,\n events,\n facts: values.facts as Pick<InferFacts<S>, FK>,\n derived: values.derived as Pick<InferDerivations<S>, DK>,\n };\n\n if (status && statusPlugin) {\n return { ...base, statusPlugin } as UseDirectiveReturnWithStatus<S, FK, DK>;\n }\n\n return base as UseDirectiveReturn<S, FK, DK>;\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher. Provides autocomplete for event names\n * and avoids needing useCallback wrappers for event dispatch.\n *\n * @example\n * ```tsx\n * const events = useEvents(system);\n * <button onClick={() => events.increment()}>+</button>\n * ```\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return useMemo(() => system.events, [system]);\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n * Updates whenever system state changes.\n *\n * @example\n * ```tsx\n * const explanation = useExplain(system, \"req-123\");\n * if (explanation) <pre>{explanation}</pre>;\n * ```\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): string | null {\n assertSystem(\"useExplain\", system);\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n return system.explain(requirementId);\n }, [system, requirementId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n// ConstraintInfo is imported from ./shared.js and re-exported above\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): ConstraintInfo[];\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): ConstraintInfo | null;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n assertSystem(\"useConstraintStatus\", system);\n const inspectState = useInspect(system);\n\n return useMemo(() => {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return inspection.constraints.find((c) => c.id === constraintId) ?? null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, constraintId, inspectState]);\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\n/** Result of useOptimisticUpdate */\nexport interface OptimisticUpdateResult {\n /** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */\n mutate: (updateFn: () => void) => void;\n /** Whether a resolver is currently processing the optimistic change */\n isPending: boolean;\n /** Error if the resolver failed */\n error: Error | null;\n /** Manually rollback to the pre-mutation snapshot */\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n *\n * @example\n * ```tsx\n * const { mutate, isPending, error, rollback } = useOptimisticUpdate(\n * system, statusPlugin, \"SAVE_ITEM\"\n * );\n * mutate(() => { system.facts.items = [...system.facts.items, newItem]; });\n * ```\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const snapshotRef = useRef<SystemSnapshot | null>(null);\n\n const rollback = useCallback(() => {\n if (snapshotRef.current) {\n system.restore(snapshotRef.current);\n snapshotRef.current = null;\n }\n setIsPending(false);\n setError(null);\n }, [system]);\n\n const mutate = useCallback(\n (updateFn: () => void) => {\n snapshotRef.current = system.getSnapshot();\n setIsPending(true);\n setError(null);\n system.batch(updateFn);\n },\n [system],\n );\n\n // Watch for resolver completion/failure\n useEffect(() => {\n if (!statusPlugin || !requirementType || !isPending) return;\n\n return statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n // Resolved successfully — keep optimistic state\n snapshotRef.current = null;\n setIsPending(false);\n } else if (status.hasError) {\n // Failed — rollback\n setError(status.lastError);\n rollback();\n }\n });\n }, [statusPlugin, requirementType, isPending, rollback]);\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// DirectiveHydrator + useHydratedSystem — SSR/RSC hydration\n// ============================================================================\n\n/** Props for DirectiveHydrator component */\nexport interface HydratorProps {\n snapshot: DistributableSnapshot;\n children: ReactNode;\n}\n\n/** Context for hydrated snapshot */\nconst HydrationContext = createContext<DistributableSnapshot | null>(null);\n\n/**\n * SSR/RSC hydration component. Wraps children with a snapshot context\n * that `useHydratedSystem` can consume on the client.\n *\n * @example\n * ```tsx\n * // Server component\n * <DirectiveHydrator snapshot={serverSnapshot}>\n * <ClientApp />\n * </DirectiveHydrator>\n * ```\n */\nexport function DirectiveHydrator({ snapshot, children }: HydratorProps) {\n return (\n <HydrationContext.Provider value={snapshot}>\n {children}\n </HydrationContext.Provider>\n );\n}\n\n/**\n * Client-side hook that creates a system hydrated from a server snapshot.\n * Must be used inside a `<DirectiveHydrator>`.\n *\n * @example\n * ```tsx\n * function ClientApp() {\n * const system = useHydratedSystem(counterModule);\n * const count = useFact(system, \"count\");\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useHydratedSystem<S extends ModuleSchema>(\n moduleDef: ModuleDef<S>,\n config?: DirectiveRefBaseConfig,\n): SingleModuleSystem<S> {\n const snapshot = useContext(HydrationContext);\n\n // Merge snapshot data as initial facts if available\n const mergedConfig = useMemo(() => {\n if (!snapshot?.data) return config ?? {};\n return {\n ...(config ?? {}),\n initialFacts: {\n ...(config?.initialFacts ?? {}),\n ...snapshot.data,\n },\n };\n }, [snapshot, config]);\n\n return useDirectiveRef(moduleDef, mergedConfig) as SingleModuleSystem<S>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.tsx"],"names":["UNINITIALIZED","useFact","system","keyOrKeys","assertSystem","_useFacts","_useSingleFact","factKey","subscribe","useCallback","onStoreChange","getSnapshot","useSyncExternalStore","factKeys","cachedValue","useRef","result","key","same","useDerived","_useDerivedMulti","_useSingleDerived","derivationId","derivationIds","id","useSelector","systemArg","selector","defaultValueArg","equalityFnArg","_useNamespacedSelectorImpl","defaultValue","hasDefault","equalityFn","defaultEquality","selectorRef","eqRef","defaultValueRef","trackedFactKeysRef","trackedDeriveKeysRef","unsubsRef","deriveKeys","useMemo","runWithTracking","runTrackedSelector","resubscribe","unsub","derivedKeys","updated","depsChanged","effectiveValue","newValue","moduleNames","wildcardKeys","ns","useDispatch","event","useWatch","callback","callbackRef","useEffect","prevValue","useInspect","options","syncState","_useInspectSync","throttleMs","deferredState","setDeferredState","useState","throttleRef","createThrottle","args","_buildInspectState","computeInspectState","cachedSnapshot","cachedUnmetIds","cachedInflightIds","cachedIsSettled","unsubFacts","unsubSettled","state","unmetSame","u","i","inflightSame","f","settledSame","useHistory","cachedRef","buildHistoryState","useRequirementStatus","statusPlugin","typeOrTypes","_useRequirementStatusMulti","_useRequirementStatusSingle","type","status","prev","types","cachedKey","parts","suspenseCacheMap","getSuspenseCache","plugin","cache","useSuspenseRequirement","_useSuspenseRequirementMulti","_useSuspenseRequirementSingle","promise","resolve","unsubscribe","hasLoading","firstError","cacheKey","t","useDirectiveRef","config","systemRef","statusPluginRef","factoryRef","wantStatus","isNamespaced","modules","rest","plugins","history","trace","errorBoundary","tickMs","zeroConfig","initialFacts","sys","createSystem","isModule","mod","baseOpts","allPlugins","createRequirementStatusPlugin","useNamespacedSelector","keys","keysRef","useDirective","moduleOrOptions","selections","factKeysOpt","derivedKeysOpt","configRest","subscribeAll","refResult","allDerivationKeys","unsubs","cachedFacts","cachedDerived","cachedWrapper","factsResult","derivedResult","effectiveFactKeys","effectiveDerivedKeys","factsSame","derivedSame","stableFacts","stableDerived","values","dispatch","events","useEvents","base","useExplain","requirementId","useConstraintStatus","constraintId","inspectState","inspection","c","useOptimisticUpdate","requirementType","isPending","setIsPending","error","setError","snapshotRef","rollback","mutate","updateFn","HydrationContext","createContext","DirectiveHydrator","snapshot","children","jsx","useHydratedSystem","moduleDef","useContext","mergedConfig"],"mappings":"8KA2FA,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CAAAA,CAAmBC,oBAA4C,IAAI,CAAA,CAclE,SAASC,EAAAA,CAAkB,CAAE,QAAA,CAAAC,CAAAA,CAAU,SAAAC,CAAS,CAAA,CAAkB,CACvE,OACEC,cAAAA,CAACL,CAAAA,CAAiB,QAAA,CAAjB,CAA0B,KAAA,CAAOG,CAAAA,CAC/B,SAAAC,CAAAA,CACH,CAEJ,CAeO,SAASE,EAAAA,CACdC,CAAAA,CACA3E,CAAAA,CACuB,CACvB,IAAMuE,CAAAA,CAAWK,iBAAWR,CAAgB,CAAA,CAGtCS,EAAexJ,aAAAA,CAAQ,IACtBkJ,CAAAA,EAAU,IAAA,CACR,CACL,GAAIvE,CAAAA,EAAU,EAAC,CACf,YAAA,CAAc,CACZ,GAAIA,CAAAA,EAAQ,YAAA,EAAgB,GAC5B,GAAGuE,CAAAA,CAAS,IACd,CACF,CAAA,CAP4BvE,GAAU,EAAC,CAQtC,CAACuE,CAAAA,CAAUvE,CAAM,CAAC,CAAA,CAErB,OAAOD,CAAAA,CAAgB4E,CAAAA,CAAWE,CAAY,CAChD","file":"index.cjs","sourcesContent":["/**\n * React Adapter - Consolidated hooks for React integration\n *\n * 18 public exports: useFact, useDerived, useDispatch, useDirective,\n * useDirectiveRef, useSelector, useWatch, useInspect, useRequirementStatus,\n * useSuspenseRequirement, useEvents, useExplain, useConstraintStatus,\n * useOptimisticUpdate, DirectiveHydrator, useHydratedSystem,\n * useHistory, shallowEqual\n *\n * @example\n * ```tsx\n * import { useFact, useDerived, useEvents } from '@directive-run/react';\n *\n * const system = createSystem({ module: counterModule });\n * system.start();\n *\n * function Counter() {\n * const count = useFact(system, \"count\");\n * const doubled = useDerived(system, \"doubled\");\n * const events = useEvents(system);\n *\n * return (\n * <div>\n * <p>Count: {count}</p>\n * <p>Doubled: {doubled}</p>\n * <button onClick={() => events.increment()}>+</button>\n * </div>\n * );\n * }\n * ```\n */\n\nimport type {\n TraceOption,\n DistributableSnapshot,\n ErrorBoundaryConfig,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemSnapshot,\n HistoryOption,\n HistoryState,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport type { ReactNode } from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/** Sentinel value for uninitialized selector cache */\nconst UNINITIALIZED = Symbol(\"directive.uninitialized\");\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;\n\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;\n\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFacts(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return _useSingleFact(system, keyOrKeys);\n}\n\nfunction _useSingleFact(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKey: string,\n): unknown {\n if (process.env.NODE_ENV !== \"production\") {\n if (!(factKey in system.facts.$store.toObject())) {\n console.warn(\n `[Directive] useFact(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe([factKey], onStoreChange);\n },\n [system, factKey],\n );\n\n const getSnapshot = useCallback(() => {\n return system.facts.$store.get(factKey as never);\n }, [system, factKey]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useFacts(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe(factKeys, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...factKeys],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key as never);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const key of factKeys) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[key],\n result[key],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...factKeys]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];\n\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Pick<InferDerivations<S>, K>;\n\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useDerived\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(keyOrKeys)) {\n return _useDerivedMulti(system, keyOrKeys);\n }\n\n // Single key path\n return _useSingleDerived(system, keyOrKeys);\n}\n\nfunction _useSingleDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationId: string,\n): unknown {\n if (process.env.NODE_ENV !== \"production\") {\n if (!(derivationId in system.derive)) {\n console.warn(\n `[Directive] useDerived(\"${derivationId}\") — derivation not found. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe([derivationId], onStoreChange);\n },\n [system, derivationId],\n );\n\n const getSnapshot = useCallback(() => {\n return system.read(derivationId);\n }, [system, derivationId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useDerivedMulti(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe(derivationIds, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...derivationIds],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const id of derivationIds) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[id],\n result[id],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...derivationIds]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSelector — Zustand-style selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations (Zustand-style).\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys. Falls back to subscribeAll\n * if no keys are detected.\n *\n * Supports an optional default value as the 3rd parameter, used when\n * the system is null/undefined or the selector returns undefined.\n * When a default value is provided, the system parameter may be\n * null | undefined — the hook returns the default and recomputes\n * when the system becomes available.\n *\n * An optional equality function can be passed as the 4th parameter\n * to customize when the selector result is considered \"changed\".\n * Defaults to `Object.is`. Use `shallowEqual` (exported from this\n * package) when your selector returns a new object/array each time.\n *\n * @example\n * ```tsx\n * // Basic usage\n * const count = useSelector(system, (s) => s.count);\n *\n * // With default value (allows nullable system)\n * const count = useSelector(system, (s) => s.count, 0);\n *\n * // With default value + custom equality\n * const coords = useSelector(system, (s) => ({ x: s.x, y: s.y }), { x: 0, y: 0 }, shallowEqual);\n * ```\n */\n\n// Non-null system, no default\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n): R;\n\n// Non-null system, with default value and optional equality\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable system, default REQUIRED\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S> | null | undefined,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Namespaced system overloads ---\n\n// Namespaced system, no default\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n): R;\n\n// Namespaced system, with default value and optional equality\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable namespaced system, default REQUIRED\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules> | null | undefined,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Generic fallbacks ---\n\n// Generic fallback: non-null system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue?: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Generic fallback: nullable system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature accepts both system types\n systemArg: SingleModuleSystem<any> | NamespacedSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n // Route to namespaced implementation if system is a NamespacedSystem\n // biome-ignore lint/suspicious/noExplicitAny: Runtime type check\n if (systemArg && (systemArg as any)._mode === \"namespaced\") {\n // biome-ignore lint/suspicious/noExplicitAny: Delegate to namespaced impl\n return _useNamespacedSelectorImpl(\n systemArg as NamespacedSystem<any>,\n selector,\n defaultValueArg,\n equalityFnArg,\n );\n }\n\n // After the namespaced check, system is a SingleModuleSystem\n const system = systemArg as SingleModuleSystem<any> | null | undefined;\n let defaultValue: unknown;\n let hasDefault = false;\n const equalityFn: (a: unknown, b: unknown) => boolean =\n equalityFnArg ?? defaultEquality;\n\n if (defaultValueArg !== undefined) {\n defaultValue = defaultValueArg;\n hasDefault = true;\n }\n\n // Dev-mode warning: null system without a default value\n if (process.env.NODE_ENV !== \"production\") {\n if (!system && !hasDefault) {\n console.error(\n \"[Directive] useSelector() received a null/undefined system without a default value. \" +\n \"Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)\",\n );\n }\n }\n\n // Store selector/eq/default in refs to avoid resubscription churn\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValue);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValue;\n\n const trackedFactKeysRef = useRef<string[]>([]);\n const trackedDeriveKeysRef = useRef<string[]>([]);\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n const unsubsRef = useRef<Array<() => void>>([]);\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const deriveKeys = useMemo(\n () => (system ? new Set(Object.keys(system.derive)) : new Set<string>()),\n [system],\n );\n\n const runWithTracking = useCallback(() => {\n if (!system) {\n return {\n value: defaultValueRef.current,\n factKeys: [] as string[],\n deriveKeys: [] as string[],\n };\n }\n\n return runTrackedSelector(system, deriveKeys, selectorRef.current);\n }, [system, deriveKeys]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!system) {\n // No system — return noop unsubscribe\n return () => {};\n }\n\n const resubscribe = () => {\n // Cleanup previous subscriptions\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n\n // Run selector with tracking to detect accessed keys\n const { factKeys, deriveKeys: derivedKeys } = runWithTracking();\n trackedFactKeysRef.current = factKeys;\n trackedDeriveKeysRef.current = derivedKeys;\n\n // Subscribe to accessed fact keys\n if (factKeys.length > 0) {\n unsubsRef.current.push(\n system.facts.$store.subscribe(factKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n } else if (derivedKeys.length === 0) {\n // No deps at all — subscribe to everything\n unsubsRef.current.push(\n system.facts.$store.subscribeAll(onStoreChange),\n );\n }\n\n // Subscribe to accessed derivation keys\n if (derivedKeys.length > 0) {\n unsubsRef.current.push(\n system.subscribe(derivedKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n };\n },\n [system, runWithTracking],\n );\n\n const getSnapshot = useCallback(() => {\n let effectiveValue: unknown;\n\n if (!system) {\n effectiveValue = defaultValueRef.current;\n } else {\n const { value: newValue } = runWithTracking();\n\n // When selector returns undefined and we have a default, use it\n effectiveValue =\n newValue === undefined && hasDefault\n ? defaultValueRef.current\n : newValue;\n }\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [runWithTracking, system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// _useNamespacedSelectorImpl — internal namespaced useSelector\n// ============================================================================\n\n/**\n * Internal implementation for useSelector with NamespacedSystem.\n * Subscribes to all module namespaces and runs the selector against the system.\n * Uses equality comparison to prevent unnecessary re-renders.\n */\nfunction _useNamespacedSelectorImpl(\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n system: NamespacedSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n const hasDefault = defaultValueArg !== undefined;\n const equalityFn = equalityFnArg ?? defaultEquality;\n\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValueArg);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValueArg;\n\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n\n // Get all module namespace names for wildcard subscription\n const moduleNames = useMemo(() => Object.keys(system.facts), [system]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n // Subscribe to all modules using wildcard keys\n const wildcardKeys = moduleNames.map((ns) => `${ns}.*`);\n\n return system.subscribe(wildcardKeys, onStoreChange);\n },\n [system, moduleNames],\n );\n\n const getSnapshot = useCallback(() => {\n const newValue = selectorRef.current(system);\n const effectiveValue =\n newValue === undefined && hasDefault ? defaultValueRef.current : newValue;\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return useCallback(\n (event: InferEvents<S>) => {\n system.dispatch(event);\n },\n [system],\n );\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect (no re-render)\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n prevValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n prevValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n callback: (newValue: any, prevValue: any) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n useEffect(() => {\n return system.watch(key, (newValue, prevValue) => {\n callbackRef.current(newValue, prevValue);\n });\n }, [system, key]);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n// InspectState is imported from ./shared.js and re-exported above\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n /** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */\n throttleMs?: number;\n}\n\n/**\n * Hook to get consolidated system inspection data reactively.\n *\n * Merges isSettled, unmet/inflight requirements, and working state\n * into a single subscription. Optionally throttle updates.\n *\n * @example\n * ```tsx\n * const { isSettled, isWorking, hasUnmet } = useInspect(system);\n * const throttled = useInspect(system, { throttleMs: 200 });\n * ```\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): InspectState {\n assertSystem(\"useInspect\", system);\n // Always call the sync version (useSyncExternalStore path) — no conditional hooks\n const syncState = _useInspectSync(system);\n\n const throttleMs = options?.throttleMs;\n const [deferredState, setDeferredState] = useState(syncState);\n const throttleRef = useRef<{\n throttled: (...args: unknown[]) => void;\n cleanup: () => void;\n } | null>(null);\n\n // Create/recreate throttle when throttleMs changes\n useEffect(() => {\n if (!throttleMs || throttleMs <= 0) {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n return;\n }\n // Clean up old throttle before creating new one\n throttleRef.current?.cleanup();\n throttleRef.current = createThrottle((...args: unknown[]) => {\n setDeferredState(args[0] as InspectState);\n }, throttleMs);\n return () => {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n };\n }, [throttleMs]);\n\n // Feed sync state through throttle after each render\n useEffect(() => {\n if (throttleRef.current) {\n throttleRef.current.throttled(syncState);\n }\n }, [syncState]);\n\n if (!throttleMs || throttleMs <= 0) return syncState;\n return deferredState;\n}\n\nfunction _buildInspectState(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n return computeInspectState(system);\n}\n\nfunction _useInspectSync(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n const cachedSnapshot = useRef<InspectState | null>(null);\n const cachedUnmetIds = useRef<string[]>([]);\n const cachedInflightIds = useRef<string[]>([]);\n const cachedIsSettled = useRef<boolean | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = _buildInspectState(system);\n\n const unmetSame =\n state.unmet.length === cachedUnmetIds.current.length &&\n state.unmet.every((u, i) => u.id === cachedUnmetIds.current[i]);\n const inflightSame =\n state.inflight.length === cachedInflightIds.current.length &&\n state.inflight.every((f, i) => f.id === cachedInflightIds.current[i]);\n const settledSame = state.isSettled === cachedIsSettled.current;\n\n if (unmetSame && inflightSame && settledSame && cachedSnapshot.current) {\n return cachedSnapshot.current;\n }\n\n cachedSnapshot.current = state;\n cachedUnmetIds.current = state.unmet.map((u) => u.id);\n cachedInflightIds.current = state.inflight.map((f) => f.id);\n cachedIsSettled.current = state.isSettled;\n\n return state;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useHistory — reactive history state\n// ============================================================================\n\n/**\n * Reactive history hook. Returns null when history is disabled.\n * Re-renders when snapshots are taken or navigation occurs.\n *\n * @example\n * ```tsx\n * const history = useHistory(system);\n * if (history) {\n * return (\n * <div>\n * <button disabled={!history.canGoBack} onClick={() => history.goBack()}>Undo</button>\n * <button disabled={!history.canGoForward} onClick={() => history.goForward()}>Redo</button>\n * <span>{history.currentIndex + 1} / {history.totalSnapshots}</span>\n * </div>\n * );\n * }\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): HistoryState | null {\n assertSystem(\"useHistory\", system);\n const cachedRef = useRef<HistoryState | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => system.onHistoryChange(onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = buildHistoryState(system);\n if (!state) return null;\n\n // Return stable reference when values haven't changed\n if (\n cachedRef.current &&\n cachedRef.current.canGoBack === state.canGoBack &&\n cachedRef.current.canGoForward === state.canGoForward &&\n cachedRef.current.currentIndex === state.currentIndex &&\n cachedRef.current.totalSnapshots === state.totalSnapshots &&\n cachedRef.current.isPaused === state.isPaused\n ) {\n return cachedRef.current;\n }\n\n cachedRef.current = state;\n return cachedRef.current;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useRequirementStatusMulti(statusPlugin, typeOrTypes);\n }\n return _useRequirementStatusSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useRequirementStatusSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const cachedRef = useRef<RequirementTypeStatus | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const status = statusPlugin.getStatus(type);\n\n if (cachedRef.current !== UNINITIALIZED) {\n const prev = cachedRef.current;\n if (\n prev.pending === status.pending &&\n prev.inflight === status.inflight &&\n prev.failed === status.failed &&\n prev.isLoading === status.isLoading &&\n prev.hasError === status.hasError &&\n prev.lastError === status.lastError\n ) {\n return cachedRef.current;\n }\n }\n\n cachedRef.current = status;\n return status;\n }, [statusPlugin, type]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useRequirementStatusMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const cachedRef = useRef<Record<string, RequirementTypeStatus> | null>(null);\n const cachedKey = useRef<string>(\"\");\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, RequirementTypeStatus> = {};\n const parts: string[] = [];\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n parts.push(\n `${type}:${status.pending}:${status.inflight}:${status.failed}:${status.hasError}:${status.lastError?.message ?? \"\"}`,\n );\n }\n const key = parts.join(\"|\");\n\n if (key !== cachedKey.current) {\n cachedKey.current = key;\n cachedRef.current = result;\n }\n\n return cachedRef.current ?? result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [statusPlugin, ...types]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSuspenseRequirement — single or multi\n// ============================================================================\n\n// Cache for pending promises, scoped per statusPlugin to prevent cross-system leaks.\nconst suspenseCacheMap = new WeakMap<\n StatusPlugin,\n Map<string, Promise<void>>\n>();\n\nfunction getSuspenseCache(plugin: StatusPlugin): Map<string, Promise<void>> {\n let cache = suspenseCacheMap.get(plugin);\n if (!cache) {\n cache = new Map();\n suspenseCacheMap.set(plugin, cache);\n }\n return cache;\n}\n\n/** Single type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useSuspenseRequirementMulti(statusPlugin, typeOrTypes);\n }\n return _useSuspenseRequirementSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useSuspenseRequirementSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const status = statusPlugin.getStatus(type);\n\n if (status.hasError && status.lastError) {\n throw status.lastError;\n }\n\n if (status.isLoading) {\n const cache = getSuspenseCache(statusPlugin);\n let promise = cache.get(type);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const currentStatus = statusPlugin.getStatus(type);\n if (!currentStatus.isLoading) {\n cache.delete(type);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(type, promise);\n }\n\n throw promise;\n }\n\n return status;\n}\n\nfunction _useSuspenseRequirementMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const result: Record<string, RequirementTypeStatus> = {};\n let hasLoading = false;\n let firstError: Error | null = null;\n\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n\n if (status.hasError && status.lastError && !firstError) {\n firstError = status.lastError;\n }\n if (status.isLoading) {\n hasLoading = true;\n }\n }\n\n if (firstError) {\n throw firstError;\n }\n\n if (hasLoading) {\n const cache = getSuspenseCache(statusPlugin);\n const cacheKey = types.slice().sort().join(\",\");\n let promise = cache.get(cacheKey);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const allDone = types.every(\n (t) => !statusPlugin.getStatus(t).isLoading,\n );\n if (allDone) {\n cache.delete(cacheKey);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(cacheKey, promise);\n }\n\n throw promise;\n }\n\n return result;\n}\n\n// ============================================================================\n// useDirectiveRef — scoped system lifecycle\n// ============================================================================\n\n/** Base options for creating a scoped system */\ninterface DirectiveRefBaseConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n history?: HistoryOption;\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n}\n\n/** Options for useDirectiveRef: module directly, or config object */\nexport type UseDirectiveRefOptions<M extends ModuleSchema> =\n | ModuleDef<M>\n | (DirectiveRefBaseConfig & { module: ModuleDef<M> });\n\n/** Options for useDirectiveRef with namespaced modules */\nexport type UseDirectiveRefNamespacedOptions<Modules extends ModulesMap> =\n DirectiveRefBaseConfig & { modules: { [K in keyof Modules]: Modules[K] } };\n\n// --- Single-module overloads ---\n\n/** Without status (no config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n): SingleModuleSystem<M>;\n\n/** Without status (with config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: DirectiveRefBaseConfig,\n): SingleModuleSystem<M>;\n\n/** With status: returns { system, statusPlugin } */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: { status: true } & DirectiveRefBaseConfig,\n): { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin };\n\n// --- Namespaced (multi-module) overloads ---\n\n/** Namespaced: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n): NamespacedSystem<Modules>;\n\n/** Namespaced with config: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n config: DirectiveRefBaseConfig,\n): NamespacedSystem<Modules>;\n\n/** Implementation */\nexport function useDirectiveRef(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature handles both modes\n options: any,\n config?: { status?: boolean } & DirectiveRefBaseConfig,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation return varies by overload\n): any {\n // biome-ignore lint/suspicious/noExplicitAny: System ref holds either system type\n const systemRef = useRef<any>(null);\n const statusPluginRef = useRef<StatusPlugin | null>(null);\n // Factory ref for strict mode re-creation (effects unmount then re-mount)\n // biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\n const factoryRef = useRef<(() => any) | null>(null);\n const wantStatus = config?.status === true;\n const isNamespaced = \"modules\" in options;\n\n if (!systemRef.current) {\n // Build a factory that creates + starts the system.\n // Called once during render and again on strict-mode re-mount.\n factoryRef.current = () => {\n if (isNamespaced) {\n // --- Namespaced mode: { modules: { ... } } ---\n const { modules, ...rest } = options;\n const plugins = config?.plugins ?? rest.plugins ?? [];\n const history = config?.history ?? rest.history;\n const trace = config?.trace ?? rest.trace;\n const errorBoundary = config?.errorBoundary ?? rest.errorBoundary;\n const tickMs = config?.tickMs ?? rest.tickMs;\n const zeroConfig = config?.zeroConfig ?? rest.zeroConfig;\n const initialFacts = config?.initialFacts ?? rest.initialFacts;\n\n const sys = createSystem({\n modules,\n plugins: plugins.length > 0 ? plugins : undefined,\n history,\n trace,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n }\n\n // --- Single-module mode ---\n const isModule = \"id\" in options && \"schema\" in options;\n const mod = isModule ? options : options.module;\n const baseOpts = isModule ? {} : (options as DirectiveRefBaseConfig);\n const plugins = config?.plugins ?? baseOpts.plugins ?? [];\n const history = config?.history ?? baseOpts.history;\n const trace = config?.trace ?? baseOpts.trace;\n const errorBoundary = config?.errorBoundary ?? baseOpts.errorBoundary;\n const tickMs = config?.tickMs ?? baseOpts.tickMs;\n const zeroConfig = config?.zeroConfig ?? baseOpts.zeroConfig;\n const initialFacts = config?.initialFacts ?? baseOpts.initialFacts;\n\n let allPlugins = [...plugins];\n\n if (wantStatus) {\n statusPluginRef.current = createRequirementStatusPlugin();\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins = [\n ...allPlugins,\n statusPluginRef.current.plugin as Plugin<any>,\n ];\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const sys = createSystem({\n module: mod,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n history,\n trace,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n };\n\n // Start synchronously so facts are initialized before the first render\n systemRef.current = factoryRef.current();\n }\n\n useEffect(() => {\n // Strict mode re-mount: system was destroyed in cleanup, recreate it\n if (!systemRef.current && factoryRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n return () => {\n systemRef.current?.destroy();\n systemRef.current = null;\n statusPluginRef.current = null;\n };\n }, []);\n\n if (wantStatus && !isNamespaced) {\n return {\n system: systemRef.current!,\n statusPlugin: statusPluginRef.current!,\n };\n }\n\n return systemRef.current!;\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem with useSyncExternalStore\n// ============================================================================\n\n/**\n * React hook to select derived values from a NamespacedSystem.\n * Uses useSyncExternalStore for tear-free reads.\n *\n * @param system - The namespaced system to read from\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```tsx\n * const system = useDirectiveRef({ modules: { auth, data } });\n * const token = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * const count = useNamespacedSelector(system, [\"data.*\"], (s) => s.derive.data.total);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): R {\n const keysRef = useRef(keys);\n keysRef.current = keys;\n const selectorRef = useRef(selector);\n selectorRef.current = selector;\n\n const subscribe = useCallback(\n (onStoreChange: () => void) =>\n system.subscribe(keysRef.current, onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => selectorRef.current(system), [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDirective — scoped system with selected values in containers\n// ============================================================================\n\n/** Options for useDirective hook */\nexport interface UseDirectiveOptions<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n> extends DirectiveRefBaseConfig {\n /** Fact keys to subscribe to */\n facts?: FK[];\n /** Derivation keys to subscribe to */\n derived?: DK[];\n /** Enable status plugin */\n status?: boolean;\n}\n\n/** Return type for useDirective hook (without status) */\nexport type UseDirectiveReturn<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = {\n system: SingleModuleSystem<S>;\n dispatch: (event: InferEvents<S>) => void;\n events: SingleModuleSystem<S>[\"events\"];\n facts: Pick<InferFacts<S>, FK>;\n derived: Pick<InferDerivations<S>, DK>;\n};\n\n/** Return type for useDirective hook (with status) */\nexport type UseDirectiveReturnWithStatus<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = UseDirectiveReturn<S, FK, DK> & {\n statusPlugin: StatusPlugin;\n};\n\n/**\n * Convenience hook that creates a scoped system and reads selected facts/derivations\n * into container objects. When no `facts` or `derived` keys are specified, subscribes\n * to ALL facts and derivations (replacing the former `useModule` hook).\n *\n * @example\n * ```tsx\n * // Selective subscription\n * const { dispatch, facts: { count }, derived: { doubled } } = useDirective(counterModule, {\n * facts: [\"count\"],\n * derived: [\"doubled\"],\n * });\n *\n * // Subscribe to everything (no keys = all facts + all derivations)\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n * ```\n */\nexport function useDirective<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n>(\n moduleOrOptions: UseDirectiveRefOptions<S>,\n selections: UseDirectiveOptions<S, FK, DK> = {} as UseDirectiveOptions<\n S,\n FK,\n DK\n >,\n): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK> {\n const {\n facts: factKeysOpt,\n derived: derivedKeysOpt,\n status,\n ...configRest\n } = selections;\n const factKeys = (factKeysOpt ?? []) as FK[];\n const derivedKeys = (derivedKeysOpt ?? []) as DK[];\n\n // When no keys are specified, subscribe to everything\n const subscribeAll = factKeys.length === 0 && derivedKeys.length === 0;\n\n // Create system via useDirectiveRef (handles lifecycle)\n // biome-ignore lint/suspicious/noExplicitAny: Conditional overload dispatch\n const refResult: any = status\n ? useDirectiveRef(moduleOrOptions, { status: true as const, ...configRest })\n : useDirectiveRef(moduleOrOptions, configRest);\n\n const system: SingleModuleSystem<S> = status ? refResult.system : refResult;\n\n const statusPlugin = status\n ? (\n refResult as {\n system: SingleModuleSystem<S>;\n statusPlugin: StatusPlugin;\n }\n ).statusPlugin\n : undefined;\n\n // For subscribe-all mode, get all derivation keys\n const allDerivationKeys = useMemo(\n () => (subscribeAll ? Object.keys(system.derive) : []),\n [system, subscribeAll],\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubs: Array<() => void> = [];\n if (subscribeAll) {\n // Subscribe to ALL facts and ALL derivations\n unsubs.push(system.facts.$store.subscribeAll(onStoreChange));\n if (allDerivationKeys.length > 0) {\n unsubs.push(system.subscribe(allDerivationKeys, onStoreChange));\n }\n } else {\n if (factKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(factKeys, onStoreChange));\n }\n if (derivedKeys.length > 0) {\n unsubs.push(system.subscribe(derivedKeys, onStoreChange));\n }\n }\n return () => {\n for (const unsub of unsubs) unsub();\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys],\n );\n\n const cachedFacts = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedDerived = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedWrapper = useRef<{\n facts: Record<string, unknown>;\n derived: Record<string, unknown>;\n } | null>(null);\n\n const getSnapshot = useCallback(() => {\n let factsResult: Record<string, unknown>;\n let derivedResult: Record<string, unknown>;\n let effectiveFactKeys: readonly string[];\n let effectiveDerivedKeys: readonly string[];\n\n if (subscribeAll) {\n // Read ALL facts and ALL derivations\n factsResult = system.facts.$store.toObject();\n effectiveFactKeys = Object.keys(factsResult);\n derivedResult = {};\n for (const key of allDerivationKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = allDerivationKeys;\n } else {\n // Read selected keys only\n factsResult = {};\n for (const key of factKeys) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n factsResult[key] = (system.facts as any)[key];\n }\n effectiveFactKeys = factKeys;\n derivedResult = {};\n for (const key of derivedKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = derivedKeys;\n }\n\n // Check facts stability\n let factsSame = cachedFacts.current !== UNINITIALIZED;\n if (factsSame) {\n const prev = cachedFacts.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveFactKeys.length) {\n factsSame = false;\n } else {\n for (const key of effectiveFactKeys) {\n if (!Object.is(prev[key], factsResult[key])) {\n factsSame = false;\n break;\n }\n }\n }\n }\n\n // Check derived stability\n let derivedSame = cachedDerived.current !== UNINITIALIZED;\n if (derivedSame) {\n const prev = cachedDerived.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveDerivedKeys.length) {\n derivedSame = false;\n } else {\n for (const key of effectiveDerivedKeys) {\n if (!Object.is(prev[key], derivedResult[key])) {\n derivedSame = false;\n break;\n }\n }\n }\n }\n\n const stableFacts = factsSame\n ? (cachedFacts.current as Record<string, unknown>)\n : factsResult;\n const stableDerived = derivedSame\n ? (cachedDerived.current as Record<string, unknown>)\n : derivedResult;\n\n if (!factsSame) cachedFacts.current = factsResult;\n if (!derivedSame) cachedDerived.current = derivedResult;\n\n // Return same wrapper reference when both containers are unchanged\n if (factsSame && derivedSame && cachedWrapper.current) {\n return cachedWrapper.current;\n }\n\n cachedWrapper.current = { facts: stableFacts, derived: stableDerived };\n return cachedWrapper.current;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys]);\n\n const values = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const dispatch = useCallback(\n (event: InferEvents<S>) => system.dispatch(event),\n [system],\n );\n\n const events = useEvents(system);\n\n const base = {\n system,\n dispatch,\n events,\n facts: values.facts as Pick<InferFacts<S>, FK>,\n derived: values.derived as Pick<InferDerivations<S>, DK>,\n };\n\n if (status && statusPlugin) {\n return { ...base, statusPlugin } as UseDirectiveReturnWithStatus<S, FK, DK>;\n }\n\n return base as UseDirectiveReturn<S, FK, DK>;\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher. Provides autocomplete for event names\n * and avoids needing useCallback wrappers for event dispatch.\n *\n * @example\n * ```tsx\n * const events = useEvents(system);\n * <button onClick={() => events.increment()}>+</button>\n * ```\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return useMemo(() => system.events, [system]);\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n * Updates whenever system state changes.\n *\n * @example\n * ```tsx\n * const explanation = useExplain(system, \"req-123\");\n * if (explanation) <pre>{explanation}</pre>;\n * ```\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): string | null {\n assertSystem(\"useExplain\", system);\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n return system.explain(requirementId);\n }, [system, requirementId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n// ConstraintInfo is imported from ./shared.js and re-exported above\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): ConstraintInfo[];\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): ConstraintInfo | null;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n assertSystem(\"useConstraintStatus\", system);\n const inspectState = useInspect(system);\n\n return useMemo(() => {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return inspection.constraints.find((c) => c.id === constraintId) ?? null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, constraintId, inspectState]);\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\n/** Result of useOptimisticUpdate */\nexport interface OptimisticUpdateResult {\n /** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */\n mutate: (updateFn: () => void) => void;\n /** Whether a resolver is currently processing the optimistic change */\n isPending: boolean;\n /** Error if the resolver failed */\n error: Error | null;\n /** Manually rollback to the pre-mutation snapshot */\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n *\n * @example\n * ```tsx\n * const { mutate, isPending, error, rollback } = useOptimisticUpdate(\n * system, statusPlugin, \"SAVE_ITEM\"\n * );\n * mutate(() => { system.facts.items = [...system.facts.items, newItem]; });\n * ```\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const snapshotRef = useRef<SystemSnapshot | null>(null);\n\n const rollback = useCallback(() => {\n if (snapshotRef.current) {\n system.restore(snapshotRef.current);\n snapshotRef.current = null;\n }\n setIsPending(false);\n setError(null);\n }, [system]);\n\n const mutate = useCallback(\n (updateFn: () => void) => {\n snapshotRef.current = system.getSnapshot();\n setIsPending(true);\n setError(null);\n system.batch(updateFn);\n },\n [system],\n );\n\n // Watch for resolver completion/failure\n useEffect(() => {\n if (!statusPlugin || !requirementType || !isPending) return;\n\n return statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n // Resolved successfully — keep optimistic state\n snapshotRef.current = null;\n setIsPending(false);\n } else if (status.hasError) {\n // Failed — rollback\n setError(status.lastError);\n rollback();\n }\n });\n }, [statusPlugin, requirementType, isPending, rollback]);\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// DirectiveHydrator + useHydratedSystem — SSR/RSC hydration\n// ============================================================================\n\n/** Props for DirectiveHydrator component */\nexport interface HydratorProps {\n snapshot: DistributableSnapshot;\n children: ReactNode;\n}\n\n/** Context for hydrated snapshot */\nconst HydrationContext = createContext<DistributableSnapshot | null>(null);\n\n/**\n * SSR/RSC hydration component. Wraps children with a snapshot context\n * that `useHydratedSystem` can consume on the client.\n *\n * @example\n * ```tsx\n * // Server component\n * <DirectiveHydrator snapshot={serverSnapshot}>\n * <ClientApp />\n * </DirectiveHydrator>\n * ```\n */\nexport function DirectiveHydrator({ snapshot, children }: HydratorProps) {\n return (\n <HydrationContext.Provider value={snapshot}>\n {children}\n </HydrationContext.Provider>\n );\n}\n\n/**\n * Client-side hook that creates a system hydrated from a server snapshot.\n * Must be used inside a `<DirectiveHydrator>`.\n *\n * @example\n * ```tsx\n * function ClientApp() {\n * const system = useHydratedSystem(counterModule);\n * const count = useFact(system, \"count\");\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useHydratedSystem<S extends ModuleSchema>(\n moduleDef: ModuleDef<S>,\n config?: DirectiveRefBaseConfig,\n): SingleModuleSystem<S> {\n const snapshot = useContext(HydrationContext);\n\n // Merge snapshot data as initial facts if available\n const mergedConfig = useMemo(() => {\n if (!snapshot?.data) return config ?? {};\n return {\n ...(config ?? {}),\n initialFacts: {\n ...(config?.initialFacts ?? {}),\n ...snapshot.data,\n },\n };\n }, [snapshot, config]);\n\n return useDirectiveRef(moduleDef, mergedConfig) as SingleModuleSystem<S>;\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
-
import { DistributableSnapshot, createRequirementStatusPlugin, ModuleSchema, InferFacts, InferDerivations, Plugin,
|
|
2
|
+
import { DistributableSnapshot, createRequirementStatusPlugin, ModuleSchema, InferFacts, InferDerivations, Plugin, HistoryOption, TraceOption, ErrorBoundaryConfig, ModulesMap, ModuleDef, SingleModuleSystem, InferEvents, NamespacedSystem, HistoryState, RequirementTypeStatus, InferSelectorState } from '@directive-run/core';
|
|
3
3
|
export { RequirementTypeStatus } from '@directive-run/core';
|
|
4
4
|
import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
|
|
5
5
|
export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
|
|
@@ -76,24 +76,24 @@ interface UseInspectOptions {
|
|
|
76
76
|
*/
|
|
77
77
|
declare function useInspect(system: SingleModuleSystem<any>, options?: UseInspectOptions): InspectState;
|
|
78
78
|
/**
|
|
79
|
-
* Reactive
|
|
79
|
+
* Reactive history hook. Returns null when history is disabled.
|
|
80
80
|
* Re-renders when snapshots are taken or navigation occurs.
|
|
81
81
|
*
|
|
82
82
|
* @example
|
|
83
83
|
* ```tsx
|
|
84
|
-
* const
|
|
85
|
-
* if (
|
|
84
|
+
* const history = useHistory(system);
|
|
85
|
+
* if (history) {
|
|
86
86
|
* return (
|
|
87
87
|
* <div>
|
|
88
|
-
* <button disabled={!
|
|
89
|
-
* <button disabled={!
|
|
90
|
-
* <span>{
|
|
88
|
+
* <button disabled={!history.canGoBack} onClick={() => history.goBack()}>Undo</button>
|
|
89
|
+
* <button disabled={!history.canGoForward} onClick={() => history.goForward()}>Redo</button>
|
|
90
|
+
* <span>{history.currentIndex + 1} / {history.totalSnapshots}</span>
|
|
91
91
|
* </div>
|
|
92
92
|
* );
|
|
93
93
|
* }
|
|
94
94
|
* ```
|
|
95
95
|
*/
|
|
96
|
-
declare function
|
|
96
|
+
declare function useHistory(system: SingleModuleSystem<any>): HistoryState | null;
|
|
97
97
|
/** Single type overload */
|
|
98
98
|
declare function useRequirementStatus(statusPlugin: StatusPlugin, type: string): RequirementTypeStatus;
|
|
99
99
|
/** Multi-type overload */
|
|
@@ -105,7 +105,8 @@ declare function useSuspenseRequirement(statusPlugin: StatusPlugin, types: strin
|
|
|
105
105
|
/** Base options for creating a scoped system */
|
|
106
106
|
interface DirectiveRefBaseConfig {
|
|
107
107
|
plugins?: Plugin<any>[];
|
|
108
|
-
|
|
108
|
+
history?: HistoryOption;
|
|
109
|
+
trace?: TraceOption;
|
|
109
110
|
errorBoundary?: ErrorBoundaryConfig;
|
|
110
111
|
tickMs?: number;
|
|
111
112
|
zeroConfig?: boolean;
|
|
@@ -274,4 +275,4 @@ declare function DirectiveHydrator({ snapshot, children }: HydratorProps): react
|
|
|
274
275
|
*/
|
|
275
276
|
declare function useHydratedSystem<S extends ModuleSchema>(moduleDef: ModuleDef<S>, config?: DirectiveRefBaseConfig): SingleModuleSystem<S>;
|
|
276
277
|
|
|
277
|
-
export { DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefNamespacedOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useRequirementStatus, useSelector, useSuspenseRequirement,
|
|
278
|
+
export { DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefNamespacedOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useHistory, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useRequirementStatus, useSelector, useSuspenseRequirement, useWatch };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
-
import { DistributableSnapshot, createRequirementStatusPlugin, ModuleSchema, InferFacts, InferDerivations, Plugin,
|
|
2
|
+
import { DistributableSnapshot, createRequirementStatusPlugin, ModuleSchema, InferFacts, InferDerivations, Plugin, HistoryOption, TraceOption, ErrorBoundaryConfig, ModulesMap, ModuleDef, SingleModuleSystem, InferEvents, NamespacedSystem, HistoryState, RequirementTypeStatus, InferSelectorState } from '@directive-run/core';
|
|
3
3
|
export { RequirementTypeStatus } from '@directive-run/core';
|
|
4
4
|
import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
|
|
5
5
|
export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
|
|
@@ -76,24 +76,24 @@ interface UseInspectOptions {
|
|
|
76
76
|
*/
|
|
77
77
|
declare function useInspect(system: SingleModuleSystem<any>, options?: UseInspectOptions): InspectState;
|
|
78
78
|
/**
|
|
79
|
-
* Reactive
|
|
79
|
+
* Reactive history hook. Returns null when history is disabled.
|
|
80
80
|
* Re-renders when snapshots are taken or navigation occurs.
|
|
81
81
|
*
|
|
82
82
|
* @example
|
|
83
83
|
* ```tsx
|
|
84
|
-
* const
|
|
85
|
-
* if (
|
|
84
|
+
* const history = useHistory(system);
|
|
85
|
+
* if (history) {
|
|
86
86
|
* return (
|
|
87
87
|
* <div>
|
|
88
|
-
* <button disabled={!
|
|
89
|
-
* <button disabled={!
|
|
90
|
-
* <span>{
|
|
88
|
+
* <button disabled={!history.canGoBack} onClick={() => history.goBack()}>Undo</button>
|
|
89
|
+
* <button disabled={!history.canGoForward} onClick={() => history.goForward()}>Redo</button>
|
|
90
|
+
* <span>{history.currentIndex + 1} / {history.totalSnapshots}</span>
|
|
91
91
|
* </div>
|
|
92
92
|
* );
|
|
93
93
|
* }
|
|
94
94
|
* ```
|
|
95
95
|
*/
|
|
96
|
-
declare function
|
|
96
|
+
declare function useHistory(system: SingleModuleSystem<any>): HistoryState | null;
|
|
97
97
|
/** Single type overload */
|
|
98
98
|
declare function useRequirementStatus(statusPlugin: StatusPlugin, type: string): RequirementTypeStatus;
|
|
99
99
|
/** Multi-type overload */
|
|
@@ -105,7 +105,8 @@ declare function useSuspenseRequirement(statusPlugin: StatusPlugin, types: strin
|
|
|
105
105
|
/** Base options for creating a scoped system */
|
|
106
106
|
interface DirectiveRefBaseConfig {
|
|
107
107
|
plugins?: Plugin<any>[];
|
|
108
|
-
|
|
108
|
+
history?: HistoryOption;
|
|
109
|
+
trace?: TraceOption;
|
|
109
110
|
errorBoundary?: ErrorBoundaryConfig;
|
|
110
111
|
tickMs?: number;
|
|
111
112
|
zeroConfig?: boolean;
|
|
@@ -274,4 +275,4 @@ declare function DirectiveHydrator({ snapshot, children }: HydratorProps): react
|
|
|
274
275
|
*/
|
|
275
276
|
declare function useHydratedSystem<S extends ModuleSchema>(moduleDef: ModuleDef<S>, config?: DirectiveRefBaseConfig): SingleModuleSystem<S>;
|
|
276
277
|
|
|
277
|
-
export { DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefNamespacedOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useRequirementStatus, useSelector, useSuspenseRequirement,
|
|
278
|
+
export { DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefNamespacedOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useHistory, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useRequirementStatus, useSelector, useSuspenseRequirement, useWatch };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {createSystem,createRequirementStatusPlugin}from'@directive-run/core';import {assertSystem,defaultEquality,runTrackedSelector,createThrottle,buildTimeTravelState,depsChanged,computeInspectState}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {createContext,useCallback,useSyncExternalStore,useRef,useMemo,useEffect,useState,useContext}from'react';import {jsx}from'react/jsx-runtime';var h=Symbol("directive.uninitialized");function Re(e,t){return assertSystem("useFact",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useFact() received a function. Did you mean useSelector()? useFact() takes a string key or array of keys, not a selector function."),Array.isArray(t)?ne(e,t):te(e,t)}function te(e,t){process.env.NODE_ENV!=="production"&&(t in e.facts.$store.toObject()||console.warn(`[Directive] useFact("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`));let r=useCallback(n=>e.facts.$store.subscribe([t],n),[e,t]),u=useCallback(()=>e.facts[t],[e,t]);return useSyncExternalStore(r,u,u)}function ne(e,t){let r=useRef(h),u=useCallback(o=>e.facts.$store.subscribe(t,o),[e,...t]),n=useCallback(()=>{let o={};for(let s of t)o[s]=e.facts[s];if(r.current!==h){let s=true;for(let i of t)if(!Object.is(r.current[i],o[i])){s=false;break}if(s)return r.current}return r.current=o,o},[e,...t]);return useSyncExternalStore(u,n,n)}function be(e,t){return assertSystem("useDerived",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useDerived() received a function. Did you mean useSelector()? useDerived() takes a string key or array of keys, not a selector function."),Array.isArray(t)?se(e,t):re(e,t)}function re(e,t){process.env.NODE_ENV!=="production"&&(t in e.derive||console.warn(`[Directive] useDerived("${t}") \u2014 derivation not found. Check that "${t}" is defined in your module's derive property.`));let r=useCallback(n=>e.subscribe([t],n),[e,t]),u=useCallback(()=>e.read(t),[e,t]);return useSyncExternalStore(r,u,u)}function se(e,t){let r=useRef(h),u=useCallback(o=>e.subscribe(t,o),[e,...t]),n=useCallback(()=>{let o={};for(let s of t)o[s]=e.read(s);if(r.current!==h){let s=true;for(let i of t)if(!Object.is(r.current[i],o[i])){s=false;break}if(s)return r.current}return r.current=o,o},[e,...t]);return useSyncExternalStore(u,n,n)}function he(e,t,r,u){if(e&&e._mode==="namespaced")return ue(e,t,r,u);let n=e,o,s=false,i=u??defaultEquality;r!==void 0&&(o=r,s=true),process.env.NODE_ENV!=="production"&&!n&&!s&&console.error("[Directive] useSelector() received a null/undefined system without a default value. Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)");let f=useRef(t),d=useRef(i),c=useRef(o);f.current=t,d.current=i,c.current=o;let g=useRef([]),v=useRef([]),M=useRef(h),y=useRef([]),x=useMemo(()=>n?new Set(Object.keys(n.derive)):new Set,[n]),R=useCallback(()=>n?runTrackedSelector(n,x,f.current):{value:c.current,factKeys:[],deriveKeys:[]},[n,x]),F=useCallback(m=>{if(!n)return ()=>{};let k=()=>{for(let S of y.current)S();y.current=[];let{factKeys:I,deriveKeys:p}=R();g.current=I,v.current=p,I.length>0?y.current.push(n.facts.$store.subscribe(I,()=>{let S=R();depsChanged(g.current,S.factKeys,v.current,S.deriveKeys)&&k(),m();})):p.length===0&&y.current.push(n.facts.$store.subscribeAll(m)),p.length>0&&y.current.push(n.subscribe(p,()=>{let S=R();depsChanged(g.current,S.factKeys,v.current,S.deriveKeys)&&k(),m();}));};return k(),()=>{for(let I of y.current)I();y.current=[];}},[n,R]),N=useCallback(()=>{let m;if(!n)m=c.current;else {let{value:k}=R();m=k===void 0&&s?c.current:k;}return M.current!==h&&d.current(M.current,m)?M.current:(M.current=m,m)},[R,n,s]);return useSyncExternalStore(F,N,N)}function ue(e,t,r,u){let n=r!==void 0,o=u??defaultEquality,s=useRef(t),i=useRef(o),f=useRef(r);s.current=t,i.current=o,f.current=r;let d=useRef(h),c=useMemo(()=>Object.keys(e.facts),[e]),g=useCallback(M=>{let y=c.map(x=>`${x}.*`);return e.subscribe(y,M)},[e,c]),v=useCallback(()=>{let M=s.current(e),y=M===void 0&&n?f.current:M;return d.current!==h&&i.current(d.current,y)?d.current:(d.current=y,y)},[e,n]);return useSyncExternalStore(g,v,v)}function Me(e){return assertSystem("useDispatch",e),useCallback(t=>{e.dispatch(t);},[e])}function De(e,t,r){assertSystem("useWatch",e);let u=useRef(r);u.current=r,useEffect(()=>e.watch(t,(n,o)=>{u.current(n,o);}),[e,t]);}function oe(e,t){assertSystem("useInspect",e);let r=ce(e),u=t?.throttleMs,[n,o]=useState(r),s=useRef(null);return useEffect(()=>{if(!u||u<=0){s.current?.cleanup(),s.current=null;return}return s.current?.cleanup(),s.current=createThrottle((...i)=>{o(i[0]);},u),()=>{s.current?.cleanup(),s.current=null;}},[u]),useEffect(()=>{s.current&&s.current.throttled(r);},[r]),!u||u<=0?r:n}function ie(e){return computeInspectState(e)}function ce(e){let t=useRef(null),r=useRef([]),u=useRef([]),n=useRef(null),o=useCallback(i=>{let f=e.facts.$store.subscribeAll(i),d=e.onSettledChange(i);return ()=>{f(),d();}},[e]),s=useCallback(()=>{let i=ie(e),f=i.unmet.length===r.current.length&&i.unmet.every((g,v)=>g.id===r.current[v]),d=i.inflight.length===u.current.length&&i.inflight.every((g,v)=>g.id===u.current[v]),c=i.isSettled===n.current;return f&&d&&c&&t.current?t.current:(t.current=i,r.current=i.unmet.map(g=>g.id),u.current=i.inflight.map(g=>g.id),n.current=i.isSettled,i)},[e]);return useSyncExternalStore(o,s,s)}function xe(e){assertSystem("useTimeTravel",e);let t=useRef(null),r=useCallback(n=>e.onTimeTravelChange(n),[e]),u=useCallback(()=>{let n=buildTimeTravelState(e);return n?(t.current&&t.current.canUndo===n.canUndo&&t.current.canRedo===n.canRedo&&t.current.currentIndex===n.currentIndex&&t.current.totalSnapshots===n.totalSnapshots&&t.current.isPaused===n.isPaused||(t.current=n),t.current):null},[e]);return useSyncExternalStore(r,u,u)}function ke(e,t){return Array.isArray(t)?le(e,t):ae(e,t)}function ae(e,t){let r=useRef(h),u=useCallback(o=>e.subscribe(o),[e]),n=useCallback(()=>{let o=e.getStatus(t);if(r.current!==h){let s=r.current;if(s.pending===o.pending&&s.inflight===o.inflight&&s.failed===o.failed&&s.isLoading===o.isLoading&&s.hasError===o.hasError&&s.lastError===o.lastError)return r.current}return r.current=o,o},[e,t]);return useSyncExternalStore(u,n,n)}function le(e,t){let r=useRef(null),u=useRef(""),n=useCallback(s=>e.subscribe(s),[e]),o=useCallback(()=>{let s={},i=[];for(let d of t){let c=e.getStatus(d);s[d]=c,i.push(`${d}:${c.pending}:${c.inflight}:${c.failed}:${c.hasError}:${c.lastError?.message??""}`);}let f=i.join("|");return f!==u.current&&(u.current=f,r.current=s),r.current??s},[e,...t]);return useSyncExternalStore(n,o,o)}var _=new WeakMap;function j(e){let t=_.get(e);return t||(t=new Map,_.set(e,t)),t}function Ie(e,t){return Array.isArray(t)?fe(e,t):de(e,t)}function de(e,t){let r=e.getStatus(t);if(r.hasError&&r.lastError)throw r.lastError;if(r.isLoading){let u=j(e),n=u.get(t);throw n||(n=new Promise(o=>{let s=e.subscribe(()=>{e.getStatus(t).isLoading||(u.delete(t),s(),o());});}),u.set(t,n)),n}return r}function fe(e,t){let r={},u=false,n=null;for(let o of t){let s=e.getStatus(o);r[o]=s,s.hasError&&s.lastError&&!n&&(n=s.lastError),s.isLoading&&(u=true);}if(n)throw n;if(u){let o=j(e),s=t.slice().sort().join(","),i=o.get(s);throw i||(i=new Promise(f=>{let d=e.subscribe(()=>{t.every(g=>!e.getStatus(g).isLoading)&&(o.delete(s),d(),f());});}),o.set(s,i)),i}return r}function V(e,t){let r=useRef(null),u=useRef(null),n=useRef(null),o=t?.status===true,s="modules"in e;return r.current||(n.current=()=>{if(s){let{modules:N,...m}=e,k=t?.plugins??m.plugins??[],I=t?.debug??m.debug,p=t?.errorBoundary??m.errorBoundary,S=t?.tickMs??m.tickMs,E=t?.zeroConfig??m.zeroConfig,q=t?.initialFacts??m.initialFacts,w=createSystem({modules:N,plugins:k.length>0?k:void 0,debug:I,errorBoundary:p,tickMs:S,zeroConfig:E,initialFacts:q});return w.initialize(),typeof window<"u"&&w.start(),w}let i="id"in e&&"schema"in e,f=i?e:e.module,d=i?{}:e,c=t?.plugins??d.plugins??[],g=t?.debug??d.debug,v=t?.errorBoundary??d.errorBoundary,M=t?.tickMs??d.tickMs,y=t?.zeroConfig??d.zeroConfig,x=t?.initialFacts??d.initialFacts,R=[...c];o&&(u.current=createRequirementStatusPlugin(),R=[...R,u.current.plugin]);let F=createSystem({module:f,plugins:R.length>0?R:void 0,debug:g,errorBoundary:v,tickMs:M,zeroConfig:y,initialFacts:x});return F.initialize(),typeof window<"u"&&F.start(),F},r.current=n.current()),useEffect(()=>(!r.current&&n.current&&(r.current=n.current()),()=>{r.current?.destroy(),r.current=null,u.current=null;}),[]),o&&!s?{system:r.current,statusPlugin:u.current}:r.current}function we(e,t,r){let u=useRef(t);u.current=t;let n=useRef(r);n.current=r;let o=useCallback(i=>e.subscribe(u.current,i),[e]),s=useCallback(()=>n.current(e),[e]);return useSyncExternalStore(o,s,s)}function Ke(e,t={}){let{facts:r,derived:u,status:n,...o}=t,s=r??[],i=u??[],f=s.length===0&&i.length===0,d=n?V(e,{status:true,...o}):V(e,o),c=n?d.system:d,g=n?d.statusPlugin:void 0,v=useMemo(()=>f?Object.keys(c.derive):[],[c,f]),M=useCallback(p=>{let S=[];return f?(S.push(c.facts.$store.subscribeAll(p)),v.length>0&&S.push(c.subscribe(v,p))):(s.length>0&&S.push(c.facts.$store.subscribe(s,p)),i.length>0&&S.push(c.subscribe(i,p))),()=>{for(let E of S)E();}},[c,f,...s,...i,...v]),y=useRef(h),x=useRef(h),R=useRef(null),F=useCallback(()=>{let p,S,E,q;if(f){p=c.facts.$store.toObject(),E=Object.keys(p),S={};for(let b of v)S[b]=c.read(b);q=v;}else {p={};for(let b of s)p[b]=c.facts[b];E=s,S={};for(let b of i)S[b]=c.read(b);q=i;}let w=y.current!==h;if(w){let b=y.current;if(Object.keys(b).length!==E.length)w=false;else for(let T of E)if(!Object.is(b[T],p[T])){w=false;break}}let C=x.current!==h;if(C){let b=x.current;if(Object.keys(b).length!==q.length)C=false;else for(let T of q)if(!Object.is(b[T],S[T])){C=false;break}}let z=w?y.current:p,W=C?x.current:S;return w||(y.current=p),C||(x.current=S),w&&C&&R.current||(R.current={facts:z,derived:W}),R.current},[c,f,...s,...i,...v]),N=useSyncExternalStore(M,F,F),m=useCallback(p=>c.dispatch(p),[c]),k=Se(c),I={system:c,dispatch:m,events:k,facts:N.facts,derived:N.derived};return n&&g?{...I,statusPlugin:g}:I}function Se(e){return assertSystem("useEvents",e),useMemo(()=>e.events,[e])}function Fe(e,t){assertSystem("useExplain",e);let r=useCallback(n=>{let o=e.facts.$store.subscribeAll(n),s=e.onSettledChange(n);return ()=>{o(),s();}},[e]),u=useCallback(()=>e.explain(t),[e,t]);return useSyncExternalStore(r,u,u)}function Ee(e,t){assertSystem("useConstraintStatus",e);let r=oe(e);return useMemo(()=>{let u=e.inspect();return t?u.constraints.find(n=>n.id===t)??null:u.constraints},[e,t,r])}function Ne(e,t,r){assertSystem("useOptimisticUpdate",e);let[u,n]=useState(false),[o,s]=useState(null),i=useRef(null),f=useCallback(()=>{i.current&&(e.restore(i.current),i.current=null),n(false),s(null);},[e]),d=useCallback(c=>{i.current=e.getSnapshot(),n(true),s(null),e.batch(c);},[e]);return useEffect(()=>{if(!(!t||!r||!u))return t.subscribe(()=>{let c=t.getStatus(r);!c.isLoading&&!c.hasError?(i.current=null,n(false)):c.hasError&&(s(c.lastError),f());})},[t,r,u,f]),{mutate:d,isPending:u,error:o,rollback:f}}var A=createContext(null);function qe({snapshot:e,children:t}){return jsx(A.Provider,{value:e,children:t})}function Ce(e,t){let r=useContext(A),u=useMemo(()=>r?.data?{...t??{},initialFacts:{...t?.initialFacts??{},...r.data}}:t??{},[r,t]);return V(e,u)}export{qe as DirectiveHydrator,Ee as useConstraintStatus,be as useDerived,Ke as useDirective,V as useDirectiveRef,Me as useDispatch,Se as useEvents,Fe as useExplain,Re as useFact,Ce as useHydratedSystem,oe as useInspect,we as useNamespacedSelector,Ne as useOptimisticUpdate,ke as useRequirementStatus,he as useSelector,Ie as useSuspenseRequirement,xe as useTimeTravel,De as useWatch};//# sourceMappingURL=index.js.map
|
|
1
|
+
import {createSystem,createRequirementStatusPlugin}from'@directive-run/core';import {assertSystem,defaultEquality,runTrackedSelector,createThrottle,buildHistoryState,depsChanged,computeInspectState}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {createContext,useCallback,useSyncExternalStore,useRef,useMemo,useEffect,useState,useContext}from'react';import {jsx}from'react/jsx-runtime';var h=Symbol("directive.uninitialized");function me(e,t){return assertSystem("useFact",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useFact() received a function. Did you mean useSelector()? useFact() takes a string key or array of keys, not a selector function."),Array.isArray(t)?ne(e,t):te(e,t)}function te(e,t){process.env.NODE_ENV!=="production"&&(t in e.facts.$store.toObject()||console.warn(`[Directive] useFact("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`));let r=useCallback(n=>e.facts.$store.subscribe([t],n),[e,t]),o=useCallback(()=>e.facts.$store.get(t),[e,t]);return useSyncExternalStore(r,o,o)}function ne(e,t){let r=useRef(h),o=useCallback(u=>e.facts.$store.subscribe(t,u),[e,...t]),n=useCallback(()=>{let u={};for(let s of t)u[s]=e.facts.$store.get(s);if(r.current!==h){let s=true;for(let i of t)if(!Object.is(r.current[i],u[i])){s=false;break}if(s)return r.current}return r.current=u,u},[e,...t]);return useSyncExternalStore(o,n,n)}function he(e,t){return assertSystem("useDerived",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useDerived() received a function. Did you mean useSelector()? useDerived() takes a string key or array of keys, not a selector function."),Array.isArray(t)?se(e,t):re(e,t)}function re(e,t){process.env.NODE_ENV!=="production"&&(t in e.derive||console.warn(`[Directive] useDerived("${t}") \u2014 derivation not found. Check that "${t}" is defined in your module's derive property.`));let r=useCallback(n=>e.subscribe([t],n),[e,t]),o=useCallback(()=>e.read(t),[e,t]);return useSyncExternalStore(r,o,o)}function se(e,t){let r=useRef(h),o=useCallback(u=>e.subscribe(t,u),[e,...t]),n=useCallback(()=>{let u={};for(let s of t)u[s]=e.read(s);if(r.current!==h){let s=true;for(let i of t)if(!Object.is(r.current[i],u[i])){s=false;break}if(s)return r.current}return r.current=u,u},[e,...t]);return useSyncExternalStore(o,n,n)}function be(e,t,r,o){if(e&&e._mode==="namespaced")return oe(e,t,r,o);let n=e,u,s=false,i=o??defaultEquality;r!==void 0&&(u=r,s=true),process.env.NODE_ENV!=="production"&&!n&&!s&&console.error("[Directive] useSelector() received a null/undefined system without a default value. Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)");let f=useRef(t),l=useRef(i),c=useRef(u);f.current=t,l.current=i,c.current=u;let g=useRef([]),v=useRef([]),b=useRef(h),y=useRef([]),k=useMemo(()=>n?new Set(Object.keys(n.derive)):new Set,[n]),M=useCallback(()=>n?runTrackedSelector(n,k,f.current):{value:c.current,factKeys:[],deriveKeys:[]},[n,k]),K=useCallback(D=>{if(!n)return ()=>{};let R=()=>{for(let S of y.current)S();y.current=[];let{factKeys:I,deriveKeys:p}=M();g.current=I,v.current=p,I.length>0?y.current.push(n.facts.$store.subscribe(I,()=>{let S=M();depsChanged(g.current,S.factKeys,v.current,S.deriveKeys)&&R(),D();})):p.length===0&&y.current.push(n.facts.$store.subscribeAll(D)),p.length>0&&y.current.push(n.subscribe(p,()=>{let S=M();depsChanged(g.current,S.factKeys,v.current,S.deriveKeys)&&R(),D();}));};return R(),()=>{for(let I of y.current)I();y.current=[];}},[n,M]),F=useCallback(()=>{let D;if(!n)D=c.current;else {let{value:R}=M();D=R===void 0&&s?c.current:R;}return b.current!==h&&l.current(b.current,D)?b.current:(b.current=D,D)},[M,n,s]);return useSyncExternalStore(K,F,F)}function oe(e,t,r,o){let n=r!==void 0,u=o??defaultEquality,s=useRef(t),i=useRef(u),f=useRef(r);s.current=t,i.current=u,f.current=r;let l=useRef(h),c=useMemo(()=>Object.keys(e.facts),[e]),g=useCallback(b=>{let y=c.map(k=>`${k}.*`);return e.subscribe(y,b)},[e,c]),v=useCallback(()=>{let b=s.current(e),y=b===void 0&&n?f.current:b;return l.current!==h&&i.current(l.current,y)?l.current:(l.current=y,y)},[e,n]);return useSyncExternalStore(g,v,v)}function Me(e){return assertSystem("useDispatch",e),useCallback(t=>{e.dispatch(t);},[e])}function De(e,t,r){assertSystem("useWatch",e);let o=useRef(r);o.current=r,useEffect(()=>e.watch(t,(n,u)=>{o.current(n,u);}),[e,t]);}function ue(e,t){assertSystem("useInspect",e);let r=ce(e),o=t?.throttleMs,[n,u]=useState(r),s=useRef(null);return useEffect(()=>{if(!o||o<=0){s.current?.cleanup(),s.current=null;return}return s.current?.cleanup(),s.current=createThrottle((...i)=>{u(i[0]);},o),()=>{s.current?.cleanup(),s.current=null;}},[o]),useEffect(()=>{s.current&&s.current.throttled(r);},[r]),!o||o<=0?r:n}function ie(e){return computeInspectState(e)}function ce(e){let t=useRef(null),r=useRef([]),o=useRef([]),n=useRef(null),u=useCallback(i=>{let f=e.facts.$store.subscribeAll(i),l=e.onSettledChange(i);return ()=>{f(),l();}},[e]),s=useCallback(()=>{let i=ie(e),f=i.unmet.length===r.current.length&&i.unmet.every((g,v)=>g.id===r.current[v]),l=i.inflight.length===o.current.length&&i.inflight.every((g,v)=>g.id===o.current[v]),c=i.isSettled===n.current;return f&&l&&c&&t.current?t.current:(t.current=i,r.current=i.unmet.map(g=>g.id),o.current=i.inflight.map(g=>g.id),n.current=i.isSettled,i)},[e]);return useSyncExternalStore(u,s,s)}function xe(e){assertSystem("useHistory",e);let t=useRef(null),r=useCallback(n=>e.onHistoryChange(n),[e]),o=useCallback(()=>{let n=buildHistoryState(e);return n?(t.current&&t.current.canGoBack===n.canGoBack&&t.current.canGoForward===n.canGoForward&&t.current.currentIndex===n.currentIndex&&t.current.totalSnapshots===n.totalSnapshots&&t.current.isPaused===n.isPaused||(t.current=n),t.current):null},[e]);return useSyncExternalStore(r,o,o)}function ke(e,t){return Array.isArray(t)?le(e,t):ae(e,t)}function ae(e,t){let r=useRef(h),o=useCallback(u=>e.subscribe(u),[e]),n=useCallback(()=>{let u=e.getStatus(t);if(r.current!==h){let s=r.current;if(s.pending===u.pending&&s.inflight===u.inflight&&s.failed===u.failed&&s.isLoading===u.isLoading&&s.hasError===u.hasError&&s.lastError===u.lastError)return r.current}return r.current=u,u},[e,t]);return useSyncExternalStore(o,n,n)}function le(e,t){let r=useRef(null),o=useRef(""),n=useCallback(s=>e.subscribe(s),[e]),u=useCallback(()=>{let s={},i=[];for(let l of t){let c=e.getStatus(l);s[l]=c,i.push(`${l}:${c.pending}:${c.inflight}:${c.failed}:${c.hasError}:${c.lastError?.message??""}`);}let f=i.join("|");return f!==o.current&&(o.current=f,r.current=s),r.current??s},[e,...t]);return useSyncExternalStore(n,u,u)}var H=new WeakMap;function j(e){let t=H.get(e);return t||(t=new Map,H.set(e,t)),t}function Ie(e,t){return Array.isArray(t)?fe(e,t):de(e,t)}function de(e,t){let r=e.getStatus(t);if(r.hasError&&r.lastError)throw r.lastError;if(r.isLoading){let o=j(e),n=o.get(t);throw n||(n=new Promise(u=>{let s=e.subscribe(()=>{e.getStatus(t).isLoading||(o.delete(t),s(),u());});}),o.set(t,n)),n}return r}function fe(e,t){let r={},o=false,n=null;for(let u of t){let s=e.getStatus(u);r[u]=s,s.hasError&&s.lastError&&!n&&(n=s.lastError),s.isLoading&&(o=true);}if(n)throw n;if(o){let u=j(e),s=t.slice().sort().join(","),i=u.get(s);throw i||(i=new Promise(f=>{let l=e.subscribe(()=>{t.every(g=>!e.getStatus(g).isLoading)&&(u.delete(s),l(),f());});}),u.set(s,i)),i}return r}function $(e,t){let r=useRef(null),o=useRef(null),n=useRef(null),u=t?.status===true,s="modules"in e;return r.current||(n.current=()=>{if(s){let{modules:D,...R}=e,I=t?.plugins??R.plugins??[],p=t?.history??R.history,S=t?.trace??R.trace,E=t?.errorBoundary??R.errorBoundary,P=t?.tickMs??R.tickMs,N=t?.zeroConfig??R.zeroConfig,q=t?.initialFacts??R.initialFacts,U=createSystem({modules:D,plugins:I.length>0?I:void 0,history:p,trace:S,errorBoundary:E,tickMs:P,zeroConfig:N,initialFacts:q});return U.initialize(),typeof window<"u"&&U.start(),U}let i="id"in e&&"schema"in e,f=i?e:e.module,l=i?{}:e,c=t?.plugins??l.plugins??[],g=t?.history??l.history,v=t?.trace??l.trace,b=t?.errorBoundary??l.errorBoundary,y=t?.tickMs??l.tickMs,k=t?.zeroConfig??l.zeroConfig,M=t?.initialFacts??l.initialFacts,K=[...c];u&&(o.current=createRequirementStatusPlugin(),K=[...K,o.current.plugin]);let F=createSystem({module:f,plugins:K.length>0?K:void 0,history:g,trace:v,errorBoundary:b,tickMs:y,zeroConfig:k,initialFacts:M});return F.initialize(),typeof window<"u"&&F.start(),F},r.current=n.current()),useEffect(()=>(!r.current&&n.current&&(r.current=n.current()),()=>{r.current?.destroy(),r.current=null,o.current=null;}),[]),u&&!s?{system:r.current,statusPlugin:o.current}:r.current}function we(e,t,r){let o=useRef(t);o.current=t;let n=useRef(r);n.current=r;let u=useCallback(i=>e.subscribe(o.current,i),[e]),s=useCallback(()=>n.current(e),[e]);return useSyncExternalStore(u,s,s)}function Ke(e,t={}){let{facts:r,derived:o,status:n,...u}=t,s=r??[],i=o??[],f=s.length===0&&i.length===0,l=n?$(e,{status:true,...u}):$(e,u),c=n?l.system:l,g=n?l.statusPlugin:void 0,v=useMemo(()=>f?Object.keys(c.derive):[],[c,f]),b=useCallback(p=>{let S=[];return f?(S.push(c.facts.$store.subscribeAll(p)),v.length>0&&S.push(c.subscribe(v,p))):(s.length>0&&S.push(c.facts.$store.subscribe(s,p)),i.length>0&&S.push(c.subscribe(i,p))),()=>{for(let E of S)E();}},[c,f,...s,...i,...v]),y=useRef(h),k=useRef(h),M=useRef(null),K=useCallback(()=>{let p,S,E,P;if(f){p=c.facts.$store.toObject(),E=Object.keys(p),S={};for(let m of v)S[m]=c.read(m);P=v;}else {p={};for(let m of s)p[m]=c.facts[m];E=s,S={};for(let m of i)S[m]=c.read(m);P=i;}let N=y.current!==h;if(N){let m=y.current;if(Object.keys(m).length!==E.length)N=false;else for(let O of E)if(!Object.is(m[O],p[O])){N=false;break}}let q=k.current!==h;if(q){let m=k.current;if(Object.keys(m).length!==P.length)q=false;else for(let O of P)if(!Object.is(m[O],S[O])){q=false;break}}let U=N?y.current:p,z=q?k.current:S;return N||(y.current=p),q||(k.current=S),N&&q&&M.current||(M.current={facts:U,derived:z}),M.current},[c,f,...s,...i,...v]),F=useSyncExternalStore(b,K,K),D=useCallback(p=>c.dispatch(p),[c]),R=Se(c),I={system:c,dispatch:D,events:R,facts:F.facts,derived:F.derived};return n&&g?{...I,statusPlugin:g}:I}function Se(e){return assertSystem("useEvents",e),useMemo(()=>e.events,[e])}function Fe(e,t){assertSystem("useExplain",e);let r=useCallback(n=>{let u=e.facts.$store.subscribeAll(n),s=e.onSettledChange(n);return ()=>{u(),s();}},[e]),o=useCallback(()=>e.explain(t),[e,t]);return useSyncExternalStore(r,o,o)}function Ee(e,t){assertSystem("useConstraintStatus",e);let r=ue(e);return useMemo(()=>{let o=e.inspect();return t?o.constraints.find(n=>n.id===t)??null:o.constraints},[e,t,r])}function Ne(e,t,r){assertSystem("useOptimisticUpdate",e);let[o,n]=useState(false),[u,s]=useState(null),i=useRef(null),f=useCallback(()=>{i.current&&(e.restore(i.current),i.current=null),n(false),s(null);},[e]),l=useCallback(c=>{i.current=e.getSnapshot(),n(true),s(null),e.batch(c);},[e]);return useEffect(()=>{if(!(!t||!r||!o))return t.subscribe(()=>{let c=t.getStatus(r);!c.isLoading&&!c.hasError?(i.current=null,n(false)):c.hasError&&(s(c.lastError),f());})},[t,r,o,f]),{mutate:l,isPending:o,error:u,rollback:f}}var A=createContext(null);function qe({snapshot:e,children:t}){return jsx(A.Provider,{value:e,children:t})}function Pe(e,t){let r=useContext(A),o=useMemo(()=>r?.data?{...t??{},initialFacts:{...t?.initialFacts??{},...r.data}}:t??{},[r,t]);return $(e,o)}export{qe as DirectiveHydrator,Ee as useConstraintStatus,he as useDerived,Ke as useDirective,$ as useDirectiveRef,Me as useDispatch,Se as useEvents,Fe as useExplain,me as useFact,xe as useHistory,Pe as useHydratedSystem,ue as useInspect,we as useNamespacedSelector,Ne as useOptimisticUpdate,ke as useRequirementStatus,be as useSelector,Ie as useSuspenseRequirement,De as useWatch};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.tsx"],"names":["UNINITIALIZED","useFact","system","keyOrKeys","assertSystem","_useFacts","_useSingleFact","factKey","subscribe","useCallback","onStoreChange","getSnapshot","useSyncExternalStore","factKeys","cachedValue","useRef","result","key","same","useDerived","_useDerivedMulti","_useSingleDerived","derivationId","derivationIds","id","useSelector","systemArg","selector","defaultValueArg","equalityFnArg","_useNamespacedSelectorImpl","defaultValue","hasDefault","equalityFn","defaultEquality","selectorRef","eqRef","defaultValueRef","trackedFactKeysRef","trackedDeriveKeysRef","unsubsRef","deriveKeys","useMemo","runWithTracking","runTrackedSelector","resubscribe","unsub","derivedKeys","updated","depsChanged","effectiveValue","newValue","moduleNames","wildcardKeys","ns","useDispatch","event","useWatch","callback","callbackRef","useEffect","prevValue","useInspect","options","syncState","_useInspectSync","throttleMs","deferredState","setDeferredState","useState","throttleRef","createThrottle","args","_buildInspectState","computeInspectState","cachedSnapshot","cachedUnmetIds","cachedInflightIds","cachedIsSettled","unsubFacts","unsubSettled","state","unmetSame","u","i","inflightSame","f","settledSame","useTimeTravel","cachedRef","buildTimeTravelState","useRequirementStatus","statusPlugin","typeOrTypes","_useRequirementStatusMulti","_useRequirementStatusSingle","type","status","prev","types","cachedKey","parts","suspenseCacheMap","getSuspenseCache","plugin","cache","useSuspenseRequirement","_useSuspenseRequirementMulti","_useSuspenseRequirementSingle","promise","resolve","unsubscribe","hasLoading","firstError","cacheKey","t","useDirectiveRef","config","systemRef","statusPluginRef","factoryRef","wantStatus","isNamespaced","modules","rest","plugins","debug","errorBoundary","tickMs","zeroConfig","initialFacts","sys","createSystem","isModule","mod","baseOpts","allPlugins","createRequirementStatusPlugin","useNamespacedSelector","keys","keysRef","useDirective","moduleOrOptions","selections","factKeysOpt","derivedKeysOpt","configRest","subscribeAll","refResult","allDerivationKeys","unsubs","cachedFacts","cachedDerived","cachedWrapper","factsResult","derivedResult","effectiveFactKeys","effectiveDerivedKeys","factsSame","derivedSame","stableFacts","stableDerived","values","dispatch","events","useEvents","base","useExplain","requirementId","useConstraintStatus","constraintId","inspectState","inspection","c","useOptimisticUpdate","requirementType","isPending","setIsPending","error","setError","snapshotRef","rollback","mutate","updateFn","HydrationContext","createContext","DirectiveHydrator","snapshot","children","jsx","useHydratedSystem","moduleDef","useContext","mergedConfig"],"mappings":"icA0FA,IAAMA,CAAAA,CAAgB,OAAO,yBAAyB,CAAA,CAmB/C,SAASC,EAAAA,CAEdC,CAAAA,CACAC,CAAAA,CACS,CAaT,OAZAC,YAAAA,CAAa,SAAA,CAAWF,CAAM,CAAA,CAE5B,OAAA,CAAQ,IAAI,QAAA,GAAa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S,EAAevJ,OAAAA,CAAQ,IACtBiJ,CAAAA,EAAU,IAAA,CACR,CACL,GAAItE,CAAAA,EAAU,EAAC,CACf,YAAA,CAAc,CACZ,GAAIA,CAAAA,EAAQ,YAAA,EAAgB,GAC5B,GAAGsE,CAAAA,CAAS,IACd,CACF,CAAA,CAP4BtE,GAAU,EAAC,CAQtC,CAACsE,CAAAA,CAAUtE,CAAM,CAAC,CAAA,CAErB,OAAOD,CAAAA,CAAgB2E,CAAAA,CAAWE,CAAY,CAChD","file":"index.js","sourcesContent":["/**\n * React Adapter - Consolidated hooks for React integration\n *\n * 18 public exports: useFact, useDerived, useDispatch, useDirective,\n * useDirectiveRef, useSelector, useWatch, useInspect, useRequirementStatus,\n * useSuspenseRequirement, useEvents, useExplain, useConstraintStatus,\n * useOptimisticUpdate, DirectiveHydrator, useHydratedSystem,\n * useTimeTravel, shallowEqual\n *\n * @example\n * ```tsx\n * import { useFact, useDerived, useEvents } from '@directive-run/react';\n *\n * const system = createSystem({ module: counterModule });\n * system.start();\n *\n * function Counter() {\n * const count = useFact(system, \"count\");\n * const doubled = useDerived(system, \"doubled\");\n * const events = useEvents(system);\n *\n * return (\n * <div>\n * <p>Count: {count}</p>\n * <p>Doubled: {doubled}</p>\n * <button onClick={() => events.increment()}>+</button>\n * </div>\n * );\n * }\n * ```\n */\n\nimport type {\n DebugConfig,\n DistributableSnapshot,\n ErrorBoundaryConfig,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemSnapshot,\n TimeTravelState,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildTimeTravelState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport type { ReactNode } from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/** Sentinel value for uninitialized selector cache */\nconst UNINITIALIZED = Symbol(\"directive.uninitialized\");\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;\n\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;\n\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFacts(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return _useSingleFact(system, keyOrKeys);\n}\n\nfunction _useSingleFact(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKey: string,\n): unknown {\n if (process.env.NODE_ENV !== \"production\") {\n if (!(factKey in system.facts.$store.toObject())) {\n console.warn(\n `[Directive] useFact(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe([factKey], onStoreChange);\n },\n [system, factKey],\n );\n\n const getSnapshot = useCallback(() => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n return (system.facts as any)[factKey];\n }, [system, factKey]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useFacts(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe(factKeys, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...factKeys],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n result[key] = (system.facts as any)[key];\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const key of factKeys) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[key],\n result[key],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...factKeys]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];\n\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Pick<InferDerivations<S>, K>;\n\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useDerived\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(keyOrKeys)) {\n return _useDerivedMulti(system, keyOrKeys);\n }\n\n // Single key path\n return _useSingleDerived(system, keyOrKeys);\n}\n\nfunction _useSingleDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationId: string,\n): unknown {\n if (process.env.NODE_ENV !== \"production\") {\n if (!(derivationId in system.derive)) {\n console.warn(\n `[Directive] useDerived(\"${derivationId}\") — derivation not found. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe([derivationId], onStoreChange);\n },\n [system, derivationId],\n );\n\n const getSnapshot = useCallback(() => {\n return system.read(derivationId);\n }, [system, derivationId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useDerivedMulti(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe(derivationIds, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...derivationIds],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const id of derivationIds) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[id],\n result[id],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...derivationIds]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSelector — Zustand-style selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations (Zustand-style).\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys. Falls back to subscribeAll\n * if no keys are detected.\n *\n * Supports an optional default value as the 3rd parameter, used when\n * the system is null/undefined or the selector returns undefined.\n * When a default value is provided, the system parameter may be\n * null | undefined — the hook returns the default and recomputes\n * when the system becomes available.\n *\n * An optional equality function can be passed as the 4th parameter\n * to customize when the selector result is considered \"changed\".\n * Defaults to `Object.is`. Use `shallowEqual` (exported from this\n * package) when your selector returns a new object/array each time.\n *\n * @example\n * ```tsx\n * // Basic usage\n * const count = useSelector(system, (s) => s.count);\n *\n * // With default value (allows nullable system)\n * const count = useSelector(system, (s) => s.count, 0);\n *\n * // With default value + custom equality\n * const coords = useSelector(system, (s) => ({ x: s.x, y: s.y }), { x: 0, y: 0 }, shallowEqual);\n * ```\n */\n\n// Non-null system, no default\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n): R;\n\n// Non-null system, with default value and optional equality\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable system, default REQUIRED\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S> | null | undefined,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Namespaced system overloads ---\n\n// Namespaced system, no default\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n): R;\n\n// Namespaced system, with default value and optional equality\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable namespaced system, default REQUIRED\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules> | null | undefined,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Generic fallbacks ---\n\n// Generic fallback: non-null system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue?: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Generic fallback: nullable system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature accepts both system types\n systemArg: SingleModuleSystem<any> | NamespacedSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n // Route to namespaced implementation if system is a NamespacedSystem\n // biome-ignore lint/suspicious/noExplicitAny: Runtime type check\n if (systemArg && (systemArg as any)._mode === \"namespaced\") {\n // biome-ignore lint/suspicious/noExplicitAny: Delegate to namespaced impl\n return _useNamespacedSelectorImpl(\n systemArg as NamespacedSystem<any>,\n selector,\n defaultValueArg,\n equalityFnArg,\n );\n }\n\n // After the namespaced check, system is a SingleModuleSystem\n const system = systemArg as SingleModuleSystem<any> | null | undefined;\n let defaultValue: unknown;\n let hasDefault = false;\n const equalityFn: (a: unknown, b: unknown) => boolean =\n equalityFnArg ?? defaultEquality;\n\n if (defaultValueArg !== undefined) {\n defaultValue = defaultValueArg;\n hasDefault = true;\n }\n\n // Dev-mode warning: null system without a default value\n if (process.env.NODE_ENV !== \"production\") {\n if (!system && !hasDefault) {\n console.error(\n \"[Directive] useSelector() received a null/undefined system without a default value. \" +\n \"Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)\",\n );\n }\n }\n\n // Store selector/eq/default in refs to avoid resubscription churn\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValue);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValue;\n\n const trackedFactKeysRef = useRef<string[]>([]);\n const trackedDeriveKeysRef = useRef<string[]>([]);\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n const unsubsRef = useRef<Array<() => void>>([]);\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const deriveKeys = useMemo(\n () => (system ? new Set(Object.keys(system.derive)) : new Set<string>()),\n [system],\n );\n\n const runWithTracking = useCallback(() => {\n if (!system) {\n return {\n value: defaultValueRef.current,\n factKeys: [] as string[],\n deriveKeys: [] as string[],\n };\n }\n\n return runTrackedSelector(system, deriveKeys, selectorRef.current);\n }, [system, deriveKeys]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!system) {\n // No system — return noop unsubscribe\n return () => {};\n }\n\n const resubscribe = () => {\n // Cleanup previous subscriptions\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n\n // Run selector with tracking to detect accessed keys\n const { factKeys, deriveKeys: derivedKeys } = runWithTracking();\n trackedFactKeysRef.current = factKeys;\n trackedDeriveKeysRef.current = derivedKeys;\n\n // Subscribe to accessed fact keys\n if (factKeys.length > 0) {\n unsubsRef.current.push(\n system.facts.$store.subscribe(factKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n } else if (derivedKeys.length === 0) {\n // No deps at all — subscribe to everything\n unsubsRef.current.push(\n system.facts.$store.subscribeAll(onStoreChange),\n );\n }\n\n // Subscribe to accessed derivation keys\n if (derivedKeys.length > 0) {\n unsubsRef.current.push(\n system.subscribe(derivedKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n };\n },\n [system, runWithTracking],\n );\n\n const getSnapshot = useCallback(() => {\n let effectiveValue: unknown;\n\n if (!system) {\n effectiveValue = defaultValueRef.current;\n } else {\n const { value: newValue } = runWithTracking();\n\n // When selector returns undefined and we have a default, use it\n effectiveValue =\n newValue === undefined && hasDefault\n ? defaultValueRef.current\n : newValue;\n }\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [runWithTracking, system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// _useNamespacedSelectorImpl — internal namespaced useSelector\n// ============================================================================\n\n/**\n * Internal implementation for useSelector with NamespacedSystem.\n * Subscribes to all module namespaces and runs the selector against the system.\n * Uses equality comparison to prevent unnecessary re-renders.\n */\nfunction _useNamespacedSelectorImpl(\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n system: NamespacedSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n const hasDefault = defaultValueArg !== undefined;\n const equalityFn = equalityFnArg ?? defaultEquality;\n\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValueArg);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValueArg;\n\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n\n // Get all module namespace names for wildcard subscription\n const moduleNames = useMemo(() => Object.keys(system.facts), [system]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n // Subscribe to all modules using wildcard keys\n const wildcardKeys = moduleNames.map((ns) => `${ns}.*`);\n\n return system.subscribe(wildcardKeys, onStoreChange);\n },\n [system, moduleNames],\n );\n\n const getSnapshot = useCallback(() => {\n const newValue = selectorRef.current(system);\n const effectiveValue =\n newValue === undefined && hasDefault ? defaultValueRef.current : newValue;\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return useCallback(\n (event: InferEvents<S>) => {\n system.dispatch(event);\n },\n [system],\n );\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect (no re-render)\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n prevValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n prevValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n callback: (newValue: any, prevValue: any) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n useEffect(() => {\n return system.watch(key, (newValue, prevValue) => {\n callbackRef.current(newValue, prevValue);\n });\n }, [system, key]);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n// InspectState is imported from ./shared.js and re-exported above\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n /** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */\n throttleMs?: number;\n}\n\n/**\n * Hook to get consolidated system inspection data reactively.\n *\n * Merges isSettled, unmet/inflight requirements, and working state\n * into a single subscription. Optionally throttle updates.\n *\n * @example\n * ```tsx\n * const { isSettled, isWorking, hasUnmet } = useInspect(system);\n * const throttled = useInspect(system, { throttleMs: 200 });\n * ```\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): InspectState {\n assertSystem(\"useInspect\", system);\n // Always call the sync version (useSyncExternalStore path) — no conditional hooks\n const syncState = _useInspectSync(system);\n\n const throttleMs = options?.throttleMs;\n const [deferredState, setDeferredState] = useState(syncState);\n const throttleRef = useRef<{\n throttled: (...args: unknown[]) => void;\n cleanup: () => void;\n } | null>(null);\n\n // Create/recreate throttle when throttleMs changes\n useEffect(() => {\n if (!throttleMs || throttleMs <= 0) {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n return;\n }\n // Clean up old throttle before creating new one\n throttleRef.current?.cleanup();\n throttleRef.current = createThrottle((...args: unknown[]) => {\n setDeferredState(args[0] as InspectState);\n }, throttleMs);\n return () => {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n };\n }, [throttleMs]);\n\n // Feed sync state through throttle after each render\n useEffect(() => {\n if (throttleRef.current) {\n throttleRef.current.throttled(syncState);\n }\n }, [syncState]);\n\n if (!throttleMs || throttleMs <= 0) return syncState;\n return deferredState;\n}\n\nfunction _buildInspectState(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n return computeInspectState(system);\n}\n\nfunction _useInspectSync(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n const cachedSnapshot = useRef<InspectState | null>(null);\n const cachedUnmetIds = useRef<string[]>([]);\n const cachedInflightIds = useRef<string[]>([]);\n const cachedIsSettled = useRef<boolean | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = _buildInspectState(system);\n\n const unmetSame =\n state.unmet.length === cachedUnmetIds.current.length &&\n state.unmet.every((u, i) => u.id === cachedUnmetIds.current[i]);\n const inflightSame =\n state.inflight.length === cachedInflightIds.current.length &&\n state.inflight.every((f, i) => f.id === cachedInflightIds.current[i]);\n const settledSame = state.isSettled === cachedIsSettled.current;\n\n if (unmetSame && inflightSame && settledSame && cachedSnapshot.current) {\n return cachedSnapshot.current;\n }\n\n cachedSnapshot.current = state;\n cachedUnmetIds.current = state.unmet.map((u) => u.id);\n cachedInflightIds.current = state.inflight.map((f) => f.id);\n cachedIsSettled.current = state.isSettled;\n\n return state;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useTimeTravel — reactive time-travel state\n// ============================================================================\n\n/**\n * Reactive time-travel hook. Returns null when time-travel is disabled.\n * Re-renders when snapshots are taken or navigation occurs.\n *\n * @example\n * ```tsx\n * const tt = useTimeTravel(system);\n * if (tt) {\n * return (\n * <div>\n * <button disabled={!tt.canUndo} onClick={tt.undo}>Undo</button>\n * <button disabled={!tt.canRedo} onClick={tt.redo}>Redo</button>\n * <span>{tt.currentIndex + 1} / {tt.totalSnapshots}</span>\n * </div>\n * );\n * }\n * ```\n */\nexport function useTimeTravel(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): TimeTravelState | null {\n assertSystem(\"useTimeTravel\", system);\n const cachedRef = useRef<TimeTravelState | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => system.onTimeTravelChange(onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = buildTimeTravelState(system);\n if (!state) return null;\n\n // Return stable reference when values haven't changed\n if (\n cachedRef.current &&\n cachedRef.current.canUndo === state.canUndo &&\n cachedRef.current.canRedo === state.canRedo &&\n cachedRef.current.currentIndex === state.currentIndex &&\n cachedRef.current.totalSnapshots === state.totalSnapshots &&\n cachedRef.current.isPaused === state.isPaused\n ) {\n return cachedRef.current;\n }\n\n cachedRef.current = state;\n return cachedRef.current;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useRequirementStatusMulti(statusPlugin, typeOrTypes);\n }\n return _useRequirementStatusSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useRequirementStatusSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const cachedRef = useRef<RequirementTypeStatus | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const status = statusPlugin.getStatus(type);\n\n if (cachedRef.current !== UNINITIALIZED) {\n const prev = cachedRef.current;\n if (\n prev.pending === status.pending &&\n prev.inflight === status.inflight &&\n prev.failed === status.failed &&\n prev.isLoading === status.isLoading &&\n prev.hasError === status.hasError &&\n prev.lastError === status.lastError\n ) {\n return cachedRef.current;\n }\n }\n\n cachedRef.current = status;\n return status;\n }, [statusPlugin, type]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useRequirementStatusMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const cachedRef = useRef<Record<string, RequirementTypeStatus> | null>(null);\n const cachedKey = useRef<string>(\"\");\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, RequirementTypeStatus> = {};\n const parts: string[] = [];\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n parts.push(\n `${type}:${status.pending}:${status.inflight}:${status.failed}:${status.hasError}:${status.lastError?.message ?? \"\"}`,\n );\n }\n const key = parts.join(\"|\");\n\n if (key !== cachedKey.current) {\n cachedKey.current = key;\n cachedRef.current = result;\n }\n\n return cachedRef.current ?? result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [statusPlugin, ...types]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSuspenseRequirement — single or multi\n// ============================================================================\n\n// Cache for pending promises, scoped per statusPlugin to prevent cross-system leaks.\nconst suspenseCacheMap = new WeakMap<\n StatusPlugin,\n Map<string, Promise<void>>\n>();\n\nfunction getSuspenseCache(plugin: StatusPlugin): Map<string, Promise<void>> {\n let cache = suspenseCacheMap.get(plugin);\n if (!cache) {\n cache = new Map();\n suspenseCacheMap.set(plugin, cache);\n }\n return cache;\n}\n\n/** Single type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useSuspenseRequirementMulti(statusPlugin, typeOrTypes);\n }\n return _useSuspenseRequirementSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useSuspenseRequirementSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const status = statusPlugin.getStatus(type);\n\n if (status.hasError && status.lastError) {\n throw status.lastError;\n }\n\n if (status.isLoading) {\n const cache = getSuspenseCache(statusPlugin);\n let promise = cache.get(type);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const currentStatus = statusPlugin.getStatus(type);\n if (!currentStatus.isLoading) {\n cache.delete(type);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(type, promise);\n }\n\n throw promise;\n }\n\n return status;\n}\n\nfunction _useSuspenseRequirementMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const result: Record<string, RequirementTypeStatus> = {};\n let hasLoading = false;\n let firstError: Error | null = null;\n\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n\n if (status.hasError && status.lastError && !firstError) {\n firstError = status.lastError;\n }\n if (status.isLoading) {\n hasLoading = true;\n }\n }\n\n if (firstError) {\n throw firstError;\n }\n\n if (hasLoading) {\n const cache = getSuspenseCache(statusPlugin);\n const cacheKey = types.slice().sort().join(\",\");\n let promise = cache.get(cacheKey);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const allDone = types.every(\n (t) => !statusPlugin.getStatus(t).isLoading,\n );\n if (allDone) {\n cache.delete(cacheKey);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(cacheKey, promise);\n }\n\n throw promise;\n }\n\n return result;\n}\n\n// ============================================================================\n// useDirectiveRef — scoped system lifecycle\n// ============================================================================\n\n/** Base options for creating a scoped system */\ninterface DirectiveRefBaseConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n debug?: DebugConfig;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n}\n\n/** Options for useDirectiveRef: module directly, or config object */\nexport type UseDirectiveRefOptions<M extends ModuleSchema> =\n | ModuleDef<M>\n | (DirectiveRefBaseConfig & { module: ModuleDef<M> });\n\n/** Options for useDirectiveRef with namespaced modules */\nexport type UseDirectiveRefNamespacedOptions<Modules extends ModulesMap> =\n DirectiveRefBaseConfig & { modules: { [K in keyof Modules]: Modules[K] } };\n\n// --- Single-module overloads ---\n\n/** Without status (no config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n): SingleModuleSystem<M>;\n\n/** Without status (with config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: DirectiveRefBaseConfig,\n): SingleModuleSystem<M>;\n\n/** With status: returns { system, statusPlugin } */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: { status: true } & DirectiveRefBaseConfig,\n): { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin };\n\n// --- Namespaced (multi-module) overloads ---\n\n/** Namespaced: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n): NamespacedSystem<Modules>;\n\n/** Namespaced with config: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n config: DirectiveRefBaseConfig,\n): NamespacedSystem<Modules>;\n\n/** Implementation */\nexport function useDirectiveRef(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature handles both modes\n options: any,\n config?: { status?: boolean } & DirectiveRefBaseConfig,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation return varies by overload\n): any {\n // biome-ignore lint/suspicious/noExplicitAny: System ref holds either system type\n const systemRef = useRef<any>(null);\n const statusPluginRef = useRef<StatusPlugin | null>(null);\n // Factory ref for strict mode re-creation (effects unmount then re-mount)\n // biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\n const factoryRef = useRef<(() => any) | null>(null);\n const wantStatus = config?.status === true;\n const isNamespaced = \"modules\" in options;\n\n if (!systemRef.current) {\n // Build a factory that creates + starts the system.\n // Called once during render and again on strict-mode re-mount.\n factoryRef.current = () => {\n if (isNamespaced) {\n // --- Namespaced mode: { modules: { ... } } ---\n const { modules, ...rest } = options;\n const plugins = config?.plugins ?? rest.plugins ?? [];\n const debug = config?.debug ?? rest.debug;\n const errorBoundary = config?.errorBoundary ?? rest.errorBoundary;\n const tickMs = config?.tickMs ?? rest.tickMs;\n const zeroConfig = config?.zeroConfig ?? rest.zeroConfig;\n const initialFacts = config?.initialFacts ?? rest.initialFacts;\n\n const sys = createSystem({\n modules,\n plugins: plugins.length > 0 ? plugins : undefined,\n debug,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n }\n\n // --- Single-module mode ---\n const isModule = \"id\" in options && \"schema\" in options;\n const mod = isModule ? options : options.module;\n const baseOpts = isModule ? {} : (options as DirectiveRefBaseConfig);\n const plugins = config?.plugins ?? baseOpts.plugins ?? [];\n const debug = config?.debug ?? baseOpts.debug;\n const errorBoundary = config?.errorBoundary ?? baseOpts.errorBoundary;\n const tickMs = config?.tickMs ?? baseOpts.tickMs;\n const zeroConfig = config?.zeroConfig ?? baseOpts.zeroConfig;\n const initialFacts = config?.initialFacts ?? baseOpts.initialFacts;\n\n let allPlugins = [...plugins];\n\n if (wantStatus) {\n statusPluginRef.current = createRequirementStatusPlugin();\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins = [\n ...allPlugins,\n statusPluginRef.current.plugin as Plugin<any>,\n ];\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const sys = createSystem({\n module: mod,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n debug,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n };\n\n // Start synchronously so facts are initialized before the first render\n systemRef.current = factoryRef.current();\n }\n\n useEffect(() => {\n // Strict mode re-mount: system was destroyed in cleanup, recreate it\n if (!systemRef.current && factoryRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n return () => {\n systemRef.current?.destroy();\n systemRef.current = null;\n statusPluginRef.current = null;\n };\n }, []);\n\n if (wantStatus && !isNamespaced) {\n return {\n system: systemRef.current!,\n statusPlugin: statusPluginRef.current!,\n };\n }\n\n return systemRef.current!;\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem with useSyncExternalStore\n// ============================================================================\n\n/**\n * React hook to select derived values from a NamespacedSystem.\n * Uses useSyncExternalStore for tear-free reads.\n *\n * @param system - The namespaced system to read from\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```tsx\n * const system = useDirectiveRef({ modules: { auth, data } });\n * const token = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * const count = useNamespacedSelector(system, [\"data.*\"], (s) => s.derive.data.total);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): R {\n const keysRef = useRef(keys);\n keysRef.current = keys;\n const selectorRef = useRef(selector);\n selectorRef.current = selector;\n\n const subscribe = useCallback(\n (onStoreChange: () => void) =>\n system.subscribe(keysRef.current, onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => selectorRef.current(system), [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDirective — scoped system with selected values in containers\n// ============================================================================\n\n/** Options for useDirective hook */\nexport interface UseDirectiveOptions<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n> extends DirectiveRefBaseConfig {\n /** Fact keys to subscribe to */\n facts?: FK[];\n /** Derivation keys to subscribe to */\n derived?: DK[];\n /** Enable status plugin */\n status?: boolean;\n}\n\n/** Return type for useDirective hook (without status) */\nexport type UseDirectiveReturn<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = {\n system: SingleModuleSystem<S>;\n dispatch: (event: InferEvents<S>) => void;\n events: SingleModuleSystem<S>[\"events\"];\n facts: Pick<InferFacts<S>, FK>;\n derived: Pick<InferDerivations<S>, DK>;\n};\n\n/** Return type for useDirective hook (with status) */\nexport type UseDirectiveReturnWithStatus<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = UseDirectiveReturn<S, FK, DK> & {\n statusPlugin: StatusPlugin;\n};\n\n/**\n * Convenience hook that creates a scoped system and reads selected facts/derivations\n * into container objects. When no `facts` or `derived` keys are specified, subscribes\n * to ALL facts and derivations (replacing the former `useModule` hook).\n *\n * @example\n * ```tsx\n * // Selective subscription\n * const { dispatch, facts: { count }, derived: { doubled } } = useDirective(counterModule, {\n * facts: [\"count\"],\n * derived: [\"doubled\"],\n * });\n *\n * // Subscribe to everything (no keys = all facts + all derivations)\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n * ```\n */\nexport function useDirective<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n>(\n moduleOrOptions: UseDirectiveRefOptions<S>,\n selections: UseDirectiveOptions<S, FK, DK> = {} as UseDirectiveOptions<\n S,\n FK,\n DK\n >,\n): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK> {\n const {\n facts: factKeysOpt,\n derived: derivedKeysOpt,\n status,\n ...configRest\n } = selections;\n const factKeys = (factKeysOpt ?? []) as FK[];\n const derivedKeys = (derivedKeysOpt ?? []) as DK[];\n\n // When no keys are specified, subscribe to everything\n const subscribeAll = factKeys.length === 0 && derivedKeys.length === 0;\n\n // Create system via useDirectiveRef (handles lifecycle)\n // biome-ignore lint/suspicious/noExplicitAny: Conditional overload dispatch\n const refResult: any = status\n ? useDirectiveRef(moduleOrOptions, { status: true as const, ...configRest })\n : useDirectiveRef(moduleOrOptions, configRest);\n\n const system: SingleModuleSystem<S> = status ? refResult.system : refResult;\n\n const statusPlugin = status\n ? (\n refResult as {\n system: SingleModuleSystem<S>;\n statusPlugin: StatusPlugin;\n }\n ).statusPlugin\n : undefined;\n\n // For subscribe-all mode, get all derivation keys\n const allDerivationKeys = useMemo(\n () => (subscribeAll ? Object.keys(system.derive) : []),\n [system, subscribeAll],\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubs: Array<() => void> = [];\n if (subscribeAll) {\n // Subscribe to ALL facts and ALL derivations\n unsubs.push(system.facts.$store.subscribeAll(onStoreChange));\n if (allDerivationKeys.length > 0) {\n unsubs.push(system.subscribe(allDerivationKeys, onStoreChange));\n }\n } else {\n if (factKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(factKeys, onStoreChange));\n }\n if (derivedKeys.length > 0) {\n unsubs.push(system.subscribe(derivedKeys, onStoreChange));\n }\n }\n return () => {\n for (const unsub of unsubs) unsub();\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys],\n );\n\n const cachedFacts = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedDerived = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedWrapper = useRef<{\n facts: Record<string, unknown>;\n derived: Record<string, unknown>;\n } | null>(null);\n\n const getSnapshot = useCallback(() => {\n let factsResult: Record<string, unknown>;\n let derivedResult: Record<string, unknown>;\n let effectiveFactKeys: readonly string[];\n let effectiveDerivedKeys: readonly string[];\n\n if (subscribeAll) {\n // Read ALL facts and ALL derivations\n factsResult = system.facts.$store.toObject();\n effectiveFactKeys = Object.keys(factsResult);\n derivedResult = {};\n for (const key of allDerivationKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = allDerivationKeys;\n } else {\n // Read selected keys only\n factsResult = {};\n for (const key of factKeys) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n factsResult[key] = (system.facts as any)[key];\n }\n effectiveFactKeys = factKeys;\n derivedResult = {};\n for (const key of derivedKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = derivedKeys;\n }\n\n // Check facts stability\n let factsSame = cachedFacts.current !== UNINITIALIZED;\n if (factsSame) {\n const prev = cachedFacts.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveFactKeys.length) {\n factsSame = false;\n } else {\n for (const key of effectiveFactKeys) {\n if (!Object.is(prev[key], factsResult[key])) {\n factsSame = false;\n break;\n }\n }\n }\n }\n\n // Check derived stability\n let derivedSame = cachedDerived.current !== UNINITIALIZED;\n if (derivedSame) {\n const prev = cachedDerived.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveDerivedKeys.length) {\n derivedSame = false;\n } else {\n for (const key of effectiveDerivedKeys) {\n if (!Object.is(prev[key], derivedResult[key])) {\n derivedSame = false;\n break;\n }\n }\n }\n }\n\n const stableFacts = factsSame\n ? (cachedFacts.current as Record<string, unknown>)\n : factsResult;\n const stableDerived = derivedSame\n ? (cachedDerived.current as Record<string, unknown>)\n : derivedResult;\n\n if (!factsSame) cachedFacts.current = factsResult;\n if (!derivedSame) cachedDerived.current = derivedResult;\n\n // Return same wrapper reference when both containers are unchanged\n if (factsSame && derivedSame && cachedWrapper.current) {\n return cachedWrapper.current;\n }\n\n cachedWrapper.current = { facts: stableFacts, derived: stableDerived };\n return cachedWrapper.current;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys]);\n\n const values = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const dispatch = useCallback(\n (event: InferEvents<S>) => system.dispatch(event),\n [system],\n );\n\n const events = useEvents(system);\n\n const base = {\n system,\n dispatch,\n events,\n facts: values.facts as Pick<InferFacts<S>, FK>,\n derived: values.derived as Pick<InferDerivations<S>, DK>,\n };\n\n if (status && statusPlugin) {\n return { ...base, statusPlugin } as UseDirectiveReturnWithStatus<S, FK, DK>;\n }\n\n return base as UseDirectiveReturn<S, FK, DK>;\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher. Provides autocomplete for event names\n * and avoids needing useCallback wrappers for event dispatch.\n *\n * @example\n * ```tsx\n * const events = useEvents(system);\n * <button onClick={() => events.increment()}>+</button>\n * ```\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return useMemo(() => system.events, [system]);\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n * Updates whenever system state changes.\n *\n * @example\n * ```tsx\n * const explanation = useExplain(system, \"req-123\");\n * if (explanation) <pre>{explanation}</pre>;\n * ```\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): string | null {\n assertSystem(\"useExplain\", system);\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n return system.explain(requirementId);\n }, [system, requirementId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n// ConstraintInfo is imported from ./shared.js and re-exported above\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): ConstraintInfo[];\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): ConstraintInfo | null;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n assertSystem(\"useConstraintStatus\", system);\n const inspectState = useInspect(system);\n\n return useMemo(() => {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return inspection.constraints.find((c) => c.id === constraintId) ?? null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, constraintId, inspectState]);\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\n/** Result of useOptimisticUpdate */\nexport interface OptimisticUpdateResult {\n /** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */\n mutate: (updateFn: () => void) => void;\n /** Whether a resolver is currently processing the optimistic change */\n isPending: boolean;\n /** Error if the resolver failed */\n error: Error | null;\n /** Manually rollback to the pre-mutation snapshot */\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n *\n * @example\n * ```tsx\n * const { mutate, isPending, error, rollback } = useOptimisticUpdate(\n * system, statusPlugin, \"SAVE_ITEM\"\n * );\n * mutate(() => { system.facts.items = [...system.facts.items, newItem]; });\n * ```\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const snapshotRef = useRef<SystemSnapshot | null>(null);\n\n const rollback = useCallback(() => {\n if (snapshotRef.current) {\n system.restore(snapshotRef.current);\n snapshotRef.current = null;\n }\n setIsPending(false);\n setError(null);\n }, [system]);\n\n const mutate = useCallback(\n (updateFn: () => void) => {\n snapshotRef.current = system.getSnapshot();\n setIsPending(true);\n setError(null);\n system.batch(updateFn);\n },\n [system],\n );\n\n // Watch for resolver completion/failure\n useEffect(() => {\n if (!statusPlugin || !requirementType || !isPending) return;\n\n return statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n // Resolved successfully — keep optimistic state\n snapshotRef.current = null;\n setIsPending(false);\n } else if (status.hasError) {\n // Failed — rollback\n setError(status.lastError);\n rollback();\n }\n });\n }, [statusPlugin, requirementType, isPending, rollback]);\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// DirectiveHydrator + useHydratedSystem — SSR/RSC hydration\n// ============================================================================\n\n/** Props for DirectiveHydrator component */\nexport interface HydratorProps {\n snapshot: DistributableSnapshot;\n children: ReactNode;\n}\n\n/** Context for hydrated snapshot */\nconst HydrationContext = createContext<DistributableSnapshot | null>(null);\n\n/**\n * SSR/RSC hydration component. Wraps children with a snapshot context\n * that `useHydratedSystem` can consume on the client.\n *\n * @example\n * ```tsx\n * // Server component\n * <DirectiveHydrator snapshot={serverSnapshot}>\n * <ClientApp />\n * </DirectiveHydrator>\n * ```\n */\nexport function DirectiveHydrator({ snapshot, children }: HydratorProps) {\n return (\n <HydrationContext.Provider value={snapshot}>\n {children}\n </HydrationContext.Provider>\n );\n}\n\n/**\n * Client-side hook that creates a system hydrated from a server snapshot.\n * Must be used inside a `<DirectiveHydrator>`.\n *\n * @example\n * ```tsx\n * function ClientApp() {\n * const system = useHydratedSystem(counterModule);\n * const count = useFact(system, \"count\");\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useHydratedSystem<S extends ModuleSchema>(\n moduleDef: ModuleDef<S>,\n config?: DirectiveRefBaseConfig,\n): SingleModuleSystem<S> {\n const snapshot = useContext(HydrationContext);\n\n // Merge snapshot data as initial facts if available\n const mergedConfig = useMemo(() => {\n if (!snapshot?.data) return config ?? {};\n return {\n ...(config ?? {}),\n initialFacts: {\n ...(config?.initialFacts ?? {}),\n ...snapshot.data,\n },\n };\n }, [snapshot, config]);\n\n return useDirectiveRef(moduleDef, mergedConfig) as SingleModuleSystem<S>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.tsx"],"names":["UNINITIALIZED","useFact","system","keyOrKeys","assertSystem","_useFacts","_useSingleFact","factKey","subscribe","useCallback","onStoreChange","getSnapshot","useSyncExternalStore","factKeys","cachedValue","useRef","result","key","same","useDerived","_useDerivedMulti","_useSingleDerived","derivationId","derivationIds","id","useSelector","systemArg","selector","defaultValueArg","equalityFnArg","_useNamespacedSelectorImpl","defaultValue","hasDefault","equalityFn","defaultEquality","selectorRef","eqRef","defaultValueRef","trackedFactKeysRef","trackedDeriveKeysRef","unsubsRef","deriveKeys","useMemo","runWithTracking","runTrackedSelector","resubscribe","unsub","derivedKeys","updated","depsChanged","effectiveValue","newValue","moduleNames","wildcardKeys","ns","useDispatch","event","useWatch","callback","callbackRef","useEffect","prevValue","useInspect","options","syncState","_useInspectSync","throttleMs","deferredState","setDeferredState","useState","throttleRef","createThrottle","args","_buildInspectState","computeInspectState","cachedSnapshot","cachedUnmetIds","cachedInflightIds","cachedIsSettled","unsubFacts","unsubSettled","state","unmetSame","u","i","inflightSame","f","settledSame","useHistory","cachedRef","buildHistoryState","useRequirementStatus","statusPlugin","typeOrTypes","_useRequirementStatusMulti","_useRequirementStatusSingle","type","status","prev","types","cachedKey","parts","suspenseCacheMap","getSuspenseCache","plugin","cache","useSuspenseRequirement","_useSuspenseRequirementMulti","_useSuspenseRequirementSingle","promise","resolve","unsubscribe","hasLoading","firstError","cacheKey","t","useDirectiveRef","config","systemRef","statusPluginRef","factoryRef","wantStatus","isNamespaced","modules","rest","plugins","history","trace","errorBoundary","tickMs","zeroConfig","initialFacts","sys","createSystem","isModule","mod","baseOpts","allPlugins","createRequirementStatusPlugin","useNamespacedSelector","keys","keysRef","useDirective","moduleOrOptions","selections","factKeysOpt","derivedKeysOpt","configRest","subscribeAll","refResult","allDerivationKeys","unsubs","cachedFacts","cachedDerived","cachedWrapper","factsResult","derivedResult","effectiveFactKeys","effectiveDerivedKeys","factsSame","derivedSame","stableFacts","stableDerived","values","dispatch","events","useEvents","base","useExplain","requirementId","useConstraintStatus","constraintId","inspectState","inspection","c","useOptimisticUpdate","requirementType","isPending","setIsPending","error","setError","snapshotRef","rollback","mutate","updateFn","HydrationContext","createContext","DirectiveHydrator","snapshot","children","jsx","useHydratedSystem","moduleDef","useContext","mergedConfig"],"mappings":"8bA2FA,IAAMA,CAAAA,CAAgB,OAAO,yBAAyB,CAAA,CAmB/C,SAASC,EAAAA,CAEdC,CAAAA,CACAC,CAAAA,CACS,CAaT,OAZAC,YAAAA,CAAa,SAAA,CAAWF,CAAM,CAAA,CAE5B,OAAA,CAAQ,IAAI,QAAA,GAAa,YAAA,EACzB,OAAOC,CAAAA,EAAc,YAErB,OAAA,CAAQ,KAAA,CACN,gJAEF,CAAA,CAIE,KAAA,CAAM,QAAQA,CAAS,CAAA,CAClBE,EAAAA,CAAUH,CAAAA,CAAQC,CAAS,CAAA,CAI7BG,EAAAA,CAAeJ,EAAQC,CAAS,CACzC,CAEA,SAASG,EAAAA,CAEPJ,CAAAA,CACAK,CAAAA,CACS,CACL,OAAA,CAAQ,GAAA,CAAI,WAAa,YAAA,GACrBA,CAAAA,IAAWL,EAAO,KAAA,CAAM,MAAA,CAAO,QAAA,EAAS,EAC5C,QAAQ,IAAA,CACN,CAAA,qBAAA,EAAwBK,CAAO,CAAA,+CAAA,EACdA,CAAO,uCAC1B,CAAA,CAAA,CAIJ,IAAMC,CAAAA,CAAYC,WAAAA,CACfC,GACQR,CAAAA,CAAO,KAAA,CAAM,OAAO,SAAA,CAAU,CAACK,CAAO,CAAA,CAAGG,CAAa,CAAA,CAE/D,CAACR,EAAQK,CAAO,CAClB,EAEMI,CAAAA,CAAcF,WAAAA,CAAY,IACvBP,CAAAA,CAAO,KAAA,CAAM,MAAA,CAAO,GAAA,CAAIK,CAAgB,CAAA,CAC9C,CAACL,EAAQK,CAAO,CAAC,EAEpB,OAAOK,oBAAAA,CAAqBJ,CAAAA,CAAWG,CAAAA,CAAaA,CAAW,CACjE,CAE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AAiBC,EAAWK,CAAQ,CAAC,EAEhD,CAAE,MAAA,CAAAC,EAAQ,SAAA,CAAAN,CAAAA,CAAW,KAAA,CAAAE,CAAAA,CAAO,SAAAG,CAAS,CAC9C,CAaA,IAAMG,CAAAA,CAAmBC,cAA4C,IAAI,CAAA,CAclE,SAASC,EAAAA,CAAkB,CAAE,QAAA,CAAAC,CAAAA,CAAU,SAAAC,CAAS,CAAA,CAAkB,CACvE,OACEC,GAAAA,CAACL,CAAAA,CAAiB,QAAA,CAAjB,CAA0B,KAAA,CAAOG,CAAAA,CAC/B,SAAAC,CAAAA,CACH,CAEJ,CAeO,SAASE,EAAAA,CACdC,CAAAA,CACA3E,CAAAA,CACuB,CACvB,IAAMuE,CAAAA,CAAWK,WAAWR,CAAgB,CAAA,CAGtCS,EAAexJ,OAAAA,CAAQ,IACtBkJ,CAAAA,EAAU,IAAA,CACR,CACL,GAAIvE,CAAAA,EAAU,EAAC,CACf,YAAA,CAAc,CACZ,GAAIA,CAAAA,EAAQ,YAAA,EAAgB,GAC5B,GAAGuE,CAAAA,CAAS,IACd,CACF,CAAA,CAP4BvE,GAAU,EAAC,CAQtC,CAACuE,CAAAA,CAAUvE,CAAM,CAAC,CAAA,CAErB,OAAOD,CAAAA,CAAgB4E,CAAAA,CAAWE,CAAY,CAChD","file":"index.js","sourcesContent":["/**\n * React Adapter - Consolidated hooks for React integration\n *\n * 18 public exports: useFact, useDerived, useDispatch, useDirective,\n * useDirectiveRef, useSelector, useWatch, useInspect, useRequirementStatus,\n * useSuspenseRequirement, useEvents, useExplain, useConstraintStatus,\n * useOptimisticUpdate, DirectiveHydrator, useHydratedSystem,\n * useHistory, shallowEqual\n *\n * @example\n * ```tsx\n * import { useFact, useDerived, useEvents } from '@directive-run/react';\n *\n * const system = createSystem({ module: counterModule });\n * system.start();\n *\n * function Counter() {\n * const count = useFact(system, \"count\");\n * const doubled = useDerived(system, \"doubled\");\n * const events = useEvents(system);\n *\n * return (\n * <div>\n * <p>Count: {count}</p>\n * <p>Doubled: {doubled}</p>\n * <button onClick={() => events.increment()}>+</button>\n * </div>\n * );\n * }\n * ```\n */\n\nimport type {\n TraceOption,\n DistributableSnapshot,\n ErrorBoundaryConfig,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemSnapshot,\n HistoryOption,\n HistoryState,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport type { ReactNode } from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/** Sentinel value for uninitialized selector cache */\nconst UNINITIALIZED = Symbol(\"directive.uninitialized\");\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;\n\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;\n\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFacts(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return _useSingleFact(system, keyOrKeys);\n}\n\nfunction _useSingleFact(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKey: string,\n): unknown {\n if (process.env.NODE_ENV !== \"production\") {\n if (!(factKey in system.facts.$store.toObject())) {\n console.warn(\n `[Directive] useFact(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe([factKey], onStoreChange);\n },\n [system, factKey],\n );\n\n const getSnapshot = useCallback(() => {\n return system.facts.$store.get(factKey as never);\n }, [system, factKey]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useFacts(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe(factKeys, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...factKeys],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key as never);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const key of factKeys) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[key],\n result[key],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...factKeys]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];\n\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Pick<InferDerivations<S>, K>;\n\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useDerived\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(keyOrKeys)) {\n return _useDerivedMulti(system, keyOrKeys);\n }\n\n // Single key path\n return _useSingleDerived(system, keyOrKeys);\n}\n\nfunction _useSingleDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationId: string,\n): unknown {\n if (process.env.NODE_ENV !== \"production\") {\n if (!(derivationId in system.derive)) {\n console.warn(\n `[Directive] useDerived(\"${derivationId}\") — derivation not found. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe([derivationId], onStoreChange);\n },\n [system, derivationId],\n );\n\n const getSnapshot = useCallback(() => {\n return system.read(derivationId);\n }, [system, derivationId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useDerivedMulti(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe(derivationIds, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...derivationIds],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const id of derivationIds) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[id],\n result[id],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...derivationIds]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSelector — Zustand-style selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations (Zustand-style).\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys. Falls back to subscribeAll\n * if no keys are detected.\n *\n * Supports an optional default value as the 3rd parameter, used when\n * the system is null/undefined or the selector returns undefined.\n * When a default value is provided, the system parameter may be\n * null | undefined — the hook returns the default and recomputes\n * when the system becomes available.\n *\n * An optional equality function can be passed as the 4th parameter\n * to customize when the selector result is considered \"changed\".\n * Defaults to `Object.is`. Use `shallowEqual` (exported from this\n * package) when your selector returns a new object/array each time.\n *\n * @example\n * ```tsx\n * // Basic usage\n * const count = useSelector(system, (s) => s.count);\n *\n * // With default value (allows nullable system)\n * const count = useSelector(system, (s) => s.count, 0);\n *\n * // With default value + custom equality\n * const coords = useSelector(system, (s) => ({ x: s.x, y: s.y }), { x: 0, y: 0 }, shallowEqual);\n * ```\n */\n\n// Non-null system, no default\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n): R;\n\n// Non-null system, with default value and optional equality\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable system, default REQUIRED\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S> | null | undefined,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Namespaced system overloads ---\n\n// Namespaced system, no default\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n): R;\n\n// Namespaced system, with default value and optional equality\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable namespaced system, default REQUIRED\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules> | null | undefined,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Generic fallbacks ---\n\n// Generic fallback: non-null system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue?: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Generic fallback: nullable system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature accepts both system types\n systemArg: SingleModuleSystem<any> | NamespacedSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n // Route to namespaced implementation if system is a NamespacedSystem\n // biome-ignore lint/suspicious/noExplicitAny: Runtime type check\n if (systemArg && (systemArg as any)._mode === \"namespaced\") {\n // biome-ignore lint/suspicious/noExplicitAny: Delegate to namespaced impl\n return _useNamespacedSelectorImpl(\n systemArg as NamespacedSystem<any>,\n selector,\n defaultValueArg,\n equalityFnArg,\n );\n }\n\n // After the namespaced check, system is a SingleModuleSystem\n const system = systemArg as SingleModuleSystem<any> | null | undefined;\n let defaultValue: unknown;\n let hasDefault = false;\n const equalityFn: (a: unknown, b: unknown) => boolean =\n equalityFnArg ?? defaultEquality;\n\n if (defaultValueArg !== undefined) {\n defaultValue = defaultValueArg;\n hasDefault = true;\n }\n\n // Dev-mode warning: null system without a default value\n if (process.env.NODE_ENV !== \"production\") {\n if (!system && !hasDefault) {\n console.error(\n \"[Directive] useSelector() received a null/undefined system without a default value. \" +\n \"Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)\",\n );\n }\n }\n\n // Store selector/eq/default in refs to avoid resubscription churn\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValue);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValue;\n\n const trackedFactKeysRef = useRef<string[]>([]);\n const trackedDeriveKeysRef = useRef<string[]>([]);\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n const unsubsRef = useRef<Array<() => void>>([]);\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const deriveKeys = useMemo(\n () => (system ? new Set(Object.keys(system.derive)) : new Set<string>()),\n [system],\n );\n\n const runWithTracking = useCallback(() => {\n if (!system) {\n return {\n value: defaultValueRef.current,\n factKeys: [] as string[],\n deriveKeys: [] as string[],\n };\n }\n\n return runTrackedSelector(system, deriveKeys, selectorRef.current);\n }, [system, deriveKeys]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!system) {\n // No system — return noop unsubscribe\n return () => {};\n }\n\n const resubscribe = () => {\n // Cleanup previous subscriptions\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n\n // Run selector with tracking to detect accessed keys\n const { factKeys, deriveKeys: derivedKeys } = runWithTracking();\n trackedFactKeysRef.current = factKeys;\n trackedDeriveKeysRef.current = derivedKeys;\n\n // Subscribe to accessed fact keys\n if (factKeys.length > 0) {\n unsubsRef.current.push(\n system.facts.$store.subscribe(factKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n } else if (derivedKeys.length === 0) {\n // No deps at all — subscribe to everything\n unsubsRef.current.push(\n system.facts.$store.subscribeAll(onStoreChange),\n );\n }\n\n // Subscribe to accessed derivation keys\n if (derivedKeys.length > 0) {\n unsubsRef.current.push(\n system.subscribe(derivedKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n };\n },\n [system, runWithTracking],\n );\n\n const getSnapshot = useCallback(() => {\n let effectiveValue: unknown;\n\n if (!system) {\n effectiveValue = defaultValueRef.current;\n } else {\n const { value: newValue } = runWithTracking();\n\n // When selector returns undefined and we have a default, use it\n effectiveValue =\n newValue === undefined && hasDefault\n ? defaultValueRef.current\n : newValue;\n }\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [runWithTracking, system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// _useNamespacedSelectorImpl — internal namespaced useSelector\n// ============================================================================\n\n/**\n * Internal implementation for useSelector with NamespacedSystem.\n * Subscribes to all module namespaces and runs the selector against the system.\n * Uses equality comparison to prevent unnecessary re-renders.\n */\nfunction _useNamespacedSelectorImpl(\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n system: NamespacedSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n const hasDefault = defaultValueArg !== undefined;\n const equalityFn = equalityFnArg ?? defaultEquality;\n\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValueArg);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValueArg;\n\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n\n // Get all module namespace names for wildcard subscription\n const moduleNames = useMemo(() => Object.keys(system.facts), [system]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n // Subscribe to all modules using wildcard keys\n const wildcardKeys = moduleNames.map((ns) => `${ns}.*`);\n\n return system.subscribe(wildcardKeys, onStoreChange);\n },\n [system, moduleNames],\n );\n\n const getSnapshot = useCallback(() => {\n const newValue = selectorRef.current(system);\n const effectiveValue =\n newValue === undefined && hasDefault ? defaultValueRef.current : newValue;\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return useCallback(\n (event: InferEvents<S>) => {\n system.dispatch(event);\n },\n [system],\n );\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect (no re-render)\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n prevValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n prevValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n callback: (newValue: any, prevValue: any) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n useEffect(() => {\n return system.watch(key, (newValue, prevValue) => {\n callbackRef.current(newValue, prevValue);\n });\n }, [system, key]);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n// InspectState is imported from ./shared.js and re-exported above\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n /** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */\n throttleMs?: number;\n}\n\n/**\n * Hook to get consolidated system inspection data reactively.\n *\n * Merges isSettled, unmet/inflight requirements, and working state\n * into a single subscription. Optionally throttle updates.\n *\n * @example\n * ```tsx\n * const { isSettled, isWorking, hasUnmet } = useInspect(system);\n * const throttled = useInspect(system, { throttleMs: 200 });\n * ```\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): InspectState {\n assertSystem(\"useInspect\", system);\n // Always call the sync version (useSyncExternalStore path) — no conditional hooks\n const syncState = _useInspectSync(system);\n\n const throttleMs = options?.throttleMs;\n const [deferredState, setDeferredState] = useState(syncState);\n const throttleRef = useRef<{\n throttled: (...args: unknown[]) => void;\n cleanup: () => void;\n } | null>(null);\n\n // Create/recreate throttle when throttleMs changes\n useEffect(() => {\n if (!throttleMs || throttleMs <= 0) {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n return;\n }\n // Clean up old throttle before creating new one\n throttleRef.current?.cleanup();\n throttleRef.current = createThrottle((...args: unknown[]) => {\n setDeferredState(args[0] as InspectState);\n }, throttleMs);\n return () => {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n };\n }, [throttleMs]);\n\n // Feed sync state through throttle after each render\n useEffect(() => {\n if (throttleRef.current) {\n throttleRef.current.throttled(syncState);\n }\n }, [syncState]);\n\n if (!throttleMs || throttleMs <= 0) return syncState;\n return deferredState;\n}\n\nfunction _buildInspectState(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n return computeInspectState(system);\n}\n\nfunction _useInspectSync(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n const cachedSnapshot = useRef<InspectState | null>(null);\n const cachedUnmetIds = useRef<string[]>([]);\n const cachedInflightIds = useRef<string[]>([]);\n const cachedIsSettled = useRef<boolean | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = _buildInspectState(system);\n\n const unmetSame =\n state.unmet.length === cachedUnmetIds.current.length &&\n state.unmet.every((u, i) => u.id === cachedUnmetIds.current[i]);\n const inflightSame =\n state.inflight.length === cachedInflightIds.current.length &&\n state.inflight.every((f, i) => f.id === cachedInflightIds.current[i]);\n const settledSame = state.isSettled === cachedIsSettled.current;\n\n if (unmetSame && inflightSame && settledSame && cachedSnapshot.current) {\n return cachedSnapshot.current;\n }\n\n cachedSnapshot.current = state;\n cachedUnmetIds.current = state.unmet.map((u) => u.id);\n cachedInflightIds.current = state.inflight.map((f) => f.id);\n cachedIsSettled.current = state.isSettled;\n\n return state;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useHistory — reactive history state\n// ============================================================================\n\n/**\n * Reactive history hook. Returns null when history is disabled.\n * Re-renders when snapshots are taken or navigation occurs.\n *\n * @example\n * ```tsx\n * const history = useHistory(system);\n * if (history) {\n * return (\n * <div>\n * <button disabled={!history.canGoBack} onClick={() => history.goBack()}>Undo</button>\n * <button disabled={!history.canGoForward} onClick={() => history.goForward()}>Redo</button>\n * <span>{history.currentIndex + 1} / {history.totalSnapshots}</span>\n * </div>\n * );\n * }\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): HistoryState | null {\n assertSystem(\"useHistory\", system);\n const cachedRef = useRef<HistoryState | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => system.onHistoryChange(onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = buildHistoryState(system);\n if (!state) return null;\n\n // Return stable reference when values haven't changed\n if (\n cachedRef.current &&\n cachedRef.current.canGoBack === state.canGoBack &&\n cachedRef.current.canGoForward === state.canGoForward &&\n cachedRef.current.currentIndex === state.currentIndex &&\n cachedRef.current.totalSnapshots === state.totalSnapshots &&\n cachedRef.current.isPaused === state.isPaused\n ) {\n return cachedRef.current;\n }\n\n cachedRef.current = state;\n return cachedRef.current;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useRequirementStatusMulti(statusPlugin, typeOrTypes);\n }\n return _useRequirementStatusSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useRequirementStatusSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const cachedRef = useRef<RequirementTypeStatus | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const status = statusPlugin.getStatus(type);\n\n if (cachedRef.current !== UNINITIALIZED) {\n const prev = cachedRef.current;\n if (\n prev.pending === status.pending &&\n prev.inflight === status.inflight &&\n prev.failed === status.failed &&\n prev.isLoading === status.isLoading &&\n prev.hasError === status.hasError &&\n prev.lastError === status.lastError\n ) {\n return cachedRef.current;\n }\n }\n\n cachedRef.current = status;\n return status;\n }, [statusPlugin, type]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useRequirementStatusMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const cachedRef = useRef<Record<string, RequirementTypeStatus> | null>(null);\n const cachedKey = useRef<string>(\"\");\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, RequirementTypeStatus> = {};\n const parts: string[] = [];\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n parts.push(\n `${type}:${status.pending}:${status.inflight}:${status.failed}:${status.hasError}:${status.lastError?.message ?? \"\"}`,\n );\n }\n const key = parts.join(\"|\");\n\n if (key !== cachedKey.current) {\n cachedKey.current = key;\n cachedRef.current = result;\n }\n\n return cachedRef.current ?? result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [statusPlugin, ...types]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSuspenseRequirement — single or multi\n// ============================================================================\n\n// Cache for pending promises, scoped per statusPlugin to prevent cross-system leaks.\nconst suspenseCacheMap = new WeakMap<\n StatusPlugin,\n Map<string, Promise<void>>\n>();\n\nfunction getSuspenseCache(plugin: StatusPlugin): Map<string, Promise<void>> {\n let cache = suspenseCacheMap.get(plugin);\n if (!cache) {\n cache = new Map();\n suspenseCacheMap.set(plugin, cache);\n }\n return cache;\n}\n\n/** Single type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useSuspenseRequirementMulti(statusPlugin, typeOrTypes);\n }\n return _useSuspenseRequirementSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useSuspenseRequirementSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const status = statusPlugin.getStatus(type);\n\n if (status.hasError && status.lastError) {\n throw status.lastError;\n }\n\n if (status.isLoading) {\n const cache = getSuspenseCache(statusPlugin);\n let promise = cache.get(type);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const currentStatus = statusPlugin.getStatus(type);\n if (!currentStatus.isLoading) {\n cache.delete(type);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(type, promise);\n }\n\n throw promise;\n }\n\n return status;\n}\n\nfunction _useSuspenseRequirementMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const result: Record<string, RequirementTypeStatus> = {};\n let hasLoading = false;\n let firstError: Error | null = null;\n\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n\n if (status.hasError && status.lastError && !firstError) {\n firstError = status.lastError;\n }\n if (status.isLoading) {\n hasLoading = true;\n }\n }\n\n if (firstError) {\n throw firstError;\n }\n\n if (hasLoading) {\n const cache = getSuspenseCache(statusPlugin);\n const cacheKey = types.slice().sort().join(\",\");\n let promise = cache.get(cacheKey);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const allDone = types.every(\n (t) => !statusPlugin.getStatus(t).isLoading,\n );\n if (allDone) {\n cache.delete(cacheKey);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(cacheKey, promise);\n }\n\n throw promise;\n }\n\n return result;\n}\n\n// ============================================================================\n// useDirectiveRef — scoped system lifecycle\n// ============================================================================\n\n/** Base options for creating a scoped system */\ninterface DirectiveRefBaseConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n history?: HistoryOption;\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n}\n\n/** Options for useDirectiveRef: module directly, or config object */\nexport type UseDirectiveRefOptions<M extends ModuleSchema> =\n | ModuleDef<M>\n | (DirectiveRefBaseConfig & { module: ModuleDef<M> });\n\n/** Options for useDirectiveRef with namespaced modules */\nexport type UseDirectiveRefNamespacedOptions<Modules extends ModulesMap> =\n DirectiveRefBaseConfig & { modules: { [K in keyof Modules]: Modules[K] } };\n\n// --- Single-module overloads ---\n\n/** Without status (no config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n): SingleModuleSystem<M>;\n\n/** Without status (with config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: DirectiveRefBaseConfig,\n): SingleModuleSystem<M>;\n\n/** With status: returns { system, statusPlugin } */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: { status: true } & DirectiveRefBaseConfig,\n): { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin };\n\n// --- Namespaced (multi-module) overloads ---\n\n/** Namespaced: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n): NamespacedSystem<Modules>;\n\n/** Namespaced with config: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n config: DirectiveRefBaseConfig,\n): NamespacedSystem<Modules>;\n\n/** Implementation */\nexport function useDirectiveRef(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature handles both modes\n options: any,\n config?: { status?: boolean } & DirectiveRefBaseConfig,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation return varies by overload\n): any {\n // biome-ignore lint/suspicious/noExplicitAny: System ref holds either system type\n const systemRef = useRef<any>(null);\n const statusPluginRef = useRef<StatusPlugin | null>(null);\n // Factory ref for strict mode re-creation (effects unmount then re-mount)\n // biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\n const factoryRef = useRef<(() => any) | null>(null);\n const wantStatus = config?.status === true;\n const isNamespaced = \"modules\" in options;\n\n if (!systemRef.current) {\n // Build a factory that creates + starts the system.\n // Called once during render and again on strict-mode re-mount.\n factoryRef.current = () => {\n if (isNamespaced) {\n // --- Namespaced mode: { modules: { ... } } ---\n const { modules, ...rest } = options;\n const plugins = config?.plugins ?? rest.plugins ?? [];\n const history = config?.history ?? rest.history;\n const trace = config?.trace ?? rest.trace;\n const errorBoundary = config?.errorBoundary ?? rest.errorBoundary;\n const tickMs = config?.tickMs ?? rest.tickMs;\n const zeroConfig = config?.zeroConfig ?? rest.zeroConfig;\n const initialFacts = config?.initialFacts ?? rest.initialFacts;\n\n const sys = createSystem({\n modules,\n plugins: plugins.length > 0 ? plugins : undefined,\n history,\n trace,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n }\n\n // --- Single-module mode ---\n const isModule = \"id\" in options && \"schema\" in options;\n const mod = isModule ? options : options.module;\n const baseOpts = isModule ? {} : (options as DirectiveRefBaseConfig);\n const plugins = config?.plugins ?? baseOpts.plugins ?? [];\n const history = config?.history ?? baseOpts.history;\n const trace = config?.trace ?? baseOpts.trace;\n const errorBoundary = config?.errorBoundary ?? baseOpts.errorBoundary;\n const tickMs = config?.tickMs ?? baseOpts.tickMs;\n const zeroConfig = config?.zeroConfig ?? baseOpts.zeroConfig;\n const initialFacts = config?.initialFacts ?? baseOpts.initialFacts;\n\n let allPlugins = [...plugins];\n\n if (wantStatus) {\n statusPluginRef.current = createRequirementStatusPlugin();\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins = [\n ...allPlugins,\n statusPluginRef.current.plugin as Plugin<any>,\n ];\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const sys = createSystem({\n module: mod,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n history,\n trace,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n };\n\n // Start synchronously so facts are initialized before the first render\n systemRef.current = factoryRef.current();\n }\n\n useEffect(() => {\n // Strict mode re-mount: system was destroyed in cleanup, recreate it\n if (!systemRef.current && factoryRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n return () => {\n systemRef.current?.destroy();\n systemRef.current = null;\n statusPluginRef.current = null;\n };\n }, []);\n\n if (wantStatus && !isNamespaced) {\n return {\n system: systemRef.current!,\n statusPlugin: statusPluginRef.current!,\n };\n }\n\n return systemRef.current!;\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem with useSyncExternalStore\n// ============================================================================\n\n/**\n * React hook to select derived values from a NamespacedSystem.\n * Uses useSyncExternalStore for tear-free reads.\n *\n * @param system - The namespaced system to read from\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```tsx\n * const system = useDirectiveRef({ modules: { auth, data } });\n * const token = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * const count = useNamespacedSelector(system, [\"data.*\"], (s) => s.derive.data.total);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): R {\n const keysRef = useRef(keys);\n keysRef.current = keys;\n const selectorRef = useRef(selector);\n selectorRef.current = selector;\n\n const subscribe = useCallback(\n (onStoreChange: () => void) =>\n system.subscribe(keysRef.current, onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => selectorRef.current(system), [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDirective — scoped system with selected values in containers\n// ============================================================================\n\n/** Options for useDirective hook */\nexport interface UseDirectiveOptions<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n> extends DirectiveRefBaseConfig {\n /** Fact keys to subscribe to */\n facts?: FK[];\n /** Derivation keys to subscribe to */\n derived?: DK[];\n /** Enable status plugin */\n status?: boolean;\n}\n\n/** Return type for useDirective hook (without status) */\nexport type UseDirectiveReturn<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = {\n system: SingleModuleSystem<S>;\n dispatch: (event: InferEvents<S>) => void;\n events: SingleModuleSystem<S>[\"events\"];\n facts: Pick<InferFacts<S>, FK>;\n derived: Pick<InferDerivations<S>, DK>;\n};\n\n/** Return type for useDirective hook (with status) */\nexport type UseDirectiveReturnWithStatus<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = UseDirectiveReturn<S, FK, DK> & {\n statusPlugin: StatusPlugin;\n};\n\n/**\n * Convenience hook that creates a scoped system and reads selected facts/derivations\n * into container objects. When no `facts` or `derived` keys are specified, subscribes\n * to ALL facts and derivations (replacing the former `useModule` hook).\n *\n * @example\n * ```tsx\n * // Selective subscription\n * const { dispatch, facts: { count }, derived: { doubled } } = useDirective(counterModule, {\n * facts: [\"count\"],\n * derived: [\"doubled\"],\n * });\n *\n * // Subscribe to everything (no keys = all facts + all derivations)\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n * ```\n */\nexport function useDirective<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n>(\n moduleOrOptions: UseDirectiveRefOptions<S>,\n selections: UseDirectiveOptions<S, FK, DK> = {} as UseDirectiveOptions<\n S,\n FK,\n DK\n >,\n): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK> {\n const {\n facts: factKeysOpt,\n derived: derivedKeysOpt,\n status,\n ...configRest\n } = selections;\n const factKeys = (factKeysOpt ?? []) as FK[];\n const derivedKeys = (derivedKeysOpt ?? []) as DK[];\n\n // When no keys are specified, subscribe to everything\n const subscribeAll = factKeys.length === 0 && derivedKeys.length === 0;\n\n // Create system via useDirectiveRef (handles lifecycle)\n // biome-ignore lint/suspicious/noExplicitAny: Conditional overload dispatch\n const refResult: any = status\n ? useDirectiveRef(moduleOrOptions, { status: true as const, ...configRest })\n : useDirectiveRef(moduleOrOptions, configRest);\n\n const system: SingleModuleSystem<S> = status ? refResult.system : refResult;\n\n const statusPlugin = status\n ? (\n refResult as {\n system: SingleModuleSystem<S>;\n statusPlugin: StatusPlugin;\n }\n ).statusPlugin\n : undefined;\n\n // For subscribe-all mode, get all derivation keys\n const allDerivationKeys = useMemo(\n () => (subscribeAll ? Object.keys(system.derive) : []),\n [system, subscribeAll],\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubs: Array<() => void> = [];\n if (subscribeAll) {\n // Subscribe to ALL facts and ALL derivations\n unsubs.push(system.facts.$store.subscribeAll(onStoreChange));\n if (allDerivationKeys.length > 0) {\n unsubs.push(system.subscribe(allDerivationKeys, onStoreChange));\n }\n } else {\n if (factKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(factKeys, onStoreChange));\n }\n if (derivedKeys.length > 0) {\n unsubs.push(system.subscribe(derivedKeys, onStoreChange));\n }\n }\n return () => {\n for (const unsub of unsubs) unsub();\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys],\n );\n\n const cachedFacts = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedDerived = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedWrapper = useRef<{\n facts: Record<string, unknown>;\n derived: Record<string, unknown>;\n } | null>(null);\n\n const getSnapshot = useCallback(() => {\n let factsResult: Record<string, unknown>;\n let derivedResult: Record<string, unknown>;\n let effectiveFactKeys: readonly string[];\n let effectiveDerivedKeys: readonly string[];\n\n if (subscribeAll) {\n // Read ALL facts and ALL derivations\n factsResult = system.facts.$store.toObject();\n effectiveFactKeys = Object.keys(factsResult);\n derivedResult = {};\n for (const key of allDerivationKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = allDerivationKeys;\n } else {\n // Read selected keys only\n factsResult = {};\n for (const key of factKeys) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n factsResult[key] = (system.facts as any)[key];\n }\n effectiveFactKeys = factKeys;\n derivedResult = {};\n for (const key of derivedKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = derivedKeys;\n }\n\n // Check facts stability\n let factsSame = cachedFacts.current !== UNINITIALIZED;\n if (factsSame) {\n const prev = cachedFacts.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveFactKeys.length) {\n factsSame = false;\n } else {\n for (const key of effectiveFactKeys) {\n if (!Object.is(prev[key], factsResult[key])) {\n factsSame = false;\n break;\n }\n }\n }\n }\n\n // Check derived stability\n let derivedSame = cachedDerived.current !== UNINITIALIZED;\n if (derivedSame) {\n const prev = cachedDerived.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveDerivedKeys.length) {\n derivedSame = false;\n } else {\n for (const key of effectiveDerivedKeys) {\n if (!Object.is(prev[key], derivedResult[key])) {\n derivedSame = false;\n break;\n }\n }\n }\n }\n\n const stableFacts = factsSame\n ? (cachedFacts.current as Record<string, unknown>)\n : factsResult;\n const stableDerived = derivedSame\n ? (cachedDerived.current as Record<string, unknown>)\n : derivedResult;\n\n if (!factsSame) cachedFacts.current = factsResult;\n if (!derivedSame) cachedDerived.current = derivedResult;\n\n // Return same wrapper reference when both containers are unchanged\n if (factsSame && derivedSame && cachedWrapper.current) {\n return cachedWrapper.current;\n }\n\n cachedWrapper.current = { facts: stableFacts, derived: stableDerived };\n return cachedWrapper.current;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys]);\n\n const values = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const dispatch = useCallback(\n (event: InferEvents<S>) => system.dispatch(event),\n [system],\n );\n\n const events = useEvents(system);\n\n const base = {\n system,\n dispatch,\n events,\n facts: values.facts as Pick<InferFacts<S>, FK>,\n derived: values.derived as Pick<InferDerivations<S>, DK>,\n };\n\n if (status && statusPlugin) {\n return { ...base, statusPlugin } as UseDirectiveReturnWithStatus<S, FK, DK>;\n }\n\n return base as UseDirectiveReturn<S, FK, DK>;\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher. Provides autocomplete for event names\n * and avoids needing useCallback wrappers for event dispatch.\n *\n * @example\n * ```tsx\n * const events = useEvents(system);\n * <button onClick={() => events.increment()}>+</button>\n * ```\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return useMemo(() => system.events, [system]);\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n * Updates whenever system state changes.\n *\n * @example\n * ```tsx\n * const explanation = useExplain(system, \"req-123\");\n * if (explanation) <pre>{explanation}</pre>;\n * ```\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): string | null {\n assertSystem(\"useExplain\", system);\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n return system.explain(requirementId);\n }, [system, requirementId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n// ConstraintInfo is imported from ./shared.js and re-exported above\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): ConstraintInfo[];\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): ConstraintInfo | null;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n assertSystem(\"useConstraintStatus\", system);\n const inspectState = useInspect(system);\n\n return useMemo(() => {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return inspection.constraints.find((c) => c.id === constraintId) ?? null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, constraintId, inspectState]);\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\n/** Result of useOptimisticUpdate */\nexport interface OptimisticUpdateResult {\n /** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */\n mutate: (updateFn: () => void) => void;\n /** Whether a resolver is currently processing the optimistic change */\n isPending: boolean;\n /** Error if the resolver failed */\n error: Error | null;\n /** Manually rollback to the pre-mutation snapshot */\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n *\n * @example\n * ```tsx\n * const { mutate, isPending, error, rollback } = useOptimisticUpdate(\n * system, statusPlugin, \"SAVE_ITEM\"\n * );\n * mutate(() => { system.facts.items = [...system.facts.items, newItem]; });\n * ```\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const snapshotRef = useRef<SystemSnapshot | null>(null);\n\n const rollback = useCallback(() => {\n if (snapshotRef.current) {\n system.restore(snapshotRef.current);\n snapshotRef.current = null;\n }\n setIsPending(false);\n setError(null);\n }, [system]);\n\n const mutate = useCallback(\n (updateFn: () => void) => {\n snapshotRef.current = system.getSnapshot();\n setIsPending(true);\n setError(null);\n system.batch(updateFn);\n },\n [system],\n );\n\n // Watch for resolver completion/failure\n useEffect(() => {\n if (!statusPlugin || !requirementType || !isPending) return;\n\n return statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n // Resolved successfully — keep optimistic state\n snapshotRef.current = null;\n setIsPending(false);\n } else if (status.hasError) {\n // Failed — rollback\n setError(status.lastError);\n rollback();\n }\n });\n }, [statusPlugin, requirementType, isPending, rollback]);\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// DirectiveHydrator + useHydratedSystem — SSR/RSC hydration\n// ============================================================================\n\n/** Props for DirectiveHydrator component */\nexport interface HydratorProps {\n snapshot: DistributableSnapshot;\n children: ReactNode;\n}\n\n/** Context for hydrated snapshot */\nconst HydrationContext = createContext<DistributableSnapshot | null>(null);\n\n/**\n * SSR/RSC hydration component. Wraps children with a snapshot context\n * that `useHydratedSystem` can consume on the client.\n *\n * @example\n * ```tsx\n * // Server component\n * <DirectiveHydrator snapshot={serverSnapshot}>\n * <ClientApp />\n * </DirectiveHydrator>\n * ```\n */\nexport function DirectiveHydrator({ snapshot, children }: HydratorProps) {\n return (\n <HydrationContext.Provider value={snapshot}>\n {children}\n </HydrationContext.Provider>\n );\n}\n\n/**\n * Client-side hook that creates a system hydrated from a server snapshot.\n * Must be used inside a `<DirectiveHydrator>`.\n *\n * @example\n * ```tsx\n * function ClientApp() {\n * const system = useHydratedSystem(counterModule);\n * const count = useFact(system, \"count\");\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useHydratedSystem<S extends ModuleSchema>(\n moduleDef: ModuleDef<S>,\n config?: DirectiveRefBaseConfig,\n): SingleModuleSystem<S> {\n const snapshot = useContext(HydrationContext);\n\n // Merge snapshot data as initial facts if available\n const mergedConfig = useMemo(() => {\n if (!snapshot?.data) return config ?? {};\n return {\n ...(config ?? {}),\n initialFacts: {\n ...(config?.initialFacts ?? {}),\n ...snapshot.data,\n },\n };\n }, [snapshot, config]);\n\n return useDirectiveRef(moduleDef, mergedConfig) as SingleModuleSystem<S>;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@directive-run/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "React hooks and components for Directive.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Jason Comes",
|
|
@@ -50,13 +50,14 @@
|
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@testing-library/react": "^16.3.2",
|
|
52
52
|
"@types/node": "^25.2.0",
|
|
53
|
-
"@types/react": "^
|
|
53
|
+
"@types/react": "^19.1.2",
|
|
54
|
+
"@types/react-dom": "^19.1.2",
|
|
54
55
|
"happy-dom": "^20.8.3",
|
|
55
|
-
"react": "^
|
|
56
|
-
"react-dom": "^
|
|
56
|
+
"react": "^19.1.0",
|
|
57
|
+
"react-dom": "^19.1.0",
|
|
57
58
|
"tsup": "^8.3.5",
|
|
58
59
|
"typescript": "^5.7.2",
|
|
59
|
-
"@directive-run/core": "0.
|
|
60
|
+
"@directive-run/core": "0.8.0"
|
|
60
61
|
},
|
|
61
62
|
"scripts": {
|
|
62
63
|
"build": "tsup",
|