@directive-run/react 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jason Comes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # @directive-run/react
2
+
3
+ React hooks for Directive. Provides `useSyncExternalStore`-based hooks for reading facts, derivations, and dispatching events.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @directive-run/core @directive-run/react
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```tsx
14
+ import { useFact, useDerived, useEvents } from "@directive-run/react";
15
+
16
+ function Counter({ system }) {
17
+ const count = useFact(system, "count");
18
+ const doubled = useDerived(system, "doubled");
19
+ const events = useEvents(system);
20
+
21
+ return (
22
+ <div>
23
+ <p>Count: {count} (doubled: {doubled})</p>
24
+ <button onClick={() => events.increment()}>+</button>
25
+ </div>
26
+ );
27
+ }
28
+ ```
29
+
30
+ ## Exports
31
+
32
+ `useFact`, `useDerived`, `useSelector`, `useDispatch`, `useEvents`, `useWatch`, `useInspect`, `useRequirementStatus`, `useSuspenseRequirement`, `useExplain`, `useConstraintStatus`, `useOptimisticUpdate`, `useTimeTravel`, `useDirective`, `useDirectiveRef`, `useHydratedSystem`, `DirectiveDevTools`, `DirectiveHydrator`, `shallowEqual`
33
+
34
+ ## Peer Dependencies
35
+
36
+ - `react >= 18`
37
+ - `@directive-run/core`
38
+
39
+ ## License
40
+
41
+ MIT
42
+
43
+ [Full documentation](https://directive.run/docs)
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use strict';var react=require('react'),core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils'),jsxRuntime=require('react/jsx-runtime');var M=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)?oe(e,t):se(e,t)}function se(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(s=>e.facts.$store.subscribe([t],s),[e,t]),i=react.useCallback(()=>e.facts[t],[e,t]);return react.useSyncExternalStore(r,i,i)}function oe(e,t){let r=react.useRef(M),i=react.useCallback(o=>e.facts.$store.subscribe(t,o),[e,...t]),s=react.useCallback(()=>{let o={};for(let n of t)o[n]=e.facts[n];if(r.current!==M){let n=true;for(let u of t)if(!Object.is(r.current[u],o[u])){n=false;break}if(n)return r.current}return r.current=o,o},[e,...t]);return react.useSyncExternalStore(i,s,s)}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)?ue(e,t):ie(e,t)}function ie(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(s=>e.subscribe([t],s),[e,t]),i=react.useCallback(()=>e.read(t),[e,t]);return react.useSyncExternalStore(r,i,i)}function ue(e,t){let r=react.useRef(M),i=react.useCallback(o=>e.subscribe(t,o),[e,...t]),s=react.useCallback(()=>{let o={};for(let n of t)o[n]=e.read(n);if(r.current!==M){let n=true;for(let u of t)if(!Object.is(r.current[u],o[u])){n=false;break}if(n)return r.current}return r.current=o,o},[e,...t]);return react.useSyncExternalStore(i,s,s)}function Re(e,t,r,i){let s,o=false,n;typeof r=="function"&&i===void 0?n=r:(r!==void 0&&(s=r,o=true),n=i??adapterUtils.defaultEquality),process.env.NODE_ENV!=="production"&&!e&&!o&&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 u=react.useRef(t),l=react.useRef(n),S=react.useRef(s);u.current=t,l.current=n,S.current=s;let c=react.useRef([]),g=react.useRef([]),y=react.useRef(M),D=react.useRef([]),h=react.useMemo(()=>e?new Set(Object.keys(e.derive)):new Set,[e]),R=react.useCallback(()=>e?adapterUtils.runTrackedSelector(e,h,u.current):{value:S.current,factKeys:[],deriveKeys:[]},[e,h]),a=react.useCallback(b=>{if(!e)return ()=>{};let K=()=>{for(let p of D.current)p();D.current=[];let{factKeys:F,deriveKeys:T}=R();c.current=F,g.current=T,F.length>0?D.current.push(e.facts.$store.subscribe(F,()=>{let p=R();adapterUtils.depsChanged(c.current,p.factKeys,g.current,p.deriveKeys)&&K(),b();})):T.length===0&&D.current.push(e.facts.$store.subscribeAll(b)),T.length>0&&D.current.push(e.subscribe(T,()=>{let p=R();adapterUtils.depsChanged(c.current,p.factKeys,g.current,p.deriveKeys)&&K(),b();}));};return K(),()=>{for(let F of D.current)F();D.current=[];}},[e,R]),x=react.useCallback(()=>{let b;if(!e)b=S.current;else {let{value:K}=R();b=K===void 0&&o?S.current:K;}return y.current!==M&&l.current(y.current,b)?y.current:(y.current=b,b)},[R,e,o]);return react.useSyncExternalStore(a,x,x)}function xe(e){return adapterUtils.assertSystem("useDispatch",e),react.useCallback(t=>{e.dispatch(t);},[e])}function De(e,t,r,i){adapterUtils.assertSystem("useWatch",e);let s=t==="fact"&&typeof r=="string"&&typeof i=="function",o=s?r:t,n=s?i:r,u=react.useRef(n);u.current=n,react.useEffect(()=>e.watch(o,(l,S)=>{u.current(l,S);}),[e,o]);}function L(e,t){adapterUtils.assertSystem("useInspect",e);let r=ae(e),i=t?.throttleMs,[s,o]=react.useState(r),n=react.useRef(null);return react.useEffect(()=>{if(!i||i<=0){n.current?.cleanup(),n.current=null;return}return n.current?.cleanup(),n.current=adapterUtils.createThrottle((...u)=>{o(u[0]);},i),()=>{n.current?.cleanup(),n.current=null;}},[i]),react.useEffect(()=>{n.current&&n.current.throttled(r);},[r]),!i||i<=0?r:s}function ce(e){return adapterUtils.computeInspectState(e)}function ae(e){let t=react.useRef(null),r=react.useRef([]),i=react.useRef([]),s=react.useRef(null),o=react.useCallback(u=>{let l=e.facts.$store.subscribeAll(u),S=e.onSettledChange(u);return ()=>{l(),S();}},[e]),n=react.useCallback(()=>{let u=ce(e),l=u.unmet.length===r.current.length&&u.unmet.every((g,y)=>g.id===r.current[y]),S=u.inflight.length===i.current.length&&u.inflight.every((g,y)=>g.id===i.current[y]),c=u.isSettled===s.current;return l&&S&&c&&t.current?t.current:(t.current=u,r.current=u.unmet.map(g=>g.id),i.current=u.inflight.map(g=>g.id),s.current=u.isSettled,u)},[e]);return react.useSyncExternalStore(o,n,n)}function ke(e){adapterUtils.assertSystem("useTimeTravel",e);let t=react.useRef(null),r=react.useCallback(s=>e.onTimeTravelChange(s),[e]),i=react.useCallback(()=>{let s=adapterUtils.buildTimeTravelState(e);return s?(t.current&&t.current.canUndo===s.canUndo&&t.current.canRedo===s.canRedo&&t.current.currentIndex===s.currentIndex&&t.current.totalSnapshots===s.totalSnapshots&&t.current.isPaused===s.isPaused||(t.current=s),t.current):null},[e]);return react.useSyncExternalStore(r,i,i)}function Me(e,t){return Array.isArray(t)?de(e,t):le(e,t)}function le(e,t){let r=react.useRef(M),i=react.useCallback(o=>e.subscribe(o),[e]),s=react.useCallback(()=>{let o=e.getStatus(t);if(r.current!==M){let n=r.current;if(n.pending===o.pending&&n.inflight===o.inflight&&n.failed===o.failed&&n.isLoading===o.isLoading&&n.hasError===o.hasError&&n.lastError===o.lastError)return r.current}return r.current=o,o},[e,t]);return react.useSyncExternalStore(i,s,s)}function de(e,t){let r=react.useRef(null),i=react.useRef(""),s=react.useCallback(n=>e.subscribe(n),[e]),o=react.useCallback(()=>{let n={},u=[];for(let S of t){let c=e.getStatus(S);n[S]=c,u.push(`${S}:${c.pending}:${c.inflight}:${c.failed}:${c.hasError}:${c.lastError?.message??""}`);}let l=u.join("|");return l!==i.current&&(i.current=l,r.current=n),r.current??n},[e,...t]);return react.useSyncExternalStore(s,o,o)}var $=new WeakMap;function _(e){let t=$.get(e);return t||(t=new Map,$.set(e,t)),t}function Ie(e,t){return Array.isArray(t)?Se(e,t):fe(e,t)}function fe(e,t){let r=e.getStatus(t);if(r.hasError&&r.lastError)throw r.lastError;if(r.isLoading){let i=_(e),s=i.get(t);throw s||(s=new Promise(o=>{let n=e.subscribe(()=>{e.getStatus(t).isLoading||(i.delete(t),n(),o());});}),i.set(t,s)),s}return r}function Se(e,t){let r={},i=false,s=null;for(let o of t){let n=e.getStatus(o);r[o]=n,n.hasError&&n.lastError&&!s&&(s=n.lastError),n.isLoading&&(i=true);}if(s)throw s;if(i){let o=_(e),n=t.slice().sort().join(","),u=o.get(n);throw u||(u=new Promise(l=>{let S=e.subscribe(()=>{t.every(g=>!e.getStatus(g).isLoading)&&(o.delete(n),S(),l());});}),o.set(n,u)),u}return r}function B(e,t){let r=react.useRef(null),i=react.useRef(null),s=t?.status===true;if(!r.current){let o="id"in e&&"schema"in e,n=o?e:e.module,u=o?{}:e,l=t?.plugins??u.plugins??[],S=t?.debug??u.debug,c=t?.errorBoundary??u.errorBoundary,g=t?.tickMs??u.tickMs,y=t?.zeroConfig??u.zeroConfig,D=t?.initialFacts??u.initialFacts,h=[...l];s&&(i.current=core.createRequirementStatusPlugin(),h=[...h,i.current.plugin]),r.current=core.createSystem({module:n,plugins:h.length>0?h:void 0,debug:S,errorBoundary:c,tickMs:g,zeroConfig:y,initialFacts:D});}return react.useEffect(()=>{let o=r.current;return o?.start(),()=>{o?.destroy(),r.current=null,i.current=null;}},[]),s?{system:r.current,statusPlugin:i.current}:r.current}function we(e,t={}){let{facts:r,derived:i,status:s,...o}=t,n=r??[],u=i??[],l=n.length===0&&u.length===0,S=s?B(e,{status:true,...o}):B(e,o),c=s?S.system:S,g=s?S.statusPlugin:void 0,y=react.useMemo(()=>l?Object.keys(c.derive):[],[c,l]),D=react.useCallback(p=>{let I=[];return l?(I.push(c.facts.$store.subscribeAll(p)),y.length>0&&I.push(c.subscribe(y,p))):(n.length>0&&I.push(c.facts.$store.subscribe(n,p)),u.length>0&&I.push(c.subscribe(u,p))),()=>{for(let P of I)P();}},[c,l,...n,...u,...y]),h=react.useRef(M),R=react.useRef(M),a=react.useRef(null),x=react.useCallback(()=>{let p,I,P,N;if(l){p=c.facts.$store.toObject(),P=Object.keys(p),I={};for(let k of y)I[k]=c.read(k);N=y;}else {p={};for(let k of n)p[k]=c.facts[k];P=n,I={};for(let k of u)I[k]=c.read(k);N=u;}let C=h.current!==M;if(C){let k=h.current;if(Object.keys(k).length!==P.length)C=false;else for(let V of P)if(!Object.is(k[V],p[V])){C=false;break}}let q=R.current!==M;if(q){let k=R.current;if(Object.keys(k).length!==N.length)q=false;else for(let V of N)if(!Object.is(k[V],I[V])){q=false;break}}let z=C?h.current:p,H=q?R.current:I;return C||(h.current=p),q||(R.current=I),C&&q&&a.current||(a.current={facts:z,derived:H}),a.current},[c,l,...n,...u,...y]),b=react.useSyncExternalStore(D,x,x),K=react.useCallback(p=>c.dispatch(p),[c]),F=pe(c),T={system:c,dispatch:K,events:F,facts:b.facts,derived:b.derived};return s&&g?{...T,statusPlugin:g}:T}function Ke({system:e,position:t="bottom-right",defaultOpen:r=false}){let[i,s]=react.useState(r),o=react.useRef(null),{isSettled:n,unmet:u,inflight:l}=L(e);react.useEffect(()=>{i&&o.current&&o.current.focus();},[i]);let S=react.useCallback(a=>e.facts.$store.subscribeAll(a),[e]),c=react.useRef(M),g=react.useCallback(()=>{let a=e.facts.$store.toObject();if(c.current!==M){let x=Object.keys(c.current),b=Object.keys(a);if(x.length===b.length){let K=true;for(let F of b)if(!Object.is(c.current[F],a[F])){K=false;break}if(K)return c.current}}return c.current=a,a},[e]),y=react.useSyncExternalStore(S,g,g);if(process.env.NODE_ENV==="production")return null;let D={position:"fixed",zIndex:99999,...t.includes("bottom")?{bottom:12}:{top:12},...t.includes("right")?{right:12}:{left:12}};if(!i)return jsxRuntime.jsx("button",{type:"button",onClick:()=>s(true),"aria-label":`Open Directive DevTools${n?"":" (system working)"}`,"aria-expanded":false,style:{...D,background:"#1a1a2e",color:"#e0e0e0",border:"1px solid #333",borderRadius:6,padding:"6px 12px",cursor:"pointer",fontFamily:"monospace",fontSize:12},children:n?"Directive":"Directive..."});let h=Object.keys(e.derive),R={};for(let a of h)try{R[a]=e.read(a);}catch{R[a]="<error>";}return jsxRuntime.jsxs("div",{role:"region","aria-label":"Directive DevTools",tabIndex:-1,onKeyDown:a=>{a.key==="Escape"&&s(false);},style:{...D,background:"#1a1a2e",color:"#e0e0e0",border:"1px solid #333",borderRadius:8,padding:12,fontFamily:"monospace",fontSize:11,maxWidth:380,maxHeight:500,overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.5)"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:8},children:[jsxRuntime.jsx("strong",{style:{color:"#7c8aff"},children:"Directive DevTools"}),jsxRuntime.jsx("button",{ref:o,type:"button",onClick:()=>s(false),"aria-label":"Close DevTools",style:{background:"none",border:"none",color:"#888",cursor:"pointer",fontSize:14},children:"\xD7"})]}),jsxRuntime.jsx("div",{style:{marginBottom:6},"aria-live":"polite",children:jsxRuntime.jsx("span",{style:{color:n?"#4ade80":"#fbbf24"},children:n?"Settled":"Working..."})}),jsxRuntime.jsxs("details",{open:true,children:[jsxRuntime.jsxs("summary",{style:{cursor:"pointer",color:"#7c8aff",marginBottom:4},children:["Facts (",Object.keys(y).length,")"]}),jsxRuntime.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{children:[jsxRuntime.jsx("th",{style:{textAlign:"left",padding:"2px 4px",color:"#7c8aff"},children:"Key"}),jsxRuntime.jsx("th",{style:{textAlign:"left",padding:"2px 4px",color:"#7c8aff"},children:"Value"})]})}),jsxRuntime.jsx("tbody",{children:Object.entries(y).map(([a,x])=>{let b;try{b=typeof x=="object"?JSON.stringify(x):String(x);}catch{b="<error>";}return jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #2a2a4a"},children:[jsxRuntime.jsx("td",{style:{padding:"2px 4px",color:"#a0a0c0"},children:a}),jsxRuntime.jsx("td",{style:{padding:"2px 4px"},children:b})]},a)})})]})]}),h.length>0&&jsxRuntime.jsxs("details",{children:[jsxRuntime.jsxs("summary",{style:{cursor:"pointer",color:"#7c8aff",marginBottom:4},children:["Derivations (",h.length,")"]}),jsxRuntime.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{children:[jsxRuntime.jsx("th",{style:{textAlign:"left",padding:"2px 4px",color:"#7c8aff"},children:"Key"}),jsxRuntime.jsx("th",{style:{textAlign:"left",padding:"2px 4px",color:"#7c8aff"},children:"Value"})]})}),jsxRuntime.jsx("tbody",{children:Object.entries(R).map(([a,x])=>jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #2a2a4a"},children:[jsxRuntime.jsx("td",{style:{padding:"2px 4px",color:"#a0a0c0"},children:a}),jsxRuntime.jsx("td",{style:{padding:"2px 4px"},children:typeof x=="object"?JSON.stringify(x):String(x)})]},a))})]})]}),l.length>0&&jsxRuntime.jsxs("details",{open:true,children:[jsxRuntime.jsxs("summary",{style:{cursor:"pointer",color:"#fbbf24",marginBottom:4},children:["Inflight (",l.length,")"]}),jsxRuntime.jsx("ul",{style:{margin:0,paddingLeft:16},children:l.map(a=>jsxRuntime.jsxs("li",{style:{fontSize:11},children:[a.resolverId," (",a.id,")"]},a.id))})]}),u.length>0&&jsxRuntime.jsxs("details",{open:true,children:[jsxRuntime.jsxs("summary",{style:{cursor:"pointer",color:"#f87171",marginBottom:4},children:["Unmet (",u.length,")"]}),jsxRuntime.jsx("ul",{style:{margin:0,paddingLeft:16},children:u.map(a=>jsxRuntime.jsxs("li",{style:{fontSize:11},children:[a.requirement.type," from ",a.fromConstraint]},a.id))})]})]})}function pe(e){return adapterUtils.assertSystem("useEvents",e),react.useMemo(()=>e.events,[e])}function Fe(e,t){adapterUtils.assertSystem("useExplain",e);let r=react.useCallback(s=>{let o=e.facts.$store.subscribeAll(s),n=e.onSettledChange(s);return ()=>{o(),n();}},[e]),i=react.useCallback(()=>e.explain(t),[e,t]);return react.useSyncExternalStore(r,i,i)}function Ee(e,t){adapterUtils.assertSystem("useConstraintStatus",e);let r=L(e);return react.useMemo(()=>{let i=e.inspect();return t?i.constraints.find(s=>s.id===t)??null:i.constraints},[e,t,r])}function Te(e,t,r){adapterUtils.assertSystem("useOptimisticUpdate",e);let[i,s]=react.useState(false),[o,n]=react.useState(null),u=react.useRef(null),l=react.useCallback(()=>{u.current&&(e.restore(u.current),u.current=null),s(false),n(null);},[e]),S=react.useCallback(c=>{u.current=e.getSnapshot(),s(true),n(null),e.batch(c);},[e]);return react.useEffect(()=>{if(!(!t||!r||!i))return t.subscribe(()=>{let c=t.getStatus(r);!c.isLoading&&!c.hasError?(u.current=null,s(false)):c.hasError&&(n(c.lastError),l());})},[t,r,i,l]),{mutate:S,isPending:i,error:o,rollback:l}}var W=react.createContext(null);function Pe({snapshot:e,children:t}){return jsxRuntime.jsx(W.Provider,{value:e,children:t})}function Ce(e,t){let r=react.useContext(W),i=react.useMemo(()=>r?.data?{...t??{},initialFacts:{...t?.initialFacts??{},...r.data}}:t??{},[r,t]);return B(e,i)}Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return adapterUtils.shallowEqual}});exports.DirectiveDevTools=Ke;exports.DirectiveHydrator=Pe;exports.useConstraintStatus=Ee;exports.useDerived=he;exports.useDirective=we;exports.useDirectiveRef=B;exports.useDispatch=xe;exports.useEvents=pe;exports.useExplain=Fe;exports.useFact=me;exports.useHydratedSystem=Ce;exports.useInspect=L;exports.useOptimisticUpdate=Te;exports.useRequirementStatus=Me;exports.useSelector=Re;exports.useSuspenseRequirement=Ie;exports.useTimeTravel=ke;exports.useWatch=De;//# sourceMappingURL=index.cjs.map
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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","selector","defaultValueOrEqFn","maybeEqFn","defaultValue","hasDefault","equalityFn","defaultEquality","selectorRef","eqRef","defaultValueRef","trackedFactKeysRef","trackedDeriveKeysRef","unsubsRef","deriveKeys","useMemo","runWithTracking","runTrackedSelector","resubscribe","unsub","derivedKeys","updated","depsChanged","effectiveValue","newValue","useDispatch","event","useWatch","derivationIdOrKind","callbackOrFactKey","maybeCallback","isFact","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","wantStatus","isModule","mod","baseOpts","plugins","debug","errorBoundary","tickMs","zeroConfig","initialFacts","allPlugins","createRequirementStatusPlugin","createSystem","sys","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","DirectiveDevTools","position","defaultOpen","isOpen","setIsOpen","closeButtonRef","isSettled","unmet","inflight","factsSubscribe","factsRef","getFactsSnapshot","current","prevKeys","currKeys","facts","positionStyles","jsx","derivationKeys","derivations","jsxs","e","value","display","r","useExplain","requirementId","useConstraintStatus","constraintId","inspectState","inspection","c","useOptimisticUpdate","requirementType","isPending","setIsPending","error","setError","snapshotRef","rollback","mutate","updateFn","HydrationContext","createContext","DirectiveHydrator","snapshot","children","useHydratedSystem","moduleDef","useContext","mergedConfig"],"mappings":"8KAwFA,IAAMA,CAAAA,CAAgB,MAAA,CAAO,yBAAyB,CAAA,CAmB/C,SAASC,GAEfC,CAAAA,CACAC,CAAAA,CACU,CAUV,OATAC,yBAAAA,CAAa,UAAWF,CAAM,CAAA,CAC1B,QAAQ,GAAA,CAAI,QAAA,GAAa,cAAgB,OAAOC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AEhD,CAAE,MAAA,CAAAC,CAAAA,CAAQ,SAAA,CAAAN,EAAW,KAAA,CAAAE,CAAAA,CAAO,SAAAG,CAAS,CAC7C,CAaA,IAAMG,CAAAA,CAAmBC,mBAAAA,CAA4C,IAAI,CAAA,CAclE,SAASC,GAAkB,CAAE,QAAA,CAAAC,EAAU,QAAA,CAAAC,CAAS,EAAkB,CACxE,OACC7B,cAAAA,CAACyB,CAAAA,CAAiB,QAAA,CAAjB,CAA0B,MAAOG,CAAAA,CAChC,QAAA,CAAAC,EACF,CAEF,CAeO,SAASC,EAAAA,CACfC,CAAAA,CACA3F,CAAAA,CACwB,CACxB,IAAMwF,CAAAA,CAAWI,iBAAWP,CAAgB,CAAA,CAGtCQ,EAAezK,aAAAA,CAAQ,IACvBoK,GAAU,IAAA,CACR,CACN,GAAIxF,CAAAA,EAAU,EAAC,CACf,aAAc,CACb,GAAIA,GAAQ,YAAA,EAAgB,GAC5B,GAAGwF,CAAAA,CAAS,IACb,CACD,CAAA,CAP4BxF,CAAAA,EAAU,EAAC,CAQrC,CAACwF,EAAUxF,CAAM,CAAC,EAErB,OAAOD,CAAAA,CAAgB4F,CAAAA,CAAWE,CAAY,CAC/C","file":"index.cjs","sourcesContent":["/**\n * React Adapter - Consolidated hooks for React integration\n *\n * 19 public exports: useFact, useDerived, useDispatch, useDirective,\n * useDirectiveRef, useSelector, useWatch, useInspect, useRequirementStatus,\n * useSuspenseRequirement, useEvents, useExplain, useConstraintStatus,\n * useOptimisticUpdate, DirectiveDevTools, 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 { ReactNode } from \"react\";\nimport {\n\tuseSyncExternalStore,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState,\n\tcreateContext,\n\tuseContext,\n} from \"react\";\nimport type {\n\tModuleSchema,\n\tModuleDef,\n\tPlugin,\n\tDebugConfig,\n\tErrorBoundaryConfig,\n\tInferFacts,\n\tInferDerivations,\n\tInferSelectorState,\n\tInferEvents,\n\tSingleModuleSystem,\n\tSystemSnapshot,\n\tDistributableSnapshot,\n\tTimeTravelState,\n} from \"@directive-run/core\";\nimport {\n\tcreateSystem,\n\tcreateRequirementStatusPlugin,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n\ttype InspectState,\n\ttype ConstraintInfo,\n\tcomputeInspectState,\n\tcreateThrottle,\n\tassertSystem,\n\tdefaultEquality,\n\tbuildTimeTravelState,\n\trunTrackedSelector,\n\tdepsChanged,\n\tshallowEqual,\n} from \"@directive-run/core/adapter-utils\";\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<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tfactKey: K,\n): InferFacts<S>[K] | undefined;\n\n/** Multi-key overload */\nexport function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tfactKeys: K[],\n): Pick<InferFacts<S>, K>;\n\n/** Implementation */\nexport function useFact(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tkeyOrKeys: string | string[],\n): unknown {\n\tassertSystem(\"useFact\", system);\n\tif (process.env.NODE_ENV !== \"production\" && typeof keyOrKeys === \"function\") {\n\t\tconsole.error(\n\t\t\t\"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n\t\t\t\t\"useFact() takes a string key or array of keys, not a selector function.\",\n\t\t);\n\t}\n\n\t// Multi-key path: useFact(system, [keys])\n\tif (Array.isArray(keyOrKeys)) {\n\t\treturn _useFacts(system, keyOrKeys);\n\t}\n\n\t// Single key path: useFact(system, key)\n\treturn _useSingleFact(system, keyOrKeys);\n}\n\nfunction _useSingleFact(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tfactKey: string,\n): unknown {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!(factKey in system.facts.$store.toObject())) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] useFact(\"${factKey}\") — fact not found in store. ` +\n\t\t\t\t\t`Check that \"${factKey}\" is defined in your module's schema.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn system.facts.$store.subscribe([factKey], onStoreChange);\n\t\t},\n\t\t[system, factKey],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n\t\treturn (system.facts as any)[factKey];\n\t}, [system, factKey]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useFacts(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tfactKeys: string[],\n): Record<string, unknown> {\n\tconst cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn system.facts.$store.subscribe(factKeys, onStoreChange);\n\t\t},\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[system, ...factKeys],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of factKeys) {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n\t\t\tresult[key] = (system.facts as any)[key];\n\t\t}\n\n\t\tif (cachedValue.current !== UNINITIALIZED) {\n\t\t\tlet same = true;\n\t\t\tfor (const key of factKeys) {\n\t\t\t\tif (!Object.is((cachedValue.current as Record<string, unknown>)[key], result[key])) {\n\t\t\t\t\tsame = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (same) return cachedValue.current;\n\t\t}\n\n\t\tcachedValue.current = result;\n\t\treturn result;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [system, ...factKeys]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tderivationId: K,\n): InferDerivations<S>[K];\n\n/** Multi-key overload */\nexport function useDerived<\n\tS extends ModuleSchema,\n\tK extends keyof InferDerivations<S> & string,\n>(\n\tsystem: SingleModuleSystem<S>,\n\tderivationIds: K[],\n): Pick<InferDerivations<S>, K>;\n\n/** Implementation */\nexport function useDerived(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tkeyOrKeys: string | string[],\n): unknown {\n\tassertSystem(\"useDerived\", system);\n\tif (process.env.NODE_ENV !== \"production\" && typeof keyOrKeys === \"function\") {\n\t\tconsole.error(\n\t\t\t\"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n\t\t\t\t\"useDerived() takes a string key or array of keys, not a selector function.\",\n\t\t);\n\t}\n\n\t// Multi-key path\n\tif (Array.isArray(keyOrKeys)) {\n\t\treturn _useDerivedMulti(system, keyOrKeys);\n\t}\n\n\t// Single key path\n\treturn _useSingleDerived(system, keyOrKeys);\n}\n\nfunction _useSingleDerived(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tderivationId: string,\n): unknown {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!(derivationId in system.derive)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] useDerived(\"${derivationId}\") — derivation not found. ` +\n\t\t\t\t\t`Check that \"${derivationId}\" is defined in your module's derive property.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn system.subscribe([derivationId], onStoreChange);\n\t\t},\n\t\t[system, derivationId],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\treturn system.read(derivationId);\n\t}, [system, derivationId]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useDerivedMulti(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tderivationIds: string[],\n): Record<string, unknown> {\n\tconst cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn system.subscribe(derivationIds, onStoreChange);\n\t\t},\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[system, ...derivationIds],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const id of derivationIds) {\n\t\t\tresult[id] = system.read(id);\n\t\t}\n\n\t\tif (cachedValue.current !== UNINITIALIZED) {\n\t\t\tlet same = true;\n\t\t\tfor (const id of derivationIds) {\n\t\t\t\tif (!Object.is((cachedValue.current as Record<string, unknown>)[id], result[id])) {\n\t\t\t\t\tsame = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (same) return cachedValue.current;\n\t\t}\n\n\t\tcachedValue.current = result;\n\t\treturn result;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [system, ...derivationIds]);\n\n\treturn 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\n// Existing: non-null system, no default (equalityFn as 3rd param)\nexport function useSelector<S extends ModuleSchema, R>(\n\tsystem: SingleModuleSystem<S>,\n\tselector: (state: InferSelectorState<S>) => R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// New: non-null system, with default value\nexport function useSelector<S extends ModuleSchema, R>(\n\tsystem: SingleModuleSystem<S>,\n\tselector: (state: InferSelectorState<S>) => R,\n\tdefaultValue: R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// New: nullable system, default REQUIRED\nexport function useSelector<S extends ModuleSchema, R>(\n\tsystem: SingleModuleSystem<S> | null | undefined,\n\tselector: (state: InferSelectorState<S>) => R,\n\tdefaultValue: R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Backward-compatible `any` fallback: equalityFn as 3rd param\nexport function useSelector<R>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any>,\n\t// biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n\tselector: (state: Record<string, any>) => R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Backward-compatible `any` fallback: default value + nullable system\nexport function useSelector<R>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any> | null | undefined,\n\t// biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n\tselector: (state: Record<string, any>) => R,\n\tdefaultValue: R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\nexport function useSelector(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any> | null | undefined,\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tselector: (state: any) => unknown,\n\tdefaultValueOrEqFn?: unknown,\n\tmaybeEqFn?: (a: unknown, b: unknown) => boolean,\n): unknown {\n\t// Discriminate arg3: function → old API (equalityFn), otherwise → new API (defaultValue)\n\tlet defaultValue: unknown;\n\tlet hasDefault = false;\n\tlet equalityFn: (a: unknown, b: unknown) => boolean;\n\n\tif (typeof defaultValueOrEqFn === \"function\" && maybeEqFn === undefined) {\n\t\t// Old API: useSelector(system, selector, equalityFn)\n\t\tequalityFn = defaultValueOrEqFn as (a: unknown, b: unknown) => boolean;\n\t} else {\n\t\t// New API: useSelector(system, selector, defaultValue, equalityFn?)\n\t\t// Also covers: useSelector(system, selector) when defaultValueOrEqFn is undefined\n\t\tif (defaultValueOrEqFn !== undefined) {\n\t\t\tdefaultValue = defaultValueOrEqFn;\n\t\t\thasDefault = true;\n\t\t}\n\t\tequalityFn = maybeEqFn ?? defaultEquality;\n\t}\n\n\t// Dev-mode warning: null system without a default value\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!system && !hasDefault) {\n\t\t\tconsole.error(\n\t\t\t\t\"[Directive] useSelector() received a null/undefined system without a default value. \" +\n\t\t\t\t\t\"Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)\",\n\t\t\t);\n\t\t}\n\t}\n\n\t// Store selector/eq/default in refs to avoid resubscription churn\n\tconst selectorRef = useRef(selector);\n\tconst eqRef = useRef(equalityFn);\n\tconst defaultValueRef = useRef(defaultValue);\n\tselectorRef.current = selector;\n\teqRef.current = equalityFn;\n\tdefaultValueRef.current = defaultValue;\n\n\tconst trackedFactKeysRef = useRef<string[]>([]);\n\tconst trackedDeriveKeysRef = useRef<string[]>([]);\n\tconst cachedValue = useRef<unknown>(UNINITIALIZED);\n\tconst unsubsRef = useRef<Array<() => void>>([]);\n\n\t// Build a tracking-aware state proxy that exposes both facts and derivations\n\tconst deriveKeys = useMemo(\n\t\t() => (system ? new Set(Object.keys(system.derive)) : new Set<string>()),\n\t\t[system],\n\t);\n\n\tconst runWithTracking = useCallback(() => {\n\t\tif (!system) {\n\t\t\treturn { value: defaultValueRef.current, factKeys: [] as string[], deriveKeys: [] as string[] };\n\t\t}\n\n\t\treturn runTrackedSelector(system, deriveKeys, selectorRef.current);\n\t}, [system, deriveKeys]);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\tif (!system) {\n\t\t\t\t// No system — return noop unsubscribe\n\t\t\t\treturn () => {};\n\t\t\t}\n\n\t\t\tconst resubscribe = () => {\n\t\t\t\t// Cleanup previous subscriptions\n\t\t\t\tfor (const unsub of unsubsRef.current) unsub();\n\t\t\t\tunsubsRef.current = [];\n\n\t\t\t\t// Run selector with tracking to detect accessed keys\n\t\t\t\tconst { factKeys, deriveKeys: derivedKeys } = runWithTracking();\n\t\t\t\ttrackedFactKeysRef.current = factKeys;\n\t\t\t\ttrackedDeriveKeysRef.current = derivedKeys;\n\n\t\t\t\t// Subscribe to accessed fact keys\n\t\t\t\tif (factKeys.length > 0) {\n\t\t\t\t\tunsubsRef.current.push(\n\t\t\t\t\t\tsystem.facts.$store.subscribe(factKeys, () => {\n\t\t\t\t\t\t\t// Re-track on notification for dynamic deps\n\t\t\t\t\t\t\tconst updated = runWithTracking();\n\t\t\t\t\t\t\tif (depsChanged(trackedFactKeysRef.current, updated.factKeys, trackedDeriveKeysRef.current, updated.deriveKeys)) resubscribe();\n\t\t\t\t\t\t\tonStoreChange();\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t} else if (derivedKeys.length === 0) {\n\t\t\t\t\t// No deps at all — subscribe to everything\n\t\t\t\t\tunsubsRef.current.push(\n\t\t\t\t\t\tsystem.facts.$store.subscribeAll(onStoreChange),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Subscribe to accessed derivation keys\n\t\t\t\tif (derivedKeys.length > 0) {\n\t\t\t\t\tunsubsRef.current.push(\n\t\t\t\t\t\tsystem.subscribe(derivedKeys, () => {\n\t\t\t\t\t\t\t// Re-track on notification for dynamic deps\n\t\t\t\t\t\t\tconst updated = runWithTracking();\n\t\t\t\t\t\t\tif (depsChanged(trackedFactKeysRef.current, updated.factKeys, trackedDeriveKeysRef.current, updated.deriveKeys)) resubscribe();\n\t\t\t\t\t\t\tonStoreChange();\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tresubscribe();\n\n\t\t\treturn () => {\n\t\t\t\tfor (const unsub of unsubsRef.current) unsub();\n\t\t\t\tunsubsRef.current = [];\n\t\t\t};\n\t\t},\n\t\t[system, runWithTracking],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tlet effectiveValue: unknown;\n\n\t\tif (!system) {\n\t\t\teffectiveValue = defaultValueRef.current;\n\t\t} else {\n\t\t\tconst { value: newValue } = runWithTracking();\n\n\t\t\t// When selector returns undefined and we have a default, use it\n\t\t\teffectiveValue = newValue === undefined && hasDefault ? defaultValueRef.current : newValue;\n\t\t}\n\n\t\tif (\n\t\t\tcachedValue.current !== UNINITIALIZED &&\n\t\t\teqRef.current(cachedValue.current, effectiveValue)\n\t\t) {\n\t\t\treturn cachedValue.current;\n\t\t}\n\t\tcachedValue.current = effectiveValue;\n\n\t\treturn effectiveValue;\n\t}, [runWithTracking, system, hasDefault]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n\tsystem: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n\tassertSystem(\"useDispatch\", system);\n\treturn useCallback(\n\t\t(event: InferEvents<S>) => {\n\t\t\tsystem.dispatch(event);\n\t\t},\n\t\t[system],\n\t);\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\tS extends ModuleSchema,\n\tK extends keyof InferDerivations<S> & string,\n>(\n\tsystem: SingleModuleSystem<S>,\n\tkey: K,\n\tcallback: (\n\t\tnewValue: InferDerivations<S>[K],\n\t\tprevValue: InferDerivations<S>[K] | undefined,\n\t) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n\tS extends ModuleSchema,\n\tK extends keyof InferFacts<S> & string,\n>(\n\tsystem: SingleModuleSystem<S>,\n\tkey: K,\n\tcallback: (\n\t\tnewValue: InferFacts<S>[K] | undefined,\n\t\tprevValue: InferFacts<S>[K] | undefined,\n\t) => void,\n): void;\n\n/**\n * Watch a fact by explicit \"fact\" discriminator.\n * @deprecated Use `useWatch(system, key, callback)` instead — facts are now auto-detected.\n */\nexport function useWatch<\n\tS extends ModuleSchema,\n\tK extends keyof InferFacts<S> & string,\n>(\n\tsystem: SingleModuleSystem<S>,\n\tkind: \"fact\",\n\tfactKey: K,\n\tcallback: (\n\t\tnewValue: InferFacts<S>[K] | undefined,\n\t\tprevValue: InferFacts<S>[K] | undefined,\n\t) => void,\n): void;\n\n/** Watch a fact or derivation (generic fallback) */\nexport function useWatch<T>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any>,\n\tkey: string,\n\tcallback: (newValue: T, prevValue: T | undefined) => void,\n): void;\n\n/** Implementation */\nexport function useWatch(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tderivationIdOrKind: string,\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n\tcallbackOrFactKey: string | ((newValue: any, prevValue: any) => void),\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n\tmaybeCallback?: (newValue: any, prevValue: any) => void,\n): void {\n\tassertSystem(\"useWatch\", system);\n\t// Backward compat: useWatch(system, \"fact\", factKey, callback)\n\tconst isFact =\n\t\tderivationIdOrKind === \"fact\" &&\n\t\ttypeof callbackOrFactKey === \"string\" &&\n\t\ttypeof maybeCallback === \"function\";\n\tconst key = isFact ? (callbackOrFactKey as string) : derivationIdOrKind;\n\tconst callback = isFact\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n\t\t? (maybeCallback as (newValue: any, prevValue: any) => void)\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n\t\t: (callbackOrFactKey as (newValue: any, prevValue: any) => void);\n\n\tconst callbackRef = useRef(callback);\n\tcallbackRef.current = callback;\n\n\tuseEffect(() => {\n\t\treturn system.watch(key, (newValue, prevValue) => {\n\t\t\tcallbackRef.current(newValue, prevValue);\n\t\t});\n\t}, [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\t/** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */\n\tthrottleMs?: 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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\toptions?: UseInspectOptions,\n): InspectState {\n\tassertSystem(\"useInspect\", system);\n\t// Always call the sync version (useSyncExternalStore path) — no conditional hooks\n\tconst syncState = _useInspectSync(system);\n\n\tconst throttleMs = options?.throttleMs;\n\tconst [deferredState, setDeferredState] = useState(syncState);\n\tconst throttleRef = useRef<{ throttled: (...args: unknown[]) => void; cleanup: () => void } | null>(null);\n\n\t// Create/recreate throttle when throttleMs changes\n\tuseEffect(() => {\n\t\tif (!throttleMs || throttleMs <= 0) {\n\t\t\tthrottleRef.current?.cleanup();\n\t\t\tthrottleRef.current = null;\n\t\t\treturn;\n\t\t}\n\t\t// Clean up old throttle before creating new one\n\t\tthrottleRef.current?.cleanup();\n\t\tthrottleRef.current = createThrottle(\n\t\t\t(...args: unknown[]) => { setDeferredState(args[0] as InspectState); },\n\t\t\tthrottleMs,\n\t\t);\n\t\treturn () => {\n\t\t\tthrottleRef.current?.cleanup();\n\t\t\tthrottleRef.current = null;\n\t\t};\n\t}, [throttleMs]);\n\n\t// Feed sync state through throttle after each render\n\tuseEffect(() => {\n\t\tif (throttleRef.current) {\n\t\t\tthrottleRef.current.throttled(syncState);\n\t\t}\n\t}, [syncState]);\n\n\tif (!throttleMs || throttleMs <= 0) return syncState;\n\treturn deferredState;\n}\n\nfunction _buildInspectState(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n): InspectState {\n\treturn computeInspectState(system);\n}\n\nfunction _useInspectSync(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n): InspectState {\n\tconst cachedSnapshot = useRef<InspectState | null>(null);\n\tconst cachedUnmetIds = useRef<string[]>([]);\n\tconst cachedInflightIds = useRef<string[]>([]);\n\tconst cachedIsSettled = useRef<boolean | null>(null);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\tconst unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n\t\t\tconst unsubSettled = system.onSettledChange(onStoreChange);\n\t\t\treturn () => {\n\t\t\t\tunsubFacts();\n\t\t\t\tunsubSettled();\n\t\t\t};\n\t\t},\n\t\t[system],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst state = _buildInspectState(system);\n\n\t\tconst unmetSame =\n\t\t\tstate.unmet.length === cachedUnmetIds.current.length &&\n\t\t\tstate.unmet.every((u, i) => u.id === cachedUnmetIds.current[i]);\n\t\tconst inflightSame =\n\t\t\tstate.inflight.length === cachedInflightIds.current.length &&\n\t\t\tstate.inflight.every((f, i) => f.id === cachedInflightIds.current[i]);\n\t\tconst settledSame = state.isSettled === cachedIsSettled.current;\n\n\t\tif (unmetSame && inflightSame && settledSame && cachedSnapshot.current) {\n\t\t\treturn cachedSnapshot.current;\n\t\t}\n\n\t\tcachedSnapshot.current = state;\n\t\tcachedUnmetIds.current = state.unmet.map((u) => u.id);\n\t\tcachedInflightIds.current = state.inflight.map((f) => f.id);\n\t\tcachedIsSettled.current = state.isSettled;\n\n\t\treturn state;\n\t}, [system]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n): TimeTravelState | null {\n\tassertSystem(\"useTimeTravel\", system);\n\tconst cachedRef = useRef<TimeTravelState | null>(null);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => system.onTimeTravelChange(onStoreChange),\n\t\t[system],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst state = buildTimeTravelState(system);\n\t\tif (!state) return null;\n\n\t\t// Return stable reference when values haven't changed\n\t\tif (\n\t\t\tcachedRef.current &&\n\t\t\tcachedRef.current.canUndo === state.canUndo &&\n\t\t\tcachedRef.current.canRedo === state.canRedo &&\n\t\t\tcachedRef.current.currentIndex === state.currentIndex &&\n\t\t\tcachedRef.current.totalSnapshots === state.totalSnapshots &&\n\t\t\tcachedRef.current.isPaused === state.isPaused\n\t\t) {\n\t\t\treturn cachedRef.current;\n\t\t}\n\n\t\tcachedRef.current = state;\n\t\treturn cachedRef.current;\n\t}, [system]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n\tstatusPlugin: StatusPlugin,\n\ttype: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useRequirementStatus(\n\tstatusPlugin: StatusPlugin,\n\ttypes: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useRequirementStatus(\n\tstatusPlugin: StatusPlugin,\n\ttypeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n\tif (Array.isArray(typeOrTypes)) {\n\t\treturn _useRequirementStatusMulti(statusPlugin, typeOrTypes);\n\t}\n\treturn _useRequirementStatusSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useRequirementStatusSingle(\n\tstatusPlugin: StatusPlugin,\n\ttype: string,\n): RequirementTypeStatus {\n\tconst cachedRef = useRef<RequirementTypeStatus | typeof UNINITIALIZED>(UNINITIALIZED);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn statusPlugin.subscribe(onStoreChange);\n\t\t},\n\t\t[statusPlugin],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst status = statusPlugin.getStatus(type);\n\n\t\tif (cachedRef.current !== UNINITIALIZED) {\n\t\t\tconst prev = cachedRef.current;\n\t\t\tif (\n\t\t\t\tprev.pending === status.pending &&\n\t\t\t\tprev.inflight === status.inflight &&\n\t\t\t\tprev.failed === status.failed &&\n\t\t\t\tprev.isLoading === status.isLoading &&\n\t\t\t\tprev.hasError === status.hasError &&\n\t\t\t\tprev.lastError === status.lastError\n\t\t\t) {\n\t\t\t\treturn cachedRef.current;\n\t\t\t}\n\t\t}\n\n\t\tcachedRef.current = status;\n\t\treturn status;\n\t}, [statusPlugin, type]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useRequirementStatusMulti(\n\tstatusPlugin: StatusPlugin,\n\ttypes: string[],\n): Record<string, RequirementTypeStatus> {\n\tconst cachedRef = useRef<Record<string, RequirementTypeStatus> | null>(null);\n\tconst cachedKey = useRef<string>(\"\");\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn statusPlugin.subscribe(onStoreChange);\n\t\t},\n\t\t[statusPlugin],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst result: Record<string, RequirementTypeStatus> = {};\n\t\tconst parts: string[] = [];\n\t\tfor (const type of types) {\n\t\t\tconst status = statusPlugin.getStatus(type);\n\t\t\tresult[type] = status;\n\t\t\tparts.push(`${type}:${status.pending}:${status.inflight}:${status.failed}:${status.hasError}:${status.lastError?.message ?? \"\"}`);\n\t\t}\n\t\tconst key = parts.join(\"|\");\n\n\t\tif (key !== cachedKey.current) {\n\t\t\tcachedKey.current = key;\n\t\t\tcachedRef.current = result;\n\t\t}\n\n\t\treturn cachedRef.current ?? result;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [statusPlugin, ...types]);\n\n\treturn 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<StatusPlugin, Map<string, Promise<void>>>();\n\nfunction getSuspenseCache(plugin: StatusPlugin): Map<string, Promise<void>> {\n\tlet cache = suspenseCacheMap.get(plugin);\n\tif (!cache) {\n\t\tcache = new Map();\n\t\tsuspenseCacheMap.set(plugin, cache);\n\t}\n\treturn cache;\n}\n\n/** Single type overload */\nexport function useSuspenseRequirement(\n\tstatusPlugin: StatusPlugin,\n\ttype: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useSuspenseRequirement(\n\tstatusPlugin: StatusPlugin,\n\ttypes: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useSuspenseRequirement(\n\tstatusPlugin: StatusPlugin,\n\ttypeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n\tif (Array.isArray(typeOrTypes)) {\n\t\treturn _useSuspenseRequirementMulti(statusPlugin, typeOrTypes);\n\t}\n\treturn _useSuspenseRequirementSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useSuspenseRequirementSingle(\n\tstatusPlugin: StatusPlugin,\n\ttype: string,\n): RequirementTypeStatus {\n\tconst status = statusPlugin.getStatus(type);\n\n\tif (status.hasError && status.lastError) {\n\t\tthrow status.lastError;\n\t}\n\n\tif (status.isLoading) {\n\t\tconst cache = getSuspenseCache(statusPlugin);\n\t\tlet promise = cache.get(type);\n\n\t\tif (!promise) {\n\t\t\tpromise = new Promise<void>((resolve) => {\n\t\t\t\tconst unsubscribe = statusPlugin.subscribe(() => {\n\t\t\t\t\tconst currentStatus = statusPlugin.getStatus(type);\n\t\t\t\t\tif (!currentStatus.isLoading) {\n\t\t\t\t\t\tcache.delete(type);\n\t\t\t\t\t\tunsubscribe();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t\tcache.set(type, promise);\n\t\t}\n\n\t\tthrow promise;\n\t}\n\n\treturn status;\n}\n\nfunction _useSuspenseRequirementMulti(\n\tstatusPlugin: StatusPlugin,\n\ttypes: string[],\n): Record<string, RequirementTypeStatus> {\n\tconst result: Record<string, RequirementTypeStatus> = {};\n\tlet hasLoading = false;\n\tlet firstError: Error | null = null;\n\n\tfor (const type of types) {\n\t\tconst status = statusPlugin.getStatus(type);\n\t\tresult[type] = status;\n\n\t\tif (status.hasError && status.lastError && !firstError) {\n\t\t\tfirstError = status.lastError;\n\t\t}\n\t\tif (status.isLoading) {\n\t\t\thasLoading = true;\n\t\t}\n\t}\n\n\tif (firstError) {\n\t\tthrow firstError;\n\t}\n\n\tif (hasLoading) {\n\t\tconst cache = getSuspenseCache(statusPlugin);\n\t\tconst cacheKey = types.slice().sort().join(\",\");\n\t\tlet promise = cache.get(cacheKey);\n\n\t\tif (!promise) {\n\t\t\tpromise = new Promise<void>((resolve) => {\n\t\t\t\tconst unsubscribe = statusPlugin.subscribe(() => {\n\t\t\t\t\tconst allDone = types.every((t) => !statusPlugin.getStatus(t).isLoading);\n\t\t\t\t\tif (allDone) {\n\t\t\t\t\t\tcache.delete(cacheKey);\n\t\t\t\t\t\tunsubscribe();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t\tcache.set(cacheKey, promise);\n\t\t}\n\n\t\tthrow promise;\n\t}\n\n\treturn result;\n}\n\n// ============================================================================\n// useDirectiveRef — scoped system lifecycle\n// ============================================================================\n\n/** Base options for creating a scoped system */\ninterface DirectiveRefBaseConfig {\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n\tplugins?: Plugin<any>[];\n\tdebug?: DebugConfig;\n\terrorBoundary?: ErrorBoundaryConfig;\n\ttickMs?: number;\n\tzeroConfig?: boolean;\n\t// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n\tinitialFacts?: Record<string, any>;\n}\n\n/** Options for useDirectiveRef: module directly, or config object */\nexport type UseDirectiveRefOptions<M extends ModuleSchema> =\n\t| ModuleDef<M>\n\t| (DirectiveRefBaseConfig & { module: ModuleDef<M> });\n\n/** Without status (no config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n\toptions: UseDirectiveRefOptions<M>,\n): SingleModuleSystem<M>;\n\n/** Without status (with config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n\toptions: UseDirectiveRefOptions<M>,\n\tconfig: DirectiveRefBaseConfig,\n): SingleModuleSystem<M>;\n\n/** With status: returns { system, statusPlugin } */\nexport function useDirectiveRef<M extends ModuleSchema>(\n\toptions: UseDirectiveRefOptions<M>,\n\tconfig: { status: true } & DirectiveRefBaseConfig,\n): { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin };\n\n/** Implementation */\nexport function useDirectiveRef<M extends ModuleSchema>(\n\toptions: UseDirectiveRefOptions<M>,\n\tconfig?: { status?: boolean } & DirectiveRefBaseConfig,\n): SingleModuleSystem<M> | { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin } {\n\tconst systemRef = useRef<SingleModuleSystem<M> | null>(null);\n\tconst statusPluginRef = useRef<StatusPlugin | null>(null);\n\tconst wantStatus = config?.status === true;\n\n\tif (!systemRef.current) {\n\t\tconst isModule = \"id\" in options && \"schema\" in options;\n\t\tconst mod = isModule ? (options as ModuleDef<M>) : (options as { module: ModuleDef<M> }).module;\n\t\tconst baseOpts = isModule ? {} : (options as DirectiveRefBaseConfig);\n\t\t// Merge config-level options over options-level (config takes precedence)\n\t\tconst plugins = config?.plugins ?? baseOpts.plugins ?? [];\n\t\tconst debug = config?.debug ?? baseOpts.debug;\n\t\tconst errorBoundary = config?.errorBoundary ?? baseOpts.errorBoundary;\n\t\tconst tickMs = config?.tickMs ?? baseOpts.tickMs;\n\t\tconst zeroConfig = config?.zeroConfig ?? baseOpts.zeroConfig;\n\t\tconst initialFacts = config?.initialFacts ?? baseOpts.initialFacts;\n\n\t\tlet allPlugins = [...plugins];\n\n\t\tif (wantStatus) {\n\t\t\tstatusPluginRef.current = createRequirementStatusPlugin();\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n\t\t\tallPlugins = [...allPlugins, statusPluginRef.current.plugin as Plugin<any>];\n\t\t}\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\t\tsystemRef.current = createSystem({\n\t\t\tmodule: mod,\n\t\t\tplugins: allPlugins.length > 0 ? allPlugins : undefined,\n\t\t\tdebug,\n\t\t\terrorBoundary,\n\t\t\ttickMs,\n\t\t\tzeroConfig,\n\t\t\tinitialFacts,\n\t\t} as any) as unknown as SingleModuleSystem<M>;\n\n\t}\n\n\tuseEffect(() => {\n\t\tconst sys = systemRef.current;\n\t\tsys?.start();\n\t\treturn () => {\n\t\t\tsys?.destroy();\n\t\t\tsystemRef.current = null;\n\t\t\tstatusPluginRef.current = null;\n\t\t};\n\t}, []);\n\n\tif (wantStatus) {\n\t\treturn {\n\t\t\tsystem: systemRef.current!,\n\t\t\tstatusPlugin: statusPluginRef.current!,\n\t\t};\n\t}\n\n\treturn systemRef.current!;\n}\n\n// ============================================================================\n// useDirective — scoped system with selected values in containers\n// ============================================================================\n\n/** Options for useDirective hook */\nexport interface UseDirectiveOptions<\n\tS extends ModuleSchema,\n\tFK extends keyof InferFacts<S> & string = never,\n\tDK extends keyof InferDerivations<S> & string = never,\n> extends DirectiveRefBaseConfig {\n\t/** Fact keys to subscribe to */\n\tfacts?: FK[];\n\t/** Derivation keys to subscribe to */\n\tderived?: DK[];\n\t/** Enable status plugin */\n\tstatus?: boolean;\n}\n\n/** Return type for useDirective hook (without status) */\nexport type UseDirectiveReturn<\n\tS extends ModuleSchema,\n\tFK extends keyof InferFacts<S> & string,\n\tDK extends keyof InferDerivations<S> & string,\n> = {\n\tsystem: SingleModuleSystem<S>;\n\tdispatch: (event: InferEvents<S>) => void;\n\tevents: SingleModuleSystem<S>[\"events\"];\n\tfacts: Pick<InferFacts<S>, FK>;\n\tderived: Pick<InferDerivations<S>, DK>;\n};\n\n/** Return type for useDirective hook (with status) */\nexport type UseDirectiveReturnWithStatus<\n\tS extends ModuleSchema,\n\tFK extends keyof InferFacts<S> & string,\n\tDK extends keyof InferDerivations<S> & string,\n> = UseDirectiveReturn<S, FK, DK> & {\n\tstatusPlugin: 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\tS extends ModuleSchema,\n\tFK extends keyof InferFacts<S> & string = never,\n\tDK extends keyof InferDerivations<S> & string = never,\n>(\n\tmoduleOrOptions: UseDirectiveRefOptions<S>,\n\tselections: UseDirectiveOptions<S, FK, DK> = {} as UseDirectiveOptions<S, FK, DK>,\n): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK> {\n\tconst { facts: factKeysOpt, derived: derivedKeysOpt, status, ...configRest } = selections;\n\tconst factKeys = (factKeysOpt ?? []) as FK[];\n\tconst derivedKeys = (derivedKeysOpt ?? []) as DK[];\n\n\t// When no keys are specified, subscribe to everything\n\tconst subscribeAll = factKeys.length === 0 && derivedKeys.length === 0;\n\n\t// Create system via useDirectiveRef (handles lifecycle)\n\t// biome-ignore lint/suspicious/noExplicitAny: Conditional overload dispatch\n\tconst refResult: any = status\n\t\t? useDirectiveRef(moduleOrOptions, { status: true as const, ...configRest })\n\t\t: useDirectiveRef(moduleOrOptions, configRest);\n\n\tconst system: SingleModuleSystem<S> = status\n\t\t? refResult.system\n\t\t: refResult;\n\n\tconst statusPlugin = status\n\t\t? (refResult as { system: SingleModuleSystem<S>; statusPlugin: StatusPlugin }).statusPlugin\n\t\t: undefined;\n\n\t// For subscribe-all mode, get all derivation keys\n\tconst allDerivationKeys = useMemo(\n\t\t() => (subscribeAll ? Object.keys(system.derive) : []),\n\t\t[system, subscribeAll],\n\t);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\tconst unsubs: Array<() => void> = [];\n\t\t\tif (subscribeAll) {\n\t\t\t\t// Subscribe to ALL facts and ALL derivations\n\t\t\t\tunsubs.push(system.facts.$store.subscribeAll(onStoreChange));\n\t\t\t\tif (allDerivationKeys.length > 0) {\n\t\t\t\t\tunsubs.push(system.subscribe(allDerivationKeys, onStoreChange));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (factKeys.length > 0) {\n\t\t\t\t\tunsubs.push(system.facts.$store.subscribe(factKeys, onStoreChange));\n\t\t\t\t}\n\t\t\t\tif (derivedKeys.length > 0) {\n\t\t\t\t\tunsubs.push(system.subscribe(derivedKeys, onStoreChange));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn () => {\n\t\t\t\tfor (const unsub of unsubs) unsub();\n\t\t\t};\n\t\t},\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys],\n\t);\n\n\tconst cachedFacts = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\tconst cachedDerived = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\tconst cachedWrapper = useRef<{ facts: Record<string, unknown>; derived: Record<string, unknown> } | null>(null);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tlet factsResult: Record<string, unknown>;\n\t\tlet derivedResult: Record<string, unknown>;\n\t\tlet effectiveFactKeys: readonly string[];\n\t\tlet effectiveDerivedKeys: readonly string[];\n\n\t\tif (subscribeAll) {\n\t\t\t// Read ALL facts and ALL derivations\n\t\t\tfactsResult = system.facts.$store.toObject();\n\t\t\teffectiveFactKeys = Object.keys(factsResult);\n\t\t\tderivedResult = {};\n\t\t\tfor (const key of allDerivationKeys) {\n\t\t\t\tderivedResult[key] = system.read(key);\n\t\t\t}\n\t\t\teffectiveDerivedKeys = allDerivationKeys;\n\t\t} else {\n\t\t\t// Read selected keys only\n\t\t\tfactsResult = {};\n\t\t\tfor (const key of factKeys) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n\t\t\t\tfactsResult[key] = (system.facts as any)[key];\n\t\t\t}\n\t\t\teffectiveFactKeys = factKeys;\n\t\t\tderivedResult = {};\n\t\t\tfor (const key of derivedKeys) {\n\t\t\t\tderivedResult[key] = system.read(key);\n\t\t\t}\n\t\t\teffectiveDerivedKeys = derivedKeys;\n\t\t}\n\n\t\t// Check facts stability\n\t\tlet factsSame = cachedFacts.current !== UNINITIALIZED;\n\t\tif (factsSame) {\n\t\t\tconst prev = cachedFacts.current as Record<string, unknown>;\n\t\t\tconst prevKeys = Object.keys(prev);\n\t\t\tif (prevKeys.length !== effectiveFactKeys.length) {\n\t\t\t\tfactsSame = false;\n\t\t\t} else {\n\t\t\t\tfor (const key of effectiveFactKeys) {\n\t\t\t\t\tif (!Object.is(prev[key], factsResult[key])) {\n\t\t\t\t\t\tfactsSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check derived stability\n\t\tlet derivedSame = cachedDerived.current !== UNINITIALIZED;\n\t\tif (derivedSame) {\n\t\t\tconst prev = cachedDerived.current as Record<string, unknown>;\n\t\t\tconst prevKeys = Object.keys(prev);\n\t\t\tif (prevKeys.length !== effectiveDerivedKeys.length) {\n\t\t\t\tderivedSame = false;\n\t\t\t} else {\n\t\t\t\tfor (const key of effectiveDerivedKeys) {\n\t\t\t\t\tif (!Object.is(prev[key], derivedResult[key])) {\n\t\t\t\t\t\tderivedSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst stableFacts = factsSame ? cachedFacts.current as Record<string, unknown> : factsResult;\n\t\tconst stableDerived = derivedSame ? cachedDerived.current as Record<string, unknown> : derivedResult;\n\n\t\tif (!factsSame) cachedFacts.current = factsResult;\n\t\tif (!derivedSame) cachedDerived.current = derivedResult;\n\n\t\t// Return same wrapper reference when both containers are unchanged\n\t\tif (factsSame && derivedSame && cachedWrapper.current) {\n\t\t\treturn cachedWrapper.current;\n\t\t}\n\n\t\tcachedWrapper.current = { facts: stableFacts, derived: stableDerived };\n\t\treturn cachedWrapper.current;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys]);\n\n\tconst values = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n\tconst dispatch = useCallback(\n\t\t(event: InferEvents<S>) => system.dispatch(event),\n\t\t[system],\n\t);\n\n\tconst events = useEvents(system);\n\n\tconst base = {\n\t\tsystem,\n\t\tdispatch,\n\t\tevents,\n\t\tfacts: values.facts as Pick<InferFacts<S>, FK>,\n\t\tderived: values.derived as Pick<InferDerivations<S>, DK>,\n\t};\n\n\tif (status && statusPlugin) {\n\t\treturn { ...base, statusPlugin } as UseDirectiveReturnWithStatus<S, FK, DK>;\n\t}\n\n\treturn base as UseDirectiveReturn<S, FK, DK>;\n}\n\n// ============================================================================\n// DevTools Component\n// ============================================================================\n\n/** Props for DirectiveDevTools component */\nexport interface DirectiveDevToolsProps {\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>;\n\t/** Position of the panel */\n\tposition?: \"bottom-right\" | \"bottom-left\" | \"top-right\" | \"top-left\";\n\t/** Whether the panel starts open */\n\tdefaultOpen?: boolean;\n}\n\n/**\n * Dev-only floating panel that shows system state.\n * Tree-shaken in production builds via `process.env.NODE_ENV` check.\n */\nexport function DirectiveDevTools({\n\tsystem,\n\tposition = \"bottom-right\",\n\tdefaultOpen = false,\n}: DirectiveDevToolsProps): ReturnType<typeof import(\"react\").createElement> | null {\n\tconst [isOpen, setIsOpen] = useState(defaultOpen);\n\tconst closeButtonRef = useRef<HTMLButtonElement | null>(null);\n\tconst { isSettled, unmet, inflight } = useInspect(system);\n\n\t// Auto-focus close button when panel opens\n\tuseEffect(() => {\n\t\tif (isOpen && closeButtonRef.current) {\n\t\t\tcloseButtonRef.current.focus();\n\t\t}\n\t}, [isOpen]);\n\n\t// Facts subscription for devtools\n\tconst factsSubscribe = useCallback(\n\t\t(onStoreChange: () => void) => system.facts.$store.subscribeAll(onStoreChange),\n\t\t[system],\n\t);\n\tconst factsRef = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\tconst getFactsSnapshot = useCallback(() => {\n\t\tconst current = system.facts.$store.toObject();\n\t\tif (factsRef.current !== UNINITIALIZED) {\n\t\t\tconst prevKeys = Object.keys(factsRef.current as Record<string, unknown>);\n\t\t\tconst currKeys = Object.keys(current);\n\t\t\tif (prevKeys.length === currKeys.length) {\n\t\t\t\tlet same = true;\n\t\t\t\tfor (const key of currKeys) {\n\t\t\t\t\tif (!Object.is((factsRef.current as Record<string, unknown>)[key], current[key])) {\n\t\t\t\t\t\tsame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (same) return factsRef.current as Record<string, unknown>;\n\t\t\t}\n\t\t}\n\t\tfactsRef.current = current;\n\t\treturn current;\n\t}, [system]);\n\tconst facts = useSyncExternalStore(factsSubscribe, getFactsSnapshot, getFactsSnapshot);\n\n\tif (process.env.NODE_ENV === \"production\") return null;\n\n\tconst positionStyles: Record<string, string | number> = {\n\t\tposition: \"fixed\",\n\t\tzIndex: 99999,\n\t\t...(position.includes(\"bottom\") ? { bottom: 12 } : { top: 12 }),\n\t\t...(position.includes(\"right\") ? { right: 12 } : { left: 12 }),\n\t};\n\n\tif (!isOpen) {\n\t\treturn (\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonClick={() => setIsOpen(true)}\n\t\t\t\taria-label={`Open Directive DevTools${isSettled ? \"\" : \" (system working)\"}`}\n\t\t\t\taria-expanded={false}\n\t\t\t\tstyle={{\n\t\t\t\t\t...positionStyles,\n\t\t\t\t\tbackground: \"#1a1a2e\",\n\t\t\t\t\tcolor: \"#e0e0e0\",\n\t\t\t\t\tborder: \"1px solid #333\",\n\t\t\t\t\tborderRadius: 6,\n\t\t\t\t\tpadding: \"6px 12px\",\n\t\t\t\t\tcursor: \"pointer\",\n\t\t\t\t\tfontFamily: \"monospace\",\n\t\t\t\t\tfontSize: 12,\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t{isSettled ? \"Directive\" : \"Directive...\"}\n\t\t\t</button>\n\t\t);\n\t}\n\n\tconst derivationKeys = Object.keys(system.derive);\n\tconst derivations: Record<string, unknown> = {};\n\tfor (const key of derivationKeys) {\n\t\ttry {\n\t\t\tderivations[key] = system.read(key);\n\t\t} catch {\n\t\t\tderivations[key] = \"<error>\";\n\t\t}\n\t}\n\n\treturn (\n\t\t<div\n\t\t\trole=\"region\"\n\t\t\taria-label=\"Directive DevTools\"\n\t\t\ttabIndex={-1}\n\t\t\tonKeyDown={(e) => {\n\t\t\t\tif (e.key === \"Escape\") setIsOpen(false);\n\t\t\t}}\n\t\t\tstyle={{\n\t\t\t\t...positionStyles,\n\t\t\t\tbackground: \"#1a1a2e\",\n\t\t\t\tcolor: \"#e0e0e0\",\n\t\t\t\tborder: \"1px solid #333\",\n\t\t\t\tborderRadius: 8,\n\t\t\t\tpadding: 12,\n\t\t\t\tfontFamily: \"monospace\",\n\t\t\t\tfontSize: 11,\n\t\t\t\tmaxWidth: 380,\n\t\t\t\tmaxHeight: 500,\n\t\t\t\toverflow: \"auto\",\n\t\t\t\tboxShadow: \"0 4px 20px rgba(0,0,0,0.5)\",\n\t\t\t}}\n\t\t>\n\t\t\t<div style={{ display: \"flex\", justifyContent: \"space-between\", marginBottom: 8 }}>\n\t\t\t\t<strong style={{ color: \"#7c8aff\" }}>Directive DevTools</strong>\n\t\t\t\t<button\n\t\t\t\t\tref={closeButtonRef}\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonClick={() => setIsOpen(false)}\n\t\t\t\t\taria-label=\"Close DevTools\"\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tbackground: \"none\",\n\t\t\t\t\t\tborder: \"none\",\n\t\t\t\t\t\tcolor: \"#888\",\n\t\t\t\t\t\tcursor: \"pointer\",\n\t\t\t\t\t\tfontSize: 14,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t{\"\\u00D7\"}\n\t\t\t\t</button>\n\t\t\t</div>\n\n\t\t\t<div style={{ marginBottom: 6 }} aria-live=\"polite\">\n\t\t\t\t<span style={{ color: isSettled ? \"#4ade80\" : \"#fbbf24\" }}>\n\t\t\t\t\t{isSettled ? \"Settled\" : \"Working...\"}\n\t\t\t\t</span>\n\t\t\t</div>\n\n\t\t\t<details open>\n\t\t\t\t<summary style={{ cursor: \"pointer\", color: \"#7c8aff\", marginBottom: 4 }}>\n\t\t\t\t\tFacts ({Object.keys(facts).length})\n\t\t\t\t</summary>\n\t\t\t\t<table style={{ width: \"100%\", borderCollapse: \"collapse\", fontSize: 11 }}>\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th style={{ textAlign: \"left\", padding: \"2px 4px\", color: \"#7c8aff\" }}>Key</th>\n\t\t\t\t\t\t\t<th style={{ textAlign: \"left\", padding: \"2px 4px\", color: \"#7c8aff\" }}>Value</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t\t{Object.entries(facts).map(([key, value]) => {\n\t\t\t\t\t\t\tlet display: string;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdisplay = typeof value === \"object\" ? JSON.stringify(value) : String(value);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tdisplay = \"<error>\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<tr key={key} style={{ borderBottom: \"1px solid #2a2a4a\" }}>\n\t\t\t\t\t\t\t\t\t<td style={{ padding: \"2px 4px\", color: \"#a0a0c0\" }}>{key}</td>\n\t\t\t\t\t\t\t\t\t<td style={{ padding: \"2px 4px\" }}>{display}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})}\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t</details>\n\n\t\t\t{derivationKeys.length > 0 && (\n\t\t\t\t<details>\n\t\t\t\t\t<summary style={{ cursor: \"pointer\", color: \"#7c8aff\", marginBottom: 4 }}>\n\t\t\t\t\t\tDerivations ({derivationKeys.length})\n\t\t\t\t\t</summary>\n\t\t\t\t\t<table style={{ width: \"100%\", borderCollapse: \"collapse\", fontSize: 11 }}>\n\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th style={{ textAlign: \"left\", padding: \"2px 4px\", color: \"#7c8aff\" }}>Key</th>\n\t\t\t\t\t\t\t\t<th style={{ textAlign: \"left\", padding: \"2px 4px\", color: \"#7c8aff\" }}>Value</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t<tbody>\n\t\t\t\t\t\t\t{Object.entries(derivations).map(([key, value]) => (\n\t\t\t\t\t\t\t\t<tr key={key} style={{ borderBottom: \"1px solid #2a2a4a\" }}>\n\t\t\t\t\t\t\t\t\t<td style={{ padding: \"2px 4px\", color: \"#a0a0c0\" }}>{key}</td>\n\t\t\t\t\t\t\t\t\t<td style={{ padding: \"2px 4px\" }}>\n\t\t\t\t\t\t\t\t\t\t{typeof value === \"object\" ? JSON.stringify(value) : String(value)}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</tbody>\n\t\t\t\t\t</table>\n\t\t\t\t</details>\n\t\t\t)}\n\n\t\t\t{inflight.length > 0 && (\n\t\t\t\t<details open>\n\t\t\t\t\t<summary style={{ cursor: \"pointer\", color: \"#fbbf24\", marginBottom: 4 }}>\n\t\t\t\t\t\tInflight ({inflight.length})\n\t\t\t\t\t</summary>\n\t\t\t\t\t<ul style={{ margin: 0, paddingLeft: 16 }}>\n\t\t\t\t\t\t{inflight.map((r) => (\n\t\t\t\t\t\t\t<li key={r.id} style={{ fontSize: 11 }}>\n\t\t\t\t\t\t\t\t{r.resolverId} ({r.id})\n\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</ul>\n\t\t\t\t</details>\n\t\t\t)}\n\n\t\t\t{unmet.length > 0 && (\n\t\t\t\t<details open>\n\t\t\t\t\t<summary style={{ cursor: \"pointer\", color: \"#f87171\", marginBottom: 4 }}>\n\t\t\t\t\t\tUnmet ({unmet.length})\n\t\t\t\t\t</summary>\n\t\t\t\t\t<ul style={{ margin: 0, paddingLeft: 16 }}>\n\t\t\t\t\t\t{unmet.map((r) => (\n\t\t\t\t\t\t\t<li key={r.id} style={{ fontSize: 11 }}>\n\t\t\t\t\t\t\t\t{r.requirement.type} from {r.fromConstraint}\n\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</ul>\n\t\t\t\t</details>\n\t\t\t)}\n\t\t</div>\n\t);\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\tsystem: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n\tassertSystem(\"useEvents\", system);\n\treturn 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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\trequirementId: string,\n): string | null {\n\tassertSystem(\"useExplain\", system);\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\tconst unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n\t\t\tconst unsubSettled = system.onSettledChange(onStoreChange);\n\t\t\treturn () => {\n\t\t\t\tunsubFacts();\n\t\t\t\tunsubSettled();\n\t\t\t};\n\t\t},\n\t\t[system],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\treturn system.explain(requirementId);\n\t}, [system, requirementId]);\n\n\treturn 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\tsystem: SingleModuleSystem<any>,\n): ConstraintInfo[];\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId: string,\n): ConstraintInfo | null;\n/** Implementation */\nexport function useConstraintStatus(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n\tassertSystem(\"useConstraintStatus\", system);\n\tconst inspectState = useInspect(system);\n\n\treturn useMemo(() => {\n\t\tconst inspection = system.inspect();\n\t\tif (!constraintId) return inspection.constraints;\n\t\treturn inspection.constraints.find((c) => c.id === constraintId) ?? null;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [system, constraintId, inspectState]);\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\n/** Result of useOptimisticUpdate */\nexport interface OptimisticUpdateResult {\n\t/** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */\n\tmutate: (updateFn: () => void) => void;\n\t/** Whether a resolver is currently processing the optimistic change */\n\tisPending: boolean;\n\t/** Error if the resolver failed */\n\terror: Error | null;\n\t/** Manually rollback to the pre-mutation snapshot */\n\trollback: () => 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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\tstatusPlugin?: StatusPlugin,\n\trequirementType?: string,\n): OptimisticUpdateResult {\n\tassertSystem(\"useOptimisticUpdate\", system);\n\tconst [isPending, setIsPending] = useState(false);\n\tconst [error, setError] = useState<Error | null>(null);\n\tconst snapshotRef = useRef<SystemSnapshot | null>(null);\n\n\tconst rollback = useCallback(() => {\n\t\tif (snapshotRef.current) {\n\t\t\tsystem.restore(snapshotRef.current);\n\t\t\tsnapshotRef.current = null;\n\t\t}\n\t\tsetIsPending(false);\n\t\tsetError(null);\n\t}, [system]);\n\n\tconst mutate = useCallback(\n\t\t(updateFn: () => void) => {\n\t\t\tsnapshotRef.current = system.getSnapshot();\n\t\t\tsetIsPending(true);\n\t\t\tsetError(null);\n\t\t\tsystem.batch(updateFn);\n\t\t},\n\t\t[system],\n\t);\n\n\t// Watch for resolver completion/failure\n\tuseEffect(() => {\n\t\tif (!statusPlugin || !requirementType || !isPending) return;\n\n\t\treturn statusPlugin.subscribe(() => {\n\t\t\tconst status = statusPlugin.getStatus(requirementType);\n\t\t\tif (!status.isLoading && !status.hasError) {\n\t\t\t\t// Resolved successfully — keep optimistic state\n\t\t\t\tsnapshotRef.current = null;\n\t\t\t\tsetIsPending(false);\n\t\t\t} else if (status.hasError) {\n\t\t\t\t// Failed — rollback\n\t\t\t\tsetError(status.lastError);\n\t\t\t\trollback();\n\t\t\t}\n\t\t});\n\t}, [statusPlugin, requirementType, isPending, rollback]);\n\n\treturn { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// DirectiveHydrator + useHydratedSystem — SSR/RSC hydration\n// ============================================================================\n\n/** Props for DirectiveHydrator component */\nexport interface HydratorProps {\n\tsnapshot: DistributableSnapshot;\n\tchildren: 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\treturn (\n\t\t<HydrationContext.Provider value={snapshot}>\n\t\t\t{children}\n\t\t</HydrationContext.Provider>\n\t);\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\tmoduleDef: ModuleDef<S>,\n\tconfig?: DirectiveRefBaseConfig,\n): SingleModuleSystem<S> {\n\tconst snapshot = useContext(HydrationContext);\n\n\t// Merge snapshot data as initial facts if available\n\tconst mergedConfig = useMemo(() => {\n\t\tif (!snapshot?.data) return config ?? {};\n\t\treturn {\n\t\t\t...(config ?? {}),\n\t\t\tinitialFacts: {\n\t\t\t\t...(config?.initialFacts ?? {}),\n\t\t\t\t...snapshot.data,\n\t\t\t},\n\t\t};\n\t}, [snapshot, config]);\n\n\treturn useDirectiveRef(moduleDef, mergedConfig) as SingleModuleSystem<S>;\n}\n\n"]}
@@ -0,0 +1,252 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import * as react from 'react';
3
+ import { ReactNode } from 'react';
4
+ import { SingleModuleSystem, DistributableSnapshot, createRequirementStatusPlugin, ModuleSchema, InferFacts, InferDerivations, Plugin, DebugConfig, ErrorBoundaryConfig, ModuleDef, InferEvents, RequirementTypeStatus, InferSelectorState, TimeTravelState } from '@directive-run/core';
5
+ export { RequirementTypeStatus } from '@directive-run/core';
6
+ import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
7
+ export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
8
+
9
+ /** Type for the requirement status plugin return value */
10
+ type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;
11
+ /** Single key overload */
12
+ declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;
13
+ /** Multi-key overload */
14
+ declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;
15
+ /** Single key overload */
16
+ declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];
17
+ /** Multi-key overload */
18
+ declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationIds: K[]): Pick<InferDerivations<S>, K>;
19
+ /**
20
+ * Auto-tracking selector over facts and derivations (Zustand-style).
21
+ * Uses `withTracking()` to detect which facts the selector accesses,
22
+ * then subscribes only to those keys. Falls back to subscribeAll
23
+ * if no keys are detected.
24
+ *
25
+ * Supports an optional default value as the 3rd parameter, used when
26
+ * the system is null/undefined or the selector returns undefined.
27
+ * When a default value is provided, the system parameter may be
28
+ * null | undefined — the hook returns the default and recomputes
29
+ * when the system becomes available.
30
+ */
31
+ declare function useSelector<S extends ModuleSchema, R>(system: SingleModuleSystem<S>, selector: (state: InferSelectorState<S>) => R, equalityFn?: (a: R, b: R) => boolean): R;
32
+ declare function useSelector<S extends ModuleSchema, R>(system: SingleModuleSystem<S>, selector: (state: InferSelectorState<S>) => R, defaultValue: R, equalityFn?: (a: R, b: R) => boolean): R;
33
+ declare function useSelector<S extends ModuleSchema, R>(system: SingleModuleSystem<S> | null | undefined, selector: (state: InferSelectorState<S>) => R, defaultValue: R, equalityFn?: (a: R, b: R) => boolean): R;
34
+ declare function useSelector<R>(system: SingleModuleSystem<any>, selector: (state: Record<string, any>) => R, equalityFn?: (a: R, b: R) => boolean): R;
35
+ declare function useSelector<R>(system: SingleModuleSystem<any> | null | undefined, selector: (state: Record<string, any>) => R, defaultValue: R, equalityFn?: (a: R, b: R) => boolean): R;
36
+ declare function useDispatch<S extends ModuleSchema>(system: SingleModuleSystem<S>): (event: InferEvents<S>) => void;
37
+ /** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */
38
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, key: K, callback: (newValue: InferDerivations<S>[K], prevValue: InferDerivations<S>[K] | undefined) => void): void;
39
+ /** Watch a fact key with auto-detection. */
40
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, key: K, callback: (newValue: InferFacts<S>[K] | undefined, prevValue: InferFacts<S>[K] | undefined) => void): void;
41
+ /**
42
+ * Watch a fact by explicit "fact" discriminator.
43
+ * @deprecated Use `useWatch(system, key, callback)` instead — facts are now auto-detected.
44
+ */
45
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, kind: "fact", factKey: K, callback: (newValue: InferFacts<S>[K] | undefined, prevValue: InferFacts<S>[K] | undefined) => void): void;
46
+ /** Watch a fact or derivation (generic fallback) */
47
+ declare function useWatch<T>(system: SingleModuleSystem<any>, key: string, callback: (newValue: T, prevValue: T | undefined) => void): void;
48
+ /** Options for useInspect */
49
+ interface UseInspectOptions {
50
+ /** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */
51
+ throttleMs?: number;
52
+ }
53
+ /**
54
+ * Hook to get consolidated system inspection data reactively.
55
+ *
56
+ * Merges isSettled, unmet/inflight requirements, and working state
57
+ * into a single subscription. Optionally throttle updates.
58
+ *
59
+ * @example
60
+ * ```tsx
61
+ * const { isSettled, isWorking, hasUnmet } = useInspect(system);
62
+ * const throttled = useInspect(system, { throttleMs: 200 });
63
+ * ```
64
+ */
65
+ declare function useInspect(system: SingleModuleSystem<any>, options?: UseInspectOptions): InspectState;
66
+ /**
67
+ * Reactive time-travel hook. Returns null when time-travel is disabled.
68
+ * Re-renders when snapshots are taken or navigation occurs.
69
+ *
70
+ * @example
71
+ * ```tsx
72
+ * const tt = useTimeTravel(system);
73
+ * if (tt) {
74
+ * return (
75
+ * <div>
76
+ * <button disabled={!tt.canUndo} onClick={tt.undo}>Undo</button>
77
+ * <button disabled={!tt.canRedo} onClick={tt.redo}>Redo</button>
78
+ * <span>{tt.currentIndex + 1} / {tt.totalSnapshots}</span>
79
+ * </div>
80
+ * );
81
+ * }
82
+ * ```
83
+ */
84
+ declare function useTimeTravel(system: SingleModuleSystem<any>): TimeTravelState | null;
85
+ /** Single type overload */
86
+ declare function useRequirementStatus(statusPlugin: StatusPlugin, type: string): RequirementTypeStatus;
87
+ /** Multi-type overload */
88
+ declare function useRequirementStatus(statusPlugin: StatusPlugin, types: string[]): Record<string, RequirementTypeStatus>;
89
+ /** Single type overload */
90
+ declare function useSuspenseRequirement(statusPlugin: StatusPlugin, type: string): RequirementTypeStatus;
91
+ /** Multi-type overload */
92
+ declare function useSuspenseRequirement(statusPlugin: StatusPlugin, types: string[]): Record<string, RequirementTypeStatus>;
93
+ /** Base options for creating a scoped system */
94
+ interface DirectiveRefBaseConfig {
95
+ plugins?: Plugin<any>[];
96
+ debug?: DebugConfig;
97
+ errorBoundary?: ErrorBoundaryConfig;
98
+ tickMs?: number;
99
+ zeroConfig?: boolean;
100
+ initialFacts?: Record<string, any>;
101
+ }
102
+ /** Options for useDirectiveRef: module directly, or config object */
103
+ type UseDirectiveRefOptions<M extends ModuleSchema> = ModuleDef<M> | (DirectiveRefBaseConfig & {
104
+ module: ModuleDef<M>;
105
+ });
106
+ /** Without status (no config): returns system directly */
107
+ declare function useDirectiveRef<M extends ModuleSchema>(options: UseDirectiveRefOptions<M>): SingleModuleSystem<M>;
108
+ /** Without status (with config): returns system directly */
109
+ declare function useDirectiveRef<M extends ModuleSchema>(options: UseDirectiveRefOptions<M>, config: DirectiveRefBaseConfig): SingleModuleSystem<M>;
110
+ /** With status: returns { system, statusPlugin } */
111
+ declare function useDirectiveRef<M extends ModuleSchema>(options: UseDirectiveRefOptions<M>, config: {
112
+ status: true;
113
+ } & DirectiveRefBaseConfig): {
114
+ system: SingleModuleSystem<M>;
115
+ statusPlugin: StatusPlugin;
116
+ };
117
+ /** Options for useDirective hook */
118
+ interface UseDirectiveOptions<S extends ModuleSchema, FK extends keyof InferFacts<S> & string = never, DK extends keyof InferDerivations<S> & string = never> extends DirectiveRefBaseConfig {
119
+ /** Fact keys to subscribe to */
120
+ facts?: FK[];
121
+ /** Derivation keys to subscribe to */
122
+ derived?: DK[];
123
+ /** Enable status plugin */
124
+ status?: boolean;
125
+ }
126
+ /** Return type for useDirective hook (without status) */
127
+ type UseDirectiveReturn<S extends ModuleSchema, FK extends keyof InferFacts<S> & string, DK extends keyof InferDerivations<S> & string> = {
128
+ system: SingleModuleSystem<S>;
129
+ dispatch: (event: InferEvents<S>) => void;
130
+ events: SingleModuleSystem<S>["events"];
131
+ facts: Pick<InferFacts<S>, FK>;
132
+ derived: Pick<InferDerivations<S>, DK>;
133
+ };
134
+ /** Return type for useDirective hook (with status) */
135
+ type UseDirectiveReturnWithStatus<S extends ModuleSchema, FK extends keyof InferFacts<S> & string, DK extends keyof InferDerivations<S> & string> = UseDirectiveReturn<S, FK, DK> & {
136
+ statusPlugin: StatusPlugin;
137
+ };
138
+ /**
139
+ * Convenience hook that creates a scoped system and reads selected facts/derivations
140
+ * into container objects. When no `facts` or `derived` keys are specified, subscribes
141
+ * to ALL facts and derivations (replacing the former `useModule` hook).
142
+ *
143
+ * @example
144
+ * ```tsx
145
+ * // Selective subscription
146
+ * const { dispatch, facts: { count }, derived: { doubled } } = useDirective(counterModule, {
147
+ * facts: ["count"],
148
+ * derived: ["doubled"],
149
+ * });
150
+ *
151
+ * // Subscribe to everything (no keys = all facts + all derivations)
152
+ * const { facts, derived, events, dispatch } = useDirective(counterModule);
153
+ * ```
154
+ */
155
+ declare function useDirective<S extends ModuleSchema, FK extends keyof InferFacts<S> & string = never, DK extends keyof InferDerivations<S> & string = never>(moduleOrOptions: UseDirectiveRefOptions<S>, selections?: UseDirectiveOptions<S, FK, DK>): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK>;
156
+ /** Props for DirectiveDevTools component */
157
+ interface DirectiveDevToolsProps {
158
+ system: SingleModuleSystem<any>;
159
+ /** Position of the panel */
160
+ position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
161
+ /** Whether the panel starts open */
162
+ defaultOpen?: boolean;
163
+ }
164
+ /**
165
+ * Dev-only floating panel that shows system state.
166
+ * Tree-shaken in production builds via `process.env.NODE_ENV` check.
167
+ */
168
+ declare function DirectiveDevTools({ system, position, defaultOpen, }: DirectiveDevToolsProps): ReturnType<typeof react.createElement> | null;
169
+ /**
170
+ * Returns the system's events dispatcher. Provides autocomplete for event names
171
+ * and avoids needing useCallback wrappers for event dispatch.
172
+ *
173
+ * @example
174
+ * ```tsx
175
+ * const events = useEvents(system);
176
+ * <button onClick={() => events.increment()}>+</button>
177
+ * ```
178
+ */
179
+ declare function useEvents<S extends ModuleSchema>(system: SingleModuleSystem<S>): SingleModuleSystem<S>["events"];
180
+ /**
181
+ * Reactively returns the explanation string for a requirement.
182
+ * Updates whenever system state changes.
183
+ *
184
+ * @example
185
+ * ```tsx
186
+ * const explanation = useExplain(system, "req-123");
187
+ * if (explanation) <pre>{explanation}</pre>;
188
+ * ```
189
+ */
190
+ declare function useExplain(system: SingleModuleSystem<any>, requirementId: string): string | null;
191
+ /** Get all constraints */
192
+ declare function useConstraintStatus(system: SingleModuleSystem<any>): ConstraintInfo[];
193
+ /** Get a single constraint by ID */
194
+ declare function useConstraintStatus(system: SingleModuleSystem<any>, constraintId: string): ConstraintInfo | null;
195
+ /** Result of useOptimisticUpdate */
196
+ interface OptimisticUpdateResult {
197
+ /** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */
198
+ mutate: (updateFn: () => void) => void;
199
+ /** Whether a resolver is currently processing the optimistic change */
200
+ isPending: boolean;
201
+ /** Error if the resolver failed */
202
+ error: Error | null;
203
+ /** Manually rollback to the pre-mutation snapshot */
204
+ rollback: () => void;
205
+ }
206
+ /**
207
+ * Optimistic update hook. Saves a snapshot before mutating, monitors
208
+ * a requirement type via statusPlugin, and rolls back on failure.
209
+ *
210
+ * @example
211
+ * ```tsx
212
+ * const { mutate, isPending, error, rollback } = useOptimisticUpdate(
213
+ * system, statusPlugin, "SAVE_ITEM"
214
+ * );
215
+ * mutate(() => { system.facts.items = [...system.facts.items, newItem]; });
216
+ * ```
217
+ */
218
+ declare function useOptimisticUpdate(system: SingleModuleSystem<any>, statusPlugin?: StatusPlugin, requirementType?: string): OptimisticUpdateResult;
219
+ /** Props for DirectiveHydrator component */
220
+ interface HydratorProps {
221
+ snapshot: DistributableSnapshot;
222
+ children: ReactNode;
223
+ }
224
+ /**
225
+ * SSR/RSC hydration component. Wraps children with a snapshot context
226
+ * that `useHydratedSystem` can consume on the client.
227
+ *
228
+ * @example
229
+ * ```tsx
230
+ * // Server component
231
+ * <DirectiveHydrator snapshot={serverSnapshot}>
232
+ * <ClientApp />
233
+ * </DirectiveHydrator>
234
+ * ```
235
+ */
236
+ declare function DirectiveHydrator({ snapshot, children }: HydratorProps): react_jsx_runtime.JSX.Element;
237
+ /**
238
+ * Client-side hook that creates a system hydrated from a server snapshot.
239
+ * Must be used inside a `<DirectiveHydrator>`.
240
+ *
241
+ * @example
242
+ * ```tsx
243
+ * function ClientApp() {
244
+ * const system = useHydratedSystem(counterModule);
245
+ * const count = useFact(system, "count");
246
+ * return <div>{count}</div>;
247
+ * }
248
+ * ```
249
+ */
250
+ declare function useHydratedSystem<S extends ModuleSchema>(moduleDef: ModuleDef<S>, config?: DirectiveRefBaseConfig): SingleModuleSystem<S>;
251
+
252
+ export { DirectiveDevTools, type DirectiveDevToolsProps, DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useHydratedSystem, useInspect, useOptimisticUpdate, useRequirementStatus, useSelector, useSuspenseRequirement, useTimeTravel, useWatch };
@@ -0,0 +1,252 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import * as react from 'react';
3
+ import { ReactNode } from 'react';
4
+ import { SingleModuleSystem, DistributableSnapshot, createRequirementStatusPlugin, ModuleSchema, InferFacts, InferDerivations, Plugin, DebugConfig, ErrorBoundaryConfig, ModuleDef, InferEvents, RequirementTypeStatus, InferSelectorState, TimeTravelState } from '@directive-run/core';
5
+ export { RequirementTypeStatus } from '@directive-run/core';
6
+ import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
7
+ export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
8
+
9
+ /** Type for the requirement status plugin return value */
10
+ type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;
11
+ /** Single key overload */
12
+ declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;
13
+ /** Multi-key overload */
14
+ declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;
15
+ /** Single key overload */
16
+ declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];
17
+ /** Multi-key overload */
18
+ declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationIds: K[]): Pick<InferDerivations<S>, K>;
19
+ /**
20
+ * Auto-tracking selector over facts and derivations (Zustand-style).
21
+ * Uses `withTracking()` to detect which facts the selector accesses,
22
+ * then subscribes only to those keys. Falls back to subscribeAll
23
+ * if no keys are detected.
24
+ *
25
+ * Supports an optional default value as the 3rd parameter, used when
26
+ * the system is null/undefined or the selector returns undefined.
27
+ * When a default value is provided, the system parameter may be
28
+ * null | undefined — the hook returns the default and recomputes
29
+ * when the system becomes available.
30
+ */
31
+ declare function useSelector<S extends ModuleSchema, R>(system: SingleModuleSystem<S>, selector: (state: InferSelectorState<S>) => R, equalityFn?: (a: R, b: R) => boolean): R;
32
+ declare function useSelector<S extends ModuleSchema, R>(system: SingleModuleSystem<S>, selector: (state: InferSelectorState<S>) => R, defaultValue: R, equalityFn?: (a: R, b: R) => boolean): R;
33
+ declare function useSelector<S extends ModuleSchema, R>(system: SingleModuleSystem<S> | null | undefined, selector: (state: InferSelectorState<S>) => R, defaultValue: R, equalityFn?: (a: R, b: R) => boolean): R;
34
+ declare function useSelector<R>(system: SingleModuleSystem<any>, selector: (state: Record<string, any>) => R, equalityFn?: (a: R, b: R) => boolean): R;
35
+ declare function useSelector<R>(system: SingleModuleSystem<any> | null | undefined, selector: (state: Record<string, any>) => R, defaultValue: R, equalityFn?: (a: R, b: R) => boolean): R;
36
+ declare function useDispatch<S extends ModuleSchema>(system: SingleModuleSystem<S>): (event: InferEvents<S>) => void;
37
+ /** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */
38
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, key: K, callback: (newValue: InferDerivations<S>[K], prevValue: InferDerivations<S>[K] | undefined) => void): void;
39
+ /** Watch a fact key with auto-detection. */
40
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, key: K, callback: (newValue: InferFacts<S>[K] | undefined, prevValue: InferFacts<S>[K] | undefined) => void): void;
41
+ /**
42
+ * Watch a fact by explicit "fact" discriminator.
43
+ * @deprecated Use `useWatch(system, key, callback)` instead — facts are now auto-detected.
44
+ */
45
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, kind: "fact", factKey: K, callback: (newValue: InferFacts<S>[K] | undefined, prevValue: InferFacts<S>[K] | undefined) => void): void;
46
+ /** Watch a fact or derivation (generic fallback) */
47
+ declare function useWatch<T>(system: SingleModuleSystem<any>, key: string, callback: (newValue: T, prevValue: T | undefined) => void): void;
48
+ /** Options for useInspect */
49
+ interface UseInspectOptions {
50
+ /** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */
51
+ throttleMs?: number;
52
+ }
53
+ /**
54
+ * Hook to get consolidated system inspection data reactively.
55
+ *
56
+ * Merges isSettled, unmet/inflight requirements, and working state
57
+ * into a single subscription. Optionally throttle updates.
58
+ *
59
+ * @example
60
+ * ```tsx
61
+ * const { isSettled, isWorking, hasUnmet } = useInspect(system);
62
+ * const throttled = useInspect(system, { throttleMs: 200 });
63
+ * ```
64
+ */
65
+ declare function useInspect(system: SingleModuleSystem<any>, options?: UseInspectOptions): InspectState;
66
+ /**
67
+ * Reactive time-travel hook. Returns null when time-travel is disabled.
68
+ * Re-renders when snapshots are taken or navigation occurs.
69
+ *
70
+ * @example
71
+ * ```tsx
72
+ * const tt = useTimeTravel(system);
73
+ * if (tt) {
74
+ * return (
75
+ * <div>
76
+ * <button disabled={!tt.canUndo} onClick={tt.undo}>Undo</button>
77
+ * <button disabled={!tt.canRedo} onClick={tt.redo}>Redo</button>
78
+ * <span>{tt.currentIndex + 1} / {tt.totalSnapshots}</span>
79
+ * </div>
80
+ * );
81
+ * }
82
+ * ```
83
+ */
84
+ declare function useTimeTravel(system: SingleModuleSystem<any>): TimeTravelState | null;
85
+ /** Single type overload */
86
+ declare function useRequirementStatus(statusPlugin: StatusPlugin, type: string): RequirementTypeStatus;
87
+ /** Multi-type overload */
88
+ declare function useRequirementStatus(statusPlugin: StatusPlugin, types: string[]): Record<string, RequirementTypeStatus>;
89
+ /** Single type overload */
90
+ declare function useSuspenseRequirement(statusPlugin: StatusPlugin, type: string): RequirementTypeStatus;
91
+ /** Multi-type overload */
92
+ declare function useSuspenseRequirement(statusPlugin: StatusPlugin, types: string[]): Record<string, RequirementTypeStatus>;
93
+ /** Base options for creating a scoped system */
94
+ interface DirectiveRefBaseConfig {
95
+ plugins?: Plugin<any>[];
96
+ debug?: DebugConfig;
97
+ errorBoundary?: ErrorBoundaryConfig;
98
+ tickMs?: number;
99
+ zeroConfig?: boolean;
100
+ initialFacts?: Record<string, any>;
101
+ }
102
+ /** Options for useDirectiveRef: module directly, or config object */
103
+ type UseDirectiveRefOptions<M extends ModuleSchema> = ModuleDef<M> | (DirectiveRefBaseConfig & {
104
+ module: ModuleDef<M>;
105
+ });
106
+ /** Without status (no config): returns system directly */
107
+ declare function useDirectiveRef<M extends ModuleSchema>(options: UseDirectiveRefOptions<M>): SingleModuleSystem<M>;
108
+ /** Without status (with config): returns system directly */
109
+ declare function useDirectiveRef<M extends ModuleSchema>(options: UseDirectiveRefOptions<M>, config: DirectiveRefBaseConfig): SingleModuleSystem<M>;
110
+ /** With status: returns { system, statusPlugin } */
111
+ declare function useDirectiveRef<M extends ModuleSchema>(options: UseDirectiveRefOptions<M>, config: {
112
+ status: true;
113
+ } & DirectiveRefBaseConfig): {
114
+ system: SingleModuleSystem<M>;
115
+ statusPlugin: StatusPlugin;
116
+ };
117
+ /** Options for useDirective hook */
118
+ interface UseDirectiveOptions<S extends ModuleSchema, FK extends keyof InferFacts<S> & string = never, DK extends keyof InferDerivations<S> & string = never> extends DirectiveRefBaseConfig {
119
+ /** Fact keys to subscribe to */
120
+ facts?: FK[];
121
+ /** Derivation keys to subscribe to */
122
+ derived?: DK[];
123
+ /** Enable status plugin */
124
+ status?: boolean;
125
+ }
126
+ /** Return type for useDirective hook (without status) */
127
+ type UseDirectiveReturn<S extends ModuleSchema, FK extends keyof InferFacts<S> & string, DK extends keyof InferDerivations<S> & string> = {
128
+ system: SingleModuleSystem<S>;
129
+ dispatch: (event: InferEvents<S>) => void;
130
+ events: SingleModuleSystem<S>["events"];
131
+ facts: Pick<InferFacts<S>, FK>;
132
+ derived: Pick<InferDerivations<S>, DK>;
133
+ };
134
+ /** Return type for useDirective hook (with status) */
135
+ type UseDirectiveReturnWithStatus<S extends ModuleSchema, FK extends keyof InferFacts<S> & string, DK extends keyof InferDerivations<S> & string> = UseDirectiveReturn<S, FK, DK> & {
136
+ statusPlugin: StatusPlugin;
137
+ };
138
+ /**
139
+ * Convenience hook that creates a scoped system and reads selected facts/derivations
140
+ * into container objects. When no `facts` or `derived` keys are specified, subscribes
141
+ * to ALL facts and derivations (replacing the former `useModule` hook).
142
+ *
143
+ * @example
144
+ * ```tsx
145
+ * // Selective subscription
146
+ * const { dispatch, facts: { count }, derived: { doubled } } = useDirective(counterModule, {
147
+ * facts: ["count"],
148
+ * derived: ["doubled"],
149
+ * });
150
+ *
151
+ * // Subscribe to everything (no keys = all facts + all derivations)
152
+ * const { facts, derived, events, dispatch } = useDirective(counterModule);
153
+ * ```
154
+ */
155
+ declare function useDirective<S extends ModuleSchema, FK extends keyof InferFacts<S> & string = never, DK extends keyof InferDerivations<S> & string = never>(moduleOrOptions: UseDirectiveRefOptions<S>, selections?: UseDirectiveOptions<S, FK, DK>): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK>;
156
+ /** Props for DirectiveDevTools component */
157
+ interface DirectiveDevToolsProps {
158
+ system: SingleModuleSystem<any>;
159
+ /** Position of the panel */
160
+ position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
161
+ /** Whether the panel starts open */
162
+ defaultOpen?: boolean;
163
+ }
164
+ /**
165
+ * Dev-only floating panel that shows system state.
166
+ * Tree-shaken in production builds via `process.env.NODE_ENV` check.
167
+ */
168
+ declare function DirectiveDevTools({ system, position, defaultOpen, }: DirectiveDevToolsProps): ReturnType<typeof react.createElement> | null;
169
+ /**
170
+ * Returns the system's events dispatcher. Provides autocomplete for event names
171
+ * and avoids needing useCallback wrappers for event dispatch.
172
+ *
173
+ * @example
174
+ * ```tsx
175
+ * const events = useEvents(system);
176
+ * <button onClick={() => events.increment()}>+</button>
177
+ * ```
178
+ */
179
+ declare function useEvents<S extends ModuleSchema>(system: SingleModuleSystem<S>): SingleModuleSystem<S>["events"];
180
+ /**
181
+ * Reactively returns the explanation string for a requirement.
182
+ * Updates whenever system state changes.
183
+ *
184
+ * @example
185
+ * ```tsx
186
+ * const explanation = useExplain(system, "req-123");
187
+ * if (explanation) <pre>{explanation}</pre>;
188
+ * ```
189
+ */
190
+ declare function useExplain(system: SingleModuleSystem<any>, requirementId: string): string | null;
191
+ /** Get all constraints */
192
+ declare function useConstraintStatus(system: SingleModuleSystem<any>): ConstraintInfo[];
193
+ /** Get a single constraint by ID */
194
+ declare function useConstraintStatus(system: SingleModuleSystem<any>, constraintId: string): ConstraintInfo | null;
195
+ /** Result of useOptimisticUpdate */
196
+ interface OptimisticUpdateResult {
197
+ /** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */
198
+ mutate: (updateFn: () => void) => void;
199
+ /** Whether a resolver is currently processing the optimistic change */
200
+ isPending: boolean;
201
+ /** Error if the resolver failed */
202
+ error: Error | null;
203
+ /** Manually rollback to the pre-mutation snapshot */
204
+ rollback: () => void;
205
+ }
206
+ /**
207
+ * Optimistic update hook. Saves a snapshot before mutating, monitors
208
+ * a requirement type via statusPlugin, and rolls back on failure.
209
+ *
210
+ * @example
211
+ * ```tsx
212
+ * const { mutate, isPending, error, rollback } = useOptimisticUpdate(
213
+ * system, statusPlugin, "SAVE_ITEM"
214
+ * );
215
+ * mutate(() => { system.facts.items = [...system.facts.items, newItem]; });
216
+ * ```
217
+ */
218
+ declare function useOptimisticUpdate(system: SingleModuleSystem<any>, statusPlugin?: StatusPlugin, requirementType?: string): OptimisticUpdateResult;
219
+ /** Props for DirectiveHydrator component */
220
+ interface HydratorProps {
221
+ snapshot: DistributableSnapshot;
222
+ children: ReactNode;
223
+ }
224
+ /**
225
+ * SSR/RSC hydration component. Wraps children with a snapshot context
226
+ * that `useHydratedSystem` can consume on the client.
227
+ *
228
+ * @example
229
+ * ```tsx
230
+ * // Server component
231
+ * <DirectiveHydrator snapshot={serverSnapshot}>
232
+ * <ClientApp />
233
+ * </DirectiveHydrator>
234
+ * ```
235
+ */
236
+ declare function DirectiveHydrator({ snapshot, children }: HydratorProps): react_jsx_runtime.JSX.Element;
237
+ /**
238
+ * Client-side hook that creates a system hydrated from a server snapshot.
239
+ * Must be used inside a `<DirectiveHydrator>`.
240
+ *
241
+ * @example
242
+ * ```tsx
243
+ * function ClientApp() {
244
+ * const system = useHydratedSystem(counterModule);
245
+ * const count = useFact(system, "count");
246
+ * return <div>{count}</div>;
247
+ * }
248
+ * ```
249
+ */
250
+ declare function useHydratedSystem<S extends ModuleSchema>(moduleDef: ModuleDef<S>, config?: DirectiveRefBaseConfig): SingleModuleSystem<S>;
251
+
252
+ export { DirectiveDevTools, type DirectiveDevToolsProps, DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useHydratedSystem, useInspect, useOptimisticUpdate, useRequirementStatus, useSelector, useSuspenseRequirement, useTimeTravel, useWatch };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import {createContext,useCallback,useSyncExternalStore,useRef,useMemo,useEffect,useState,useContext}from'react';import {createRequirementStatusPlugin,createSystem}from'@directive-run/core';import {assertSystem,runTrackedSelector,createThrottle,buildTimeTravelState,defaultEquality,depsChanged,computeInspectState}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {jsx,jsxs}from'react/jsx-runtime';var M=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)?oe(e,t):se(e,t)}function se(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(s=>e.facts.$store.subscribe([t],s),[e,t]),i=useCallback(()=>e.facts[t],[e,t]);return useSyncExternalStore(r,i,i)}function oe(e,t){let r=useRef(M),i=useCallback(o=>e.facts.$store.subscribe(t,o),[e,...t]),s=useCallback(()=>{let o={};for(let n of t)o[n]=e.facts[n];if(r.current!==M){let n=true;for(let u of t)if(!Object.is(r.current[u],o[u])){n=false;break}if(n)return r.current}return r.current=o,o},[e,...t]);return useSyncExternalStore(i,s,s)}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)?ue(e,t):ie(e,t)}function ie(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(s=>e.subscribe([t],s),[e,t]),i=useCallback(()=>e.read(t),[e,t]);return useSyncExternalStore(r,i,i)}function ue(e,t){let r=useRef(M),i=useCallback(o=>e.subscribe(t,o),[e,...t]),s=useCallback(()=>{let o={};for(let n of t)o[n]=e.read(n);if(r.current!==M){let n=true;for(let u of t)if(!Object.is(r.current[u],o[u])){n=false;break}if(n)return r.current}return r.current=o,o},[e,...t]);return useSyncExternalStore(i,s,s)}function Re(e,t,r,i){let s,o=false,n;typeof r=="function"&&i===void 0?n=r:(r!==void 0&&(s=r,o=true),n=i??defaultEquality),process.env.NODE_ENV!=="production"&&!e&&!o&&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 u=useRef(t),l=useRef(n),S=useRef(s);u.current=t,l.current=n,S.current=s;let c=useRef([]),g=useRef([]),y=useRef(M),D=useRef([]),h=useMemo(()=>e?new Set(Object.keys(e.derive)):new Set,[e]),R=useCallback(()=>e?runTrackedSelector(e,h,u.current):{value:S.current,factKeys:[],deriveKeys:[]},[e,h]),a=useCallback(b=>{if(!e)return ()=>{};let K=()=>{for(let p of D.current)p();D.current=[];let{factKeys:F,deriveKeys:T}=R();c.current=F,g.current=T,F.length>0?D.current.push(e.facts.$store.subscribe(F,()=>{let p=R();depsChanged(c.current,p.factKeys,g.current,p.deriveKeys)&&K(),b();})):T.length===0&&D.current.push(e.facts.$store.subscribeAll(b)),T.length>0&&D.current.push(e.subscribe(T,()=>{let p=R();depsChanged(c.current,p.factKeys,g.current,p.deriveKeys)&&K(),b();}));};return K(),()=>{for(let F of D.current)F();D.current=[];}},[e,R]),x=useCallback(()=>{let b;if(!e)b=S.current;else {let{value:K}=R();b=K===void 0&&o?S.current:K;}return y.current!==M&&l.current(y.current,b)?y.current:(y.current=b,b)},[R,e,o]);return useSyncExternalStore(a,x,x)}function xe(e){return assertSystem("useDispatch",e),useCallback(t=>{e.dispatch(t);},[e])}function De(e,t,r,i){assertSystem("useWatch",e);let s=t==="fact"&&typeof r=="string"&&typeof i=="function",o=s?r:t,n=s?i:r,u=useRef(n);u.current=n,useEffect(()=>e.watch(o,(l,S)=>{u.current(l,S);}),[e,o]);}function L(e,t){assertSystem("useInspect",e);let r=ae(e),i=t?.throttleMs,[s,o]=useState(r),n=useRef(null);return useEffect(()=>{if(!i||i<=0){n.current?.cleanup(),n.current=null;return}return n.current?.cleanup(),n.current=createThrottle((...u)=>{o(u[0]);},i),()=>{n.current?.cleanup(),n.current=null;}},[i]),useEffect(()=>{n.current&&n.current.throttled(r);},[r]),!i||i<=0?r:s}function ce(e){return computeInspectState(e)}function ae(e){let t=useRef(null),r=useRef([]),i=useRef([]),s=useRef(null),o=useCallback(u=>{let l=e.facts.$store.subscribeAll(u),S=e.onSettledChange(u);return ()=>{l(),S();}},[e]),n=useCallback(()=>{let u=ce(e),l=u.unmet.length===r.current.length&&u.unmet.every((g,y)=>g.id===r.current[y]),S=u.inflight.length===i.current.length&&u.inflight.every((g,y)=>g.id===i.current[y]),c=u.isSettled===s.current;return l&&S&&c&&t.current?t.current:(t.current=u,r.current=u.unmet.map(g=>g.id),i.current=u.inflight.map(g=>g.id),s.current=u.isSettled,u)},[e]);return useSyncExternalStore(o,n,n)}function ke(e){assertSystem("useTimeTravel",e);let t=useRef(null),r=useCallback(s=>e.onTimeTravelChange(s),[e]),i=useCallback(()=>{let s=buildTimeTravelState(e);return s?(t.current&&t.current.canUndo===s.canUndo&&t.current.canRedo===s.canRedo&&t.current.currentIndex===s.currentIndex&&t.current.totalSnapshots===s.totalSnapshots&&t.current.isPaused===s.isPaused||(t.current=s),t.current):null},[e]);return useSyncExternalStore(r,i,i)}function Me(e,t){return Array.isArray(t)?de(e,t):le(e,t)}function le(e,t){let r=useRef(M),i=useCallback(o=>e.subscribe(o),[e]),s=useCallback(()=>{let o=e.getStatus(t);if(r.current!==M){let n=r.current;if(n.pending===o.pending&&n.inflight===o.inflight&&n.failed===o.failed&&n.isLoading===o.isLoading&&n.hasError===o.hasError&&n.lastError===o.lastError)return r.current}return r.current=o,o},[e,t]);return useSyncExternalStore(i,s,s)}function de(e,t){let r=useRef(null),i=useRef(""),s=useCallback(n=>e.subscribe(n),[e]),o=useCallback(()=>{let n={},u=[];for(let S of t){let c=e.getStatus(S);n[S]=c,u.push(`${S}:${c.pending}:${c.inflight}:${c.failed}:${c.hasError}:${c.lastError?.message??""}`);}let l=u.join("|");return l!==i.current&&(i.current=l,r.current=n),r.current??n},[e,...t]);return useSyncExternalStore(s,o,o)}var $=new WeakMap;function _(e){let t=$.get(e);return t||(t=new Map,$.set(e,t)),t}function Ie(e,t){return Array.isArray(t)?Se(e,t):fe(e,t)}function fe(e,t){let r=e.getStatus(t);if(r.hasError&&r.lastError)throw r.lastError;if(r.isLoading){let i=_(e),s=i.get(t);throw s||(s=new Promise(o=>{let n=e.subscribe(()=>{e.getStatus(t).isLoading||(i.delete(t),n(),o());});}),i.set(t,s)),s}return r}function Se(e,t){let r={},i=false,s=null;for(let o of t){let n=e.getStatus(o);r[o]=n,n.hasError&&n.lastError&&!s&&(s=n.lastError),n.isLoading&&(i=true);}if(s)throw s;if(i){let o=_(e),n=t.slice().sort().join(","),u=o.get(n);throw u||(u=new Promise(l=>{let S=e.subscribe(()=>{t.every(g=>!e.getStatus(g).isLoading)&&(o.delete(n),S(),l());});}),o.set(n,u)),u}return r}function B(e,t){let r=useRef(null),i=useRef(null),s=t?.status===true;if(!r.current){let o="id"in e&&"schema"in e,n=o?e:e.module,u=o?{}:e,l=t?.plugins??u.plugins??[],S=t?.debug??u.debug,c=t?.errorBoundary??u.errorBoundary,g=t?.tickMs??u.tickMs,y=t?.zeroConfig??u.zeroConfig,D=t?.initialFacts??u.initialFacts,h=[...l];s&&(i.current=createRequirementStatusPlugin(),h=[...h,i.current.plugin]),r.current=createSystem({module:n,plugins:h.length>0?h:void 0,debug:S,errorBoundary:c,tickMs:g,zeroConfig:y,initialFacts:D});}return useEffect(()=>{let o=r.current;return o?.start(),()=>{o?.destroy(),r.current=null,i.current=null;}},[]),s?{system:r.current,statusPlugin:i.current}:r.current}function we(e,t={}){let{facts:r,derived:i,status:s,...o}=t,n=r??[],u=i??[],l=n.length===0&&u.length===0,S=s?B(e,{status:true,...o}):B(e,o),c=s?S.system:S,g=s?S.statusPlugin:void 0,y=useMemo(()=>l?Object.keys(c.derive):[],[c,l]),D=useCallback(p=>{let I=[];return l?(I.push(c.facts.$store.subscribeAll(p)),y.length>0&&I.push(c.subscribe(y,p))):(n.length>0&&I.push(c.facts.$store.subscribe(n,p)),u.length>0&&I.push(c.subscribe(u,p))),()=>{for(let P of I)P();}},[c,l,...n,...u,...y]),h=useRef(M),R=useRef(M),a=useRef(null),x=useCallback(()=>{let p,I,P,N;if(l){p=c.facts.$store.toObject(),P=Object.keys(p),I={};for(let k of y)I[k]=c.read(k);N=y;}else {p={};for(let k of n)p[k]=c.facts[k];P=n,I={};for(let k of u)I[k]=c.read(k);N=u;}let C=h.current!==M;if(C){let k=h.current;if(Object.keys(k).length!==P.length)C=false;else for(let V of P)if(!Object.is(k[V],p[V])){C=false;break}}let q=R.current!==M;if(q){let k=R.current;if(Object.keys(k).length!==N.length)q=false;else for(let V of N)if(!Object.is(k[V],I[V])){q=false;break}}let z=C?h.current:p,H=q?R.current:I;return C||(h.current=p),q||(R.current=I),C&&q&&a.current||(a.current={facts:z,derived:H}),a.current},[c,l,...n,...u,...y]),b=useSyncExternalStore(D,x,x),K=useCallback(p=>c.dispatch(p),[c]),F=pe(c),T={system:c,dispatch:K,events:F,facts:b.facts,derived:b.derived};return s&&g?{...T,statusPlugin:g}:T}function Ke({system:e,position:t="bottom-right",defaultOpen:r=false}){let[i,s]=useState(r),o=useRef(null),{isSettled:n,unmet:u,inflight:l}=L(e);useEffect(()=>{i&&o.current&&o.current.focus();},[i]);let S=useCallback(a=>e.facts.$store.subscribeAll(a),[e]),c=useRef(M),g=useCallback(()=>{let a=e.facts.$store.toObject();if(c.current!==M){let x=Object.keys(c.current),b=Object.keys(a);if(x.length===b.length){let K=true;for(let F of b)if(!Object.is(c.current[F],a[F])){K=false;break}if(K)return c.current}}return c.current=a,a},[e]),y=useSyncExternalStore(S,g,g);if(process.env.NODE_ENV==="production")return null;let D={position:"fixed",zIndex:99999,...t.includes("bottom")?{bottom:12}:{top:12},...t.includes("right")?{right:12}:{left:12}};if(!i)return jsx("button",{type:"button",onClick:()=>s(true),"aria-label":`Open Directive DevTools${n?"":" (system working)"}`,"aria-expanded":false,style:{...D,background:"#1a1a2e",color:"#e0e0e0",border:"1px solid #333",borderRadius:6,padding:"6px 12px",cursor:"pointer",fontFamily:"monospace",fontSize:12},children:n?"Directive":"Directive..."});let h=Object.keys(e.derive),R={};for(let a of h)try{R[a]=e.read(a);}catch{R[a]="<error>";}return jsxs("div",{role:"region","aria-label":"Directive DevTools",tabIndex:-1,onKeyDown:a=>{a.key==="Escape"&&s(false);},style:{...D,background:"#1a1a2e",color:"#e0e0e0",border:"1px solid #333",borderRadius:8,padding:12,fontFamily:"monospace",fontSize:11,maxWidth:380,maxHeight:500,overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.5)"},children:[jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:8},children:[jsx("strong",{style:{color:"#7c8aff"},children:"Directive DevTools"}),jsx("button",{ref:o,type:"button",onClick:()=>s(false),"aria-label":"Close DevTools",style:{background:"none",border:"none",color:"#888",cursor:"pointer",fontSize:14},children:"\xD7"})]}),jsx("div",{style:{marginBottom:6},"aria-live":"polite",children:jsx("span",{style:{color:n?"#4ade80":"#fbbf24"},children:n?"Settled":"Working..."})}),jsxs("details",{open:true,children:[jsxs("summary",{style:{cursor:"pointer",color:"#7c8aff",marginBottom:4},children:["Facts (",Object.keys(y).length,")"]}),jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[jsx("thead",{children:jsxs("tr",{children:[jsx("th",{style:{textAlign:"left",padding:"2px 4px",color:"#7c8aff"},children:"Key"}),jsx("th",{style:{textAlign:"left",padding:"2px 4px",color:"#7c8aff"},children:"Value"})]})}),jsx("tbody",{children:Object.entries(y).map(([a,x])=>{let b;try{b=typeof x=="object"?JSON.stringify(x):String(x);}catch{b="<error>";}return jsxs("tr",{style:{borderBottom:"1px solid #2a2a4a"},children:[jsx("td",{style:{padding:"2px 4px",color:"#a0a0c0"},children:a}),jsx("td",{style:{padding:"2px 4px"},children:b})]},a)})})]})]}),h.length>0&&jsxs("details",{children:[jsxs("summary",{style:{cursor:"pointer",color:"#7c8aff",marginBottom:4},children:["Derivations (",h.length,")"]}),jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[jsx("thead",{children:jsxs("tr",{children:[jsx("th",{style:{textAlign:"left",padding:"2px 4px",color:"#7c8aff"},children:"Key"}),jsx("th",{style:{textAlign:"left",padding:"2px 4px",color:"#7c8aff"},children:"Value"})]})}),jsx("tbody",{children:Object.entries(R).map(([a,x])=>jsxs("tr",{style:{borderBottom:"1px solid #2a2a4a"},children:[jsx("td",{style:{padding:"2px 4px",color:"#a0a0c0"},children:a}),jsx("td",{style:{padding:"2px 4px"},children:typeof x=="object"?JSON.stringify(x):String(x)})]},a))})]})]}),l.length>0&&jsxs("details",{open:true,children:[jsxs("summary",{style:{cursor:"pointer",color:"#fbbf24",marginBottom:4},children:["Inflight (",l.length,")"]}),jsx("ul",{style:{margin:0,paddingLeft:16},children:l.map(a=>jsxs("li",{style:{fontSize:11},children:[a.resolverId," (",a.id,")"]},a.id))})]}),u.length>0&&jsxs("details",{open:true,children:[jsxs("summary",{style:{cursor:"pointer",color:"#f87171",marginBottom:4},children:["Unmet (",u.length,")"]}),jsx("ul",{style:{margin:0,paddingLeft:16},children:u.map(a=>jsxs("li",{style:{fontSize:11},children:[a.requirement.type," from ",a.fromConstraint]},a.id))})]})]})}function pe(e){return assertSystem("useEvents",e),useMemo(()=>e.events,[e])}function Fe(e,t){assertSystem("useExplain",e);let r=useCallback(s=>{let o=e.facts.$store.subscribeAll(s),n=e.onSettledChange(s);return ()=>{o(),n();}},[e]),i=useCallback(()=>e.explain(t),[e,t]);return useSyncExternalStore(r,i,i)}function Ee(e,t){assertSystem("useConstraintStatus",e);let r=L(e);return useMemo(()=>{let i=e.inspect();return t?i.constraints.find(s=>s.id===t)??null:i.constraints},[e,t,r])}function Te(e,t,r){assertSystem("useOptimisticUpdate",e);let[i,s]=useState(false),[o,n]=useState(null),u=useRef(null),l=useCallback(()=>{u.current&&(e.restore(u.current),u.current=null),s(false),n(null);},[e]),S=useCallback(c=>{u.current=e.getSnapshot(),s(true),n(null),e.batch(c);},[e]);return useEffect(()=>{if(!(!t||!r||!i))return t.subscribe(()=>{let c=t.getStatus(r);!c.isLoading&&!c.hasError?(u.current=null,s(false)):c.hasError&&(n(c.lastError),l());})},[t,r,i,l]),{mutate:S,isPending:i,error:o,rollback:l}}var W=createContext(null);function Pe({snapshot:e,children:t}){return jsx(W.Provider,{value:e,children:t})}function Ce(e,t){let r=useContext(W),i=useMemo(()=>r?.data?{...t??{},initialFacts:{...t?.initialFacts??{},...r.data}}:t??{},[r,t]);return B(e,i)}export{Ke as DirectiveDevTools,Pe as DirectiveHydrator,Ee as useConstraintStatus,he as useDerived,we as useDirective,B as useDirectiveRef,xe as useDispatch,pe as useEvents,Fe as useExplain,me as useFact,Ce as useHydratedSystem,L as useInspect,Te as useOptimisticUpdate,Me as useRequirementStatus,Re as useSelector,Ie as useSuspenseRequirement,ke as useTimeTravel,De as useWatch};//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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","selector","defaultValueOrEqFn","maybeEqFn","defaultValue","hasDefault","equalityFn","defaultEquality","selectorRef","eqRef","defaultValueRef","trackedFactKeysRef","trackedDeriveKeysRef","unsubsRef","deriveKeys","useMemo","runWithTracking","runTrackedSelector","resubscribe","unsub","derivedKeys","updated","depsChanged","effectiveValue","newValue","useDispatch","event","useWatch","derivationIdOrKind","callbackOrFactKey","maybeCallback","isFact","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","wantStatus","isModule","mod","baseOpts","plugins","debug","errorBoundary","tickMs","zeroConfig","initialFacts","allPlugins","createRequirementStatusPlugin","createSystem","sys","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","DirectiveDevTools","position","defaultOpen","isOpen","setIsOpen","closeButtonRef","isSettled","unmet","inflight","factsSubscribe","factsRef","getFactsSnapshot","current","prevKeys","currKeys","facts","positionStyles","jsx","derivationKeys","derivations","jsxs","e","value","display","r","useExplain","requirementId","useConstraintStatus","constraintId","inspectState","inspection","c","useOptimisticUpdate","requirementType","isPending","setIsPending","error","setError","snapshotRef","rollback","mutate","updateFn","HydrationContext","createContext","DirectiveHydrator","snapshot","children","useHydratedSystem","moduleDef","useContext","mergedConfig"],"mappings":"scAwFA,IAAMA,CAAAA,CA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AS,CAAA,CACzBsG,GAAS,EAEX,CAAC,CACF,CAAA,CAAG,CAAC3G,EAAcqG,CAAAA,CAAiBC,CAAAA,CAAWK,CAAQ,CAAC,CAAA,CAEhD,CAAE,MAAA,CAAAC,CAAAA,CAAQ,SAAA,CAAAN,EAAW,KAAA,CAAAE,CAAAA,CAAO,SAAAG,CAAS,CAC7C,CAaA,IAAMG,CAAAA,CAAmBC,aAAAA,CAA4C,IAAI,CAAA,CAclE,SAASC,GAAkB,CAAE,QAAA,CAAAC,EAAU,QAAA,CAAAC,CAAS,EAAkB,CACxE,OACC7B,GAAAA,CAACyB,CAAAA,CAAiB,QAAA,CAAjB,CAA0B,MAAOG,CAAAA,CAChC,QAAA,CAAAC,EACF,CAEF,CAeO,SAASC,EAAAA,CACfC,CAAAA,CACA3F,CAAAA,CACwB,CACxB,IAAMwF,CAAAA,CAAWI,WAAWP,CAAgB,CAAA,CAGtCQ,EAAezK,OAAAA,CAAQ,IACvBoK,GAAU,IAAA,CACR,CACN,GAAIxF,CAAAA,EAAU,EAAC,CACf,aAAc,CACb,GAAIA,GAAQ,YAAA,EAAgB,GAC5B,GAAGwF,CAAAA,CAAS,IACb,CACD,CAAA,CAP4BxF,CAAAA,EAAU,EAAC,CAQrC,CAACwF,EAAUxF,CAAM,CAAC,EAErB,OAAOD,CAAAA,CAAgB4F,CAAAA,CAAWE,CAAY,CAC/C","file":"index.js","sourcesContent":["/**\n * React Adapter - Consolidated hooks for React integration\n *\n * 19 public exports: useFact, useDerived, useDispatch, useDirective,\n * useDirectiveRef, useSelector, useWatch, useInspect, useRequirementStatus,\n * useSuspenseRequirement, useEvents, useExplain, useConstraintStatus,\n * useOptimisticUpdate, DirectiveDevTools, 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 { ReactNode } from \"react\";\nimport {\n\tuseSyncExternalStore,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState,\n\tcreateContext,\n\tuseContext,\n} from \"react\";\nimport type {\n\tModuleSchema,\n\tModuleDef,\n\tPlugin,\n\tDebugConfig,\n\tErrorBoundaryConfig,\n\tInferFacts,\n\tInferDerivations,\n\tInferSelectorState,\n\tInferEvents,\n\tSingleModuleSystem,\n\tSystemSnapshot,\n\tDistributableSnapshot,\n\tTimeTravelState,\n} from \"@directive-run/core\";\nimport {\n\tcreateSystem,\n\tcreateRequirementStatusPlugin,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n\ttype InspectState,\n\ttype ConstraintInfo,\n\tcomputeInspectState,\n\tcreateThrottle,\n\tassertSystem,\n\tdefaultEquality,\n\tbuildTimeTravelState,\n\trunTrackedSelector,\n\tdepsChanged,\n\tshallowEqual,\n} from \"@directive-run/core/adapter-utils\";\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<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tfactKey: K,\n): InferFacts<S>[K] | undefined;\n\n/** Multi-key overload */\nexport function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tfactKeys: K[],\n): Pick<InferFacts<S>, K>;\n\n/** Implementation */\nexport function useFact(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tkeyOrKeys: string | string[],\n): unknown {\n\tassertSystem(\"useFact\", system);\n\tif (process.env.NODE_ENV !== \"production\" && typeof keyOrKeys === \"function\") {\n\t\tconsole.error(\n\t\t\t\"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n\t\t\t\t\"useFact() takes a string key or array of keys, not a selector function.\",\n\t\t);\n\t}\n\n\t// Multi-key path: useFact(system, [keys])\n\tif (Array.isArray(keyOrKeys)) {\n\t\treturn _useFacts(system, keyOrKeys);\n\t}\n\n\t// Single key path: useFact(system, key)\n\treturn _useSingleFact(system, keyOrKeys);\n}\n\nfunction _useSingleFact(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tfactKey: string,\n): unknown {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!(factKey in system.facts.$store.toObject())) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] useFact(\"${factKey}\") — fact not found in store. ` +\n\t\t\t\t\t`Check that \"${factKey}\" is defined in your module's schema.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn system.facts.$store.subscribe([factKey], onStoreChange);\n\t\t},\n\t\t[system, factKey],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n\t\treturn (system.facts as any)[factKey];\n\t}, [system, factKey]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useFacts(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tfactKeys: string[],\n): Record<string, unknown> {\n\tconst cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn system.facts.$store.subscribe(factKeys, onStoreChange);\n\t\t},\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[system, ...factKeys],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of factKeys) {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n\t\t\tresult[key] = (system.facts as any)[key];\n\t\t}\n\n\t\tif (cachedValue.current !== UNINITIALIZED) {\n\t\t\tlet same = true;\n\t\t\tfor (const key of factKeys) {\n\t\t\t\tif (!Object.is((cachedValue.current as Record<string, unknown>)[key], result[key])) {\n\t\t\t\t\tsame = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (same) return cachedValue.current;\n\t\t}\n\n\t\tcachedValue.current = result;\n\t\treturn result;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [system, ...factKeys]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tderivationId: K,\n): InferDerivations<S>[K];\n\n/** Multi-key overload */\nexport function useDerived<\n\tS extends ModuleSchema,\n\tK extends keyof InferDerivations<S> & string,\n>(\n\tsystem: SingleModuleSystem<S>,\n\tderivationIds: K[],\n): Pick<InferDerivations<S>, K>;\n\n/** Implementation */\nexport function useDerived(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tkeyOrKeys: string | string[],\n): unknown {\n\tassertSystem(\"useDerived\", system);\n\tif (process.env.NODE_ENV !== \"production\" && typeof keyOrKeys === \"function\") {\n\t\tconsole.error(\n\t\t\t\"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n\t\t\t\t\"useDerived() takes a string key or array of keys, not a selector function.\",\n\t\t);\n\t}\n\n\t// Multi-key path\n\tif (Array.isArray(keyOrKeys)) {\n\t\treturn _useDerivedMulti(system, keyOrKeys);\n\t}\n\n\t// Single key path\n\treturn _useSingleDerived(system, keyOrKeys);\n}\n\nfunction _useSingleDerived(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tderivationId: string,\n): unknown {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!(derivationId in system.derive)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] useDerived(\"${derivationId}\") — derivation not found. ` +\n\t\t\t\t\t`Check that \"${derivationId}\" is defined in your module's derive property.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn system.subscribe([derivationId], onStoreChange);\n\t\t},\n\t\t[system, derivationId],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\treturn system.read(derivationId);\n\t}, [system, derivationId]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useDerivedMulti(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tderivationIds: string[],\n): Record<string, unknown> {\n\tconst cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn system.subscribe(derivationIds, onStoreChange);\n\t\t},\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[system, ...derivationIds],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const id of derivationIds) {\n\t\t\tresult[id] = system.read(id);\n\t\t}\n\n\t\tif (cachedValue.current !== UNINITIALIZED) {\n\t\t\tlet same = true;\n\t\t\tfor (const id of derivationIds) {\n\t\t\t\tif (!Object.is((cachedValue.current as Record<string, unknown>)[id], result[id])) {\n\t\t\t\t\tsame = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (same) return cachedValue.current;\n\t\t}\n\n\t\tcachedValue.current = result;\n\t\treturn result;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [system, ...derivationIds]);\n\n\treturn 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\n// Existing: non-null system, no default (equalityFn as 3rd param)\nexport function useSelector<S extends ModuleSchema, R>(\n\tsystem: SingleModuleSystem<S>,\n\tselector: (state: InferSelectorState<S>) => R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// New: non-null system, with default value\nexport function useSelector<S extends ModuleSchema, R>(\n\tsystem: SingleModuleSystem<S>,\n\tselector: (state: InferSelectorState<S>) => R,\n\tdefaultValue: R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// New: nullable system, default REQUIRED\nexport function useSelector<S extends ModuleSchema, R>(\n\tsystem: SingleModuleSystem<S> | null | undefined,\n\tselector: (state: InferSelectorState<S>) => R,\n\tdefaultValue: R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Backward-compatible `any` fallback: equalityFn as 3rd param\nexport function useSelector<R>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any>,\n\t// biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n\tselector: (state: Record<string, any>) => R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Backward-compatible `any` fallback: default value + nullable system\nexport function useSelector<R>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any> | null | undefined,\n\t// biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n\tselector: (state: Record<string, any>) => R,\n\tdefaultValue: R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): R;\n\nexport function useSelector(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any> | null | undefined,\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tselector: (state: any) => unknown,\n\tdefaultValueOrEqFn?: unknown,\n\tmaybeEqFn?: (a: unknown, b: unknown) => boolean,\n): unknown {\n\t// Discriminate arg3: function → old API (equalityFn), otherwise → new API (defaultValue)\n\tlet defaultValue: unknown;\n\tlet hasDefault = false;\n\tlet equalityFn: (a: unknown, b: unknown) => boolean;\n\n\tif (typeof defaultValueOrEqFn === \"function\" && maybeEqFn === undefined) {\n\t\t// Old API: useSelector(system, selector, equalityFn)\n\t\tequalityFn = defaultValueOrEqFn as (a: unknown, b: unknown) => boolean;\n\t} else {\n\t\t// New API: useSelector(system, selector, defaultValue, equalityFn?)\n\t\t// Also covers: useSelector(system, selector) when defaultValueOrEqFn is undefined\n\t\tif (defaultValueOrEqFn !== undefined) {\n\t\t\tdefaultValue = defaultValueOrEqFn;\n\t\t\thasDefault = true;\n\t\t}\n\t\tequalityFn = maybeEqFn ?? defaultEquality;\n\t}\n\n\t// Dev-mode warning: null system without a default value\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!system && !hasDefault) {\n\t\t\tconsole.error(\n\t\t\t\t\"[Directive] useSelector() received a null/undefined system without a default value. \" +\n\t\t\t\t\t\"Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)\",\n\t\t\t);\n\t\t}\n\t}\n\n\t// Store selector/eq/default in refs to avoid resubscription churn\n\tconst selectorRef = useRef(selector);\n\tconst eqRef = useRef(equalityFn);\n\tconst defaultValueRef = useRef(defaultValue);\n\tselectorRef.current = selector;\n\teqRef.current = equalityFn;\n\tdefaultValueRef.current = defaultValue;\n\n\tconst trackedFactKeysRef = useRef<string[]>([]);\n\tconst trackedDeriveKeysRef = useRef<string[]>([]);\n\tconst cachedValue = useRef<unknown>(UNINITIALIZED);\n\tconst unsubsRef = useRef<Array<() => void>>([]);\n\n\t// Build a tracking-aware state proxy that exposes both facts and derivations\n\tconst deriveKeys = useMemo(\n\t\t() => (system ? new Set(Object.keys(system.derive)) : new Set<string>()),\n\t\t[system],\n\t);\n\n\tconst runWithTracking = useCallback(() => {\n\t\tif (!system) {\n\t\t\treturn { value: defaultValueRef.current, factKeys: [] as string[], deriveKeys: [] as string[] };\n\t\t}\n\n\t\treturn runTrackedSelector(system, deriveKeys, selectorRef.current);\n\t}, [system, deriveKeys]);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\tif (!system) {\n\t\t\t\t// No system — return noop unsubscribe\n\t\t\t\treturn () => {};\n\t\t\t}\n\n\t\t\tconst resubscribe = () => {\n\t\t\t\t// Cleanup previous subscriptions\n\t\t\t\tfor (const unsub of unsubsRef.current) unsub();\n\t\t\t\tunsubsRef.current = [];\n\n\t\t\t\t// Run selector with tracking to detect accessed keys\n\t\t\t\tconst { factKeys, deriveKeys: derivedKeys } = runWithTracking();\n\t\t\t\ttrackedFactKeysRef.current = factKeys;\n\t\t\t\ttrackedDeriveKeysRef.current = derivedKeys;\n\n\t\t\t\t// Subscribe to accessed fact keys\n\t\t\t\tif (factKeys.length > 0) {\n\t\t\t\t\tunsubsRef.current.push(\n\t\t\t\t\t\tsystem.facts.$store.subscribe(factKeys, () => {\n\t\t\t\t\t\t\t// Re-track on notification for dynamic deps\n\t\t\t\t\t\t\tconst updated = runWithTracking();\n\t\t\t\t\t\t\tif (depsChanged(trackedFactKeysRef.current, updated.factKeys, trackedDeriveKeysRef.current, updated.deriveKeys)) resubscribe();\n\t\t\t\t\t\t\tonStoreChange();\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t} else if (derivedKeys.length === 0) {\n\t\t\t\t\t// No deps at all — subscribe to everything\n\t\t\t\t\tunsubsRef.current.push(\n\t\t\t\t\t\tsystem.facts.$store.subscribeAll(onStoreChange),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Subscribe to accessed derivation keys\n\t\t\t\tif (derivedKeys.length > 0) {\n\t\t\t\t\tunsubsRef.current.push(\n\t\t\t\t\t\tsystem.subscribe(derivedKeys, () => {\n\t\t\t\t\t\t\t// Re-track on notification for dynamic deps\n\t\t\t\t\t\t\tconst updated = runWithTracking();\n\t\t\t\t\t\t\tif (depsChanged(trackedFactKeysRef.current, updated.factKeys, trackedDeriveKeysRef.current, updated.deriveKeys)) resubscribe();\n\t\t\t\t\t\t\tonStoreChange();\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tresubscribe();\n\n\t\t\treturn () => {\n\t\t\t\tfor (const unsub of unsubsRef.current) unsub();\n\t\t\t\tunsubsRef.current = [];\n\t\t\t};\n\t\t},\n\t\t[system, runWithTracking],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tlet effectiveValue: unknown;\n\n\t\tif (!system) {\n\t\t\teffectiveValue = defaultValueRef.current;\n\t\t} else {\n\t\t\tconst { value: newValue } = runWithTracking();\n\n\t\t\t// When selector returns undefined and we have a default, use it\n\t\t\teffectiveValue = newValue === undefined && hasDefault ? defaultValueRef.current : newValue;\n\t\t}\n\n\t\tif (\n\t\t\tcachedValue.current !== UNINITIALIZED &&\n\t\t\teqRef.current(cachedValue.current, effectiveValue)\n\t\t) {\n\t\t\treturn cachedValue.current;\n\t\t}\n\t\tcachedValue.current = effectiveValue;\n\n\t\treturn effectiveValue;\n\t}, [runWithTracking, system, hasDefault]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n\tsystem: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n\tassertSystem(\"useDispatch\", system);\n\treturn useCallback(\n\t\t(event: InferEvents<S>) => {\n\t\t\tsystem.dispatch(event);\n\t\t},\n\t\t[system],\n\t);\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\tS extends ModuleSchema,\n\tK extends keyof InferDerivations<S> & string,\n>(\n\tsystem: SingleModuleSystem<S>,\n\tkey: K,\n\tcallback: (\n\t\tnewValue: InferDerivations<S>[K],\n\t\tprevValue: InferDerivations<S>[K] | undefined,\n\t) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n\tS extends ModuleSchema,\n\tK extends keyof InferFacts<S> & string,\n>(\n\tsystem: SingleModuleSystem<S>,\n\tkey: K,\n\tcallback: (\n\t\tnewValue: InferFacts<S>[K] | undefined,\n\t\tprevValue: InferFacts<S>[K] | undefined,\n\t) => void,\n): void;\n\n/**\n * Watch a fact by explicit \"fact\" discriminator.\n * @deprecated Use `useWatch(system, key, callback)` instead — facts are now auto-detected.\n */\nexport function useWatch<\n\tS extends ModuleSchema,\n\tK extends keyof InferFacts<S> & string,\n>(\n\tsystem: SingleModuleSystem<S>,\n\tkind: \"fact\",\n\tfactKey: K,\n\tcallback: (\n\t\tnewValue: InferFacts<S>[K] | undefined,\n\t\tprevValue: InferFacts<S>[K] | undefined,\n\t) => void,\n): void;\n\n/** Watch a fact or derivation (generic fallback) */\nexport function useWatch<T>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any>,\n\tkey: string,\n\tcallback: (newValue: T, prevValue: T | undefined) => void,\n): void;\n\n/** Implementation */\nexport function useWatch(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tderivationIdOrKind: string,\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n\tcallbackOrFactKey: string | ((newValue: any, prevValue: any) => void),\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n\tmaybeCallback?: (newValue: any, prevValue: any) => void,\n): void {\n\tassertSystem(\"useWatch\", system);\n\t// Backward compat: useWatch(system, \"fact\", factKey, callback)\n\tconst isFact =\n\t\tderivationIdOrKind === \"fact\" &&\n\t\ttypeof callbackOrFactKey === \"string\" &&\n\t\ttypeof maybeCallback === \"function\";\n\tconst key = isFact ? (callbackOrFactKey as string) : derivationIdOrKind;\n\tconst callback = isFact\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n\t\t? (maybeCallback as (newValue: any, prevValue: any) => void)\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n\t\t: (callbackOrFactKey as (newValue: any, prevValue: any) => void);\n\n\tconst callbackRef = useRef(callback);\n\tcallbackRef.current = callback;\n\n\tuseEffect(() => {\n\t\treturn system.watch(key, (newValue, prevValue) => {\n\t\t\tcallbackRef.current(newValue, prevValue);\n\t\t});\n\t}, [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\t/** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */\n\tthrottleMs?: 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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\toptions?: UseInspectOptions,\n): InspectState {\n\tassertSystem(\"useInspect\", system);\n\t// Always call the sync version (useSyncExternalStore path) — no conditional hooks\n\tconst syncState = _useInspectSync(system);\n\n\tconst throttleMs = options?.throttleMs;\n\tconst [deferredState, setDeferredState] = useState(syncState);\n\tconst throttleRef = useRef<{ throttled: (...args: unknown[]) => void; cleanup: () => void } | null>(null);\n\n\t// Create/recreate throttle when throttleMs changes\n\tuseEffect(() => {\n\t\tif (!throttleMs || throttleMs <= 0) {\n\t\t\tthrottleRef.current?.cleanup();\n\t\t\tthrottleRef.current = null;\n\t\t\treturn;\n\t\t}\n\t\t// Clean up old throttle before creating new one\n\t\tthrottleRef.current?.cleanup();\n\t\tthrottleRef.current = createThrottle(\n\t\t\t(...args: unknown[]) => { setDeferredState(args[0] as InspectState); },\n\t\t\tthrottleMs,\n\t\t);\n\t\treturn () => {\n\t\t\tthrottleRef.current?.cleanup();\n\t\t\tthrottleRef.current = null;\n\t\t};\n\t}, [throttleMs]);\n\n\t// Feed sync state through throttle after each render\n\tuseEffect(() => {\n\t\tif (throttleRef.current) {\n\t\t\tthrottleRef.current.throttled(syncState);\n\t\t}\n\t}, [syncState]);\n\n\tif (!throttleMs || throttleMs <= 0) return syncState;\n\treturn deferredState;\n}\n\nfunction _buildInspectState(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n): InspectState {\n\treturn computeInspectState(system);\n}\n\nfunction _useInspectSync(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n): InspectState {\n\tconst cachedSnapshot = useRef<InspectState | null>(null);\n\tconst cachedUnmetIds = useRef<string[]>([]);\n\tconst cachedInflightIds = useRef<string[]>([]);\n\tconst cachedIsSettled = useRef<boolean | null>(null);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\tconst unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n\t\t\tconst unsubSettled = system.onSettledChange(onStoreChange);\n\t\t\treturn () => {\n\t\t\t\tunsubFacts();\n\t\t\t\tunsubSettled();\n\t\t\t};\n\t\t},\n\t\t[system],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst state = _buildInspectState(system);\n\n\t\tconst unmetSame =\n\t\t\tstate.unmet.length === cachedUnmetIds.current.length &&\n\t\t\tstate.unmet.every((u, i) => u.id === cachedUnmetIds.current[i]);\n\t\tconst inflightSame =\n\t\t\tstate.inflight.length === cachedInflightIds.current.length &&\n\t\t\tstate.inflight.every((f, i) => f.id === cachedInflightIds.current[i]);\n\t\tconst settledSame = state.isSettled === cachedIsSettled.current;\n\n\t\tif (unmetSame && inflightSame && settledSame && cachedSnapshot.current) {\n\t\t\treturn cachedSnapshot.current;\n\t\t}\n\n\t\tcachedSnapshot.current = state;\n\t\tcachedUnmetIds.current = state.unmet.map((u) => u.id);\n\t\tcachedInflightIds.current = state.inflight.map((f) => f.id);\n\t\tcachedIsSettled.current = state.isSettled;\n\n\t\treturn state;\n\t}, [system]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n): TimeTravelState | null {\n\tassertSystem(\"useTimeTravel\", system);\n\tconst cachedRef = useRef<TimeTravelState | null>(null);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => system.onTimeTravelChange(onStoreChange),\n\t\t[system],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst state = buildTimeTravelState(system);\n\t\tif (!state) return null;\n\n\t\t// Return stable reference when values haven't changed\n\t\tif (\n\t\t\tcachedRef.current &&\n\t\t\tcachedRef.current.canUndo === state.canUndo &&\n\t\t\tcachedRef.current.canRedo === state.canRedo &&\n\t\t\tcachedRef.current.currentIndex === state.currentIndex &&\n\t\t\tcachedRef.current.totalSnapshots === state.totalSnapshots &&\n\t\t\tcachedRef.current.isPaused === state.isPaused\n\t\t) {\n\t\t\treturn cachedRef.current;\n\t\t}\n\n\t\tcachedRef.current = state;\n\t\treturn cachedRef.current;\n\t}, [system]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n\tstatusPlugin: StatusPlugin,\n\ttype: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useRequirementStatus(\n\tstatusPlugin: StatusPlugin,\n\ttypes: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useRequirementStatus(\n\tstatusPlugin: StatusPlugin,\n\ttypeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n\tif (Array.isArray(typeOrTypes)) {\n\t\treturn _useRequirementStatusMulti(statusPlugin, typeOrTypes);\n\t}\n\treturn _useRequirementStatusSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useRequirementStatusSingle(\n\tstatusPlugin: StatusPlugin,\n\ttype: string,\n): RequirementTypeStatus {\n\tconst cachedRef = useRef<RequirementTypeStatus | typeof UNINITIALIZED>(UNINITIALIZED);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn statusPlugin.subscribe(onStoreChange);\n\t\t},\n\t\t[statusPlugin],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst status = statusPlugin.getStatus(type);\n\n\t\tif (cachedRef.current !== UNINITIALIZED) {\n\t\t\tconst prev = cachedRef.current;\n\t\t\tif (\n\t\t\t\tprev.pending === status.pending &&\n\t\t\t\tprev.inflight === status.inflight &&\n\t\t\t\tprev.failed === status.failed &&\n\t\t\t\tprev.isLoading === status.isLoading &&\n\t\t\t\tprev.hasError === status.hasError &&\n\t\t\t\tprev.lastError === status.lastError\n\t\t\t) {\n\t\t\t\treturn cachedRef.current;\n\t\t\t}\n\t\t}\n\n\t\tcachedRef.current = status;\n\t\treturn status;\n\t}, [statusPlugin, type]);\n\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useRequirementStatusMulti(\n\tstatusPlugin: StatusPlugin,\n\ttypes: string[],\n): Record<string, RequirementTypeStatus> {\n\tconst cachedRef = useRef<Record<string, RequirementTypeStatus> | null>(null);\n\tconst cachedKey = useRef<string>(\"\");\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\treturn statusPlugin.subscribe(onStoreChange);\n\t\t},\n\t\t[statusPlugin],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tconst result: Record<string, RequirementTypeStatus> = {};\n\t\tconst parts: string[] = [];\n\t\tfor (const type of types) {\n\t\t\tconst status = statusPlugin.getStatus(type);\n\t\t\tresult[type] = status;\n\t\t\tparts.push(`${type}:${status.pending}:${status.inflight}:${status.failed}:${status.hasError}:${status.lastError?.message ?? \"\"}`);\n\t\t}\n\t\tconst key = parts.join(\"|\");\n\n\t\tif (key !== cachedKey.current) {\n\t\t\tcachedKey.current = key;\n\t\t\tcachedRef.current = result;\n\t\t}\n\n\t\treturn cachedRef.current ?? result;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [statusPlugin, ...types]);\n\n\treturn 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<StatusPlugin, Map<string, Promise<void>>>();\n\nfunction getSuspenseCache(plugin: StatusPlugin): Map<string, Promise<void>> {\n\tlet cache = suspenseCacheMap.get(plugin);\n\tif (!cache) {\n\t\tcache = new Map();\n\t\tsuspenseCacheMap.set(plugin, cache);\n\t}\n\treturn cache;\n}\n\n/** Single type overload */\nexport function useSuspenseRequirement(\n\tstatusPlugin: StatusPlugin,\n\ttype: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useSuspenseRequirement(\n\tstatusPlugin: StatusPlugin,\n\ttypes: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useSuspenseRequirement(\n\tstatusPlugin: StatusPlugin,\n\ttypeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n\tif (Array.isArray(typeOrTypes)) {\n\t\treturn _useSuspenseRequirementMulti(statusPlugin, typeOrTypes);\n\t}\n\treturn _useSuspenseRequirementSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useSuspenseRequirementSingle(\n\tstatusPlugin: StatusPlugin,\n\ttype: string,\n): RequirementTypeStatus {\n\tconst status = statusPlugin.getStatus(type);\n\n\tif (status.hasError && status.lastError) {\n\t\tthrow status.lastError;\n\t}\n\n\tif (status.isLoading) {\n\t\tconst cache = getSuspenseCache(statusPlugin);\n\t\tlet promise = cache.get(type);\n\n\t\tif (!promise) {\n\t\t\tpromise = new Promise<void>((resolve) => {\n\t\t\t\tconst unsubscribe = statusPlugin.subscribe(() => {\n\t\t\t\t\tconst currentStatus = statusPlugin.getStatus(type);\n\t\t\t\t\tif (!currentStatus.isLoading) {\n\t\t\t\t\t\tcache.delete(type);\n\t\t\t\t\t\tunsubscribe();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t\tcache.set(type, promise);\n\t\t}\n\n\t\tthrow promise;\n\t}\n\n\treturn status;\n}\n\nfunction _useSuspenseRequirementMulti(\n\tstatusPlugin: StatusPlugin,\n\ttypes: string[],\n): Record<string, RequirementTypeStatus> {\n\tconst result: Record<string, RequirementTypeStatus> = {};\n\tlet hasLoading = false;\n\tlet firstError: Error | null = null;\n\n\tfor (const type of types) {\n\t\tconst status = statusPlugin.getStatus(type);\n\t\tresult[type] = status;\n\n\t\tif (status.hasError && status.lastError && !firstError) {\n\t\t\tfirstError = status.lastError;\n\t\t}\n\t\tif (status.isLoading) {\n\t\t\thasLoading = true;\n\t\t}\n\t}\n\n\tif (firstError) {\n\t\tthrow firstError;\n\t}\n\n\tif (hasLoading) {\n\t\tconst cache = getSuspenseCache(statusPlugin);\n\t\tconst cacheKey = types.slice().sort().join(\",\");\n\t\tlet promise = cache.get(cacheKey);\n\n\t\tif (!promise) {\n\t\t\tpromise = new Promise<void>((resolve) => {\n\t\t\t\tconst unsubscribe = statusPlugin.subscribe(() => {\n\t\t\t\t\tconst allDone = types.every((t) => !statusPlugin.getStatus(t).isLoading);\n\t\t\t\t\tif (allDone) {\n\t\t\t\t\t\tcache.delete(cacheKey);\n\t\t\t\t\t\tunsubscribe();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t\tcache.set(cacheKey, promise);\n\t\t}\n\n\t\tthrow promise;\n\t}\n\n\treturn result;\n}\n\n// ============================================================================\n// useDirectiveRef — scoped system lifecycle\n// ============================================================================\n\n/** Base options for creating a scoped system */\ninterface DirectiveRefBaseConfig {\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n\tplugins?: Plugin<any>[];\n\tdebug?: DebugConfig;\n\terrorBoundary?: ErrorBoundaryConfig;\n\ttickMs?: number;\n\tzeroConfig?: boolean;\n\t// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n\tinitialFacts?: Record<string, any>;\n}\n\n/** Options for useDirectiveRef: module directly, or config object */\nexport type UseDirectiveRefOptions<M extends ModuleSchema> =\n\t| ModuleDef<M>\n\t| (DirectiveRefBaseConfig & { module: ModuleDef<M> });\n\n/** Without status (no config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n\toptions: UseDirectiveRefOptions<M>,\n): SingleModuleSystem<M>;\n\n/** Without status (with config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n\toptions: UseDirectiveRefOptions<M>,\n\tconfig: DirectiveRefBaseConfig,\n): SingleModuleSystem<M>;\n\n/** With status: returns { system, statusPlugin } */\nexport function useDirectiveRef<M extends ModuleSchema>(\n\toptions: UseDirectiveRefOptions<M>,\n\tconfig: { status: true } & DirectiveRefBaseConfig,\n): { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin };\n\n/** Implementation */\nexport function useDirectiveRef<M extends ModuleSchema>(\n\toptions: UseDirectiveRefOptions<M>,\n\tconfig?: { status?: boolean } & DirectiveRefBaseConfig,\n): SingleModuleSystem<M> | { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin } {\n\tconst systemRef = useRef<SingleModuleSystem<M> | null>(null);\n\tconst statusPluginRef = useRef<StatusPlugin | null>(null);\n\tconst wantStatus = config?.status === true;\n\n\tif (!systemRef.current) {\n\t\tconst isModule = \"id\" in options && \"schema\" in options;\n\t\tconst mod = isModule ? (options as ModuleDef<M>) : (options as { module: ModuleDef<M> }).module;\n\t\tconst baseOpts = isModule ? {} : (options as DirectiveRefBaseConfig);\n\t\t// Merge config-level options over options-level (config takes precedence)\n\t\tconst plugins = config?.plugins ?? baseOpts.plugins ?? [];\n\t\tconst debug = config?.debug ?? baseOpts.debug;\n\t\tconst errorBoundary = config?.errorBoundary ?? baseOpts.errorBoundary;\n\t\tconst tickMs = config?.tickMs ?? baseOpts.tickMs;\n\t\tconst zeroConfig = config?.zeroConfig ?? baseOpts.zeroConfig;\n\t\tconst initialFacts = config?.initialFacts ?? baseOpts.initialFacts;\n\n\t\tlet allPlugins = [...plugins];\n\n\t\tif (wantStatus) {\n\t\t\tstatusPluginRef.current = createRequirementStatusPlugin();\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n\t\t\tallPlugins = [...allPlugins, statusPluginRef.current.plugin as Plugin<any>];\n\t\t}\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\t\tsystemRef.current = createSystem({\n\t\t\tmodule: mod,\n\t\t\tplugins: allPlugins.length > 0 ? allPlugins : undefined,\n\t\t\tdebug,\n\t\t\terrorBoundary,\n\t\t\ttickMs,\n\t\t\tzeroConfig,\n\t\t\tinitialFacts,\n\t\t} as any) as unknown as SingleModuleSystem<M>;\n\n\t}\n\n\tuseEffect(() => {\n\t\tconst sys = systemRef.current;\n\t\tsys?.start();\n\t\treturn () => {\n\t\t\tsys?.destroy();\n\t\t\tsystemRef.current = null;\n\t\t\tstatusPluginRef.current = null;\n\t\t};\n\t}, []);\n\n\tif (wantStatus) {\n\t\treturn {\n\t\t\tsystem: systemRef.current!,\n\t\t\tstatusPlugin: statusPluginRef.current!,\n\t\t};\n\t}\n\n\treturn systemRef.current!;\n}\n\n// ============================================================================\n// useDirective — scoped system with selected values in containers\n// ============================================================================\n\n/** Options for useDirective hook */\nexport interface UseDirectiveOptions<\n\tS extends ModuleSchema,\n\tFK extends keyof InferFacts<S> & string = never,\n\tDK extends keyof InferDerivations<S> & string = never,\n> extends DirectiveRefBaseConfig {\n\t/** Fact keys to subscribe to */\n\tfacts?: FK[];\n\t/** Derivation keys to subscribe to */\n\tderived?: DK[];\n\t/** Enable status plugin */\n\tstatus?: boolean;\n}\n\n/** Return type for useDirective hook (without status) */\nexport type UseDirectiveReturn<\n\tS extends ModuleSchema,\n\tFK extends keyof InferFacts<S> & string,\n\tDK extends keyof InferDerivations<S> & string,\n> = {\n\tsystem: SingleModuleSystem<S>;\n\tdispatch: (event: InferEvents<S>) => void;\n\tevents: SingleModuleSystem<S>[\"events\"];\n\tfacts: Pick<InferFacts<S>, FK>;\n\tderived: Pick<InferDerivations<S>, DK>;\n};\n\n/** Return type for useDirective hook (with status) */\nexport type UseDirectiveReturnWithStatus<\n\tS extends ModuleSchema,\n\tFK extends keyof InferFacts<S> & string,\n\tDK extends keyof InferDerivations<S> & string,\n> = UseDirectiveReturn<S, FK, DK> & {\n\tstatusPlugin: 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\tS extends ModuleSchema,\n\tFK extends keyof InferFacts<S> & string = never,\n\tDK extends keyof InferDerivations<S> & string = never,\n>(\n\tmoduleOrOptions: UseDirectiveRefOptions<S>,\n\tselections: UseDirectiveOptions<S, FK, DK> = {} as UseDirectiveOptions<S, FK, DK>,\n): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK> {\n\tconst { facts: factKeysOpt, derived: derivedKeysOpt, status, ...configRest } = selections;\n\tconst factKeys = (factKeysOpt ?? []) as FK[];\n\tconst derivedKeys = (derivedKeysOpt ?? []) as DK[];\n\n\t// When no keys are specified, subscribe to everything\n\tconst subscribeAll = factKeys.length === 0 && derivedKeys.length === 0;\n\n\t// Create system via useDirectiveRef (handles lifecycle)\n\t// biome-ignore lint/suspicious/noExplicitAny: Conditional overload dispatch\n\tconst refResult: any = status\n\t\t? useDirectiveRef(moduleOrOptions, { status: true as const, ...configRest })\n\t\t: useDirectiveRef(moduleOrOptions, configRest);\n\n\tconst system: SingleModuleSystem<S> = status\n\t\t? refResult.system\n\t\t: refResult;\n\n\tconst statusPlugin = status\n\t\t? (refResult as { system: SingleModuleSystem<S>; statusPlugin: StatusPlugin }).statusPlugin\n\t\t: undefined;\n\n\t// For subscribe-all mode, get all derivation keys\n\tconst allDerivationKeys = useMemo(\n\t\t() => (subscribeAll ? Object.keys(system.derive) : []),\n\t\t[system, subscribeAll],\n\t);\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\tconst unsubs: Array<() => void> = [];\n\t\t\tif (subscribeAll) {\n\t\t\t\t// Subscribe to ALL facts and ALL derivations\n\t\t\t\tunsubs.push(system.facts.$store.subscribeAll(onStoreChange));\n\t\t\t\tif (allDerivationKeys.length > 0) {\n\t\t\t\t\tunsubs.push(system.subscribe(allDerivationKeys, onStoreChange));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (factKeys.length > 0) {\n\t\t\t\t\tunsubs.push(system.facts.$store.subscribe(factKeys, onStoreChange));\n\t\t\t\t}\n\t\t\t\tif (derivedKeys.length > 0) {\n\t\t\t\t\tunsubs.push(system.subscribe(derivedKeys, onStoreChange));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn () => {\n\t\t\t\tfor (const unsub of unsubs) unsub();\n\t\t\t};\n\t\t},\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys],\n\t);\n\n\tconst cachedFacts = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\tconst cachedDerived = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\tconst cachedWrapper = useRef<{ facts: Record<string, unknown>; derived: Record<string, unknown> } | null>(null);\n\n\tconst getSnapshot = useCallback(() => {\n\t\tlet factsResult: Record<string, unknown>;\n\t\tlet derivedResult: Record<string, unknown>;\n\t\tlet effectiveFactKeys: readonly string[];\n\t\tlet effectiveDerivedKeys: readonly string[];\n\n\t\tif (subscribeAll) {\n\t\t\t// Read ALL facts and ALL derivations\n\t\t\tfactsResult = system.facts.$store.toObject();\n\t\t\teffectiveFactKeys = Object.keys(factsResult);\n\t\t\tderivedResult = {};\n\t\t\tfor (const key of allDerivationKeys) {\n\t\t\t\tderivedResult[key] = system.read(key);\n\t\t\t}\n\t\t\teffectiveDerivedKeys = allDerivationKeys;\n\t\t} else {\n\t\t\t// Read selected keys only\n\t\t\tfactsResult = {};\n\t\t\tfor (const key of factKeys) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n\t\t\t\tfactsResult[key] = (system.facts as any)[key];\n\t\t\t}\n\t\t\teffectiveFactKeys = factKeys;\n\t\t\tderivedResult = {};\n\t\t\tfor (const key of derivedKeys) {\n\t\t\t\tderivedResult[key] = system.read(key);\n\t\t\t}\n\t\t\teffectiveDerivedKeys = derivedKeys;\n\t\t}\n\n\t\t// Check facts stability\n\t\tlet factsSame = cachedFacts.current !== UNINITIALIZED;\n\t\tif (factsSame) {\n\t\t\tconst prev = cachedFacts.current as Record<string, unknown>;\n\t\t\tconst prevKeys = Object.keys(prev);\n\t\t\tif (prevKeys.length !== effectiveFactKeys.length) {\n\t\t\t\tfactsSame = false;\n\t\t\t} else {\n\t\t\t\tfor (const key of effectiveFactKeys) {\n\t\t\t\t\tif (!Object.is(prev[key], factsResult[key])) {\n\t\t\t\t\t\tfactsSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check derived stability\n\t\tlet derivedSame = cachedDerived.current !== UNINITIALIZED;\n\t\tif (derivedSame) {\n\t\t\tconst prev = cachedDerived.current as Record<string, unknown>;\n\t\t\tconst prevKeys = Object.keys(prev);\n\t\t\tif (prevKeys.length !== effectiveDerivedKeys.length) {\n\t\t\t\tderivedSame = false;\n\t\t\t} else {\n\t\t\t\tfor (const key of effectiveDerivedKeys) {\n\t\t\t\t\tif (!Object.is(prev[key], derivedResult[key])) {\n\t\t\t\t\t\tderivedSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst stableFacts = factsSame ? cachedFacts.current as Record<string, unknown> : factsResult;\n\t\tconst stableDerived = derivedSame ? cachedDerived.current as Record<string, unknown> : derivedResult;\n\n\t\tif (!factsSame) cachedFacts.current = factsResult;\n\t\tif (!derivedSame) cachedDerived.current = derivedResult;\n\n\t\t// Return same wrapper reference when both containers are unchanged\n\t\tif (factsSame && derivedSame && cachedWrapper.current) {\n\t\t\treturn cachedWrapper.current;\n\t\t}\n\n\t\tcachedWrapper.current = { facts: stableFacts, derived: stableDerived };\n\t\treturn cachedWrapper.current;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys]);\n\n\tconst values = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n\tconst dispatch = useCallback(\n\t\t(event: InferEvents<S>) => system.dispatch(event),\n\t\t[system],\n\t);\n\n\tconst events = useEvents(system);\n\n\tconst base = {\n\t\tsystem,\n\t\tdispatch,\n\t\tevents,\n\t\tfacts: values.facts as Pick<InferFacts<S>, FK>,\n\t\tderived: values.derived as Pick<InferDerivations<S>, DK>,\n\t};\n\n\tif (status && statusPlugin) {\n\t\treturn { ...base, statusPlugin } as UseDirectiveReturnWithStatus<S, FK, DK>;\n\t}\n\n\treturn base as UseDirectiveReturn<S, FK, DK>;\n}\n\n// ============================================================================\n// DevTools Component\n// ============================================================================\n\n/** Props for DirectiveDevTools component */\nexport interface DirectiveDevToolsProps {\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>;\n\t/** Position of the panel */\n\tposition?: \"bottom-right\" | \"bottom-left\" | \"top-right\" | \"top-left\";\n\t/** Whether the panel starts open */\n\tdefaultOpen?: boolean;\n}\n\n/**\n * Dev-only floating panel that shows system state.\n * Tree-shaken in production builds via `process.env.NODE_ENV` check.\n */\nexport function DirectiveDevTools({\n\tsystem,\n\tposition = \"bottom-right\",\n\tdefaultOpen = false,\n}: DirectiveDevToolsProps): ReturnType<typeof import(\"react\").createElement> | null {\n\tconst [isOpen, setIsOpen] = useState(defaultOpen);\n\tconst closeButtonRef = useRef<HTMLButtonElement | null>(null);\n\tconst { isSettled, unmet, inflight } = useInspect(system);\n\n\t// Auto-focus close button when panel opens\n\tuseEffect(() => {\n\t\tif (isOpen && closeButtonRef.current) {\n\t\t\tcloseButtonRef.current.focus();\n\t\t}\n\t}, [isOpen]);\n\n\t// Facts subscription for devtools\n\tconst factsSubscribe = useCallback(\n\t\t(onStoreChange: () => void) => system.facts.$store.subscribeAll(onStoreChange),\n\t\t[system],\n\t);\n\tconst factsRef = useRef<Record<string, unknown> | typeof UNINITIALIZED>(UNINITIALIZED);\n\tconst getFactsSnapshot = useCallback(() => {\n\t\tconst current = system.facts.$store.toObject();\n\t\tif (factsRef.current !== UNINITIALIZED) {\n\t\t\tconst prevKeys = Object.keys(factsRef.current as Record<string, unknown>);\n\t\t\tconst currKeys = Object.keys(current);\n\t\t\tif (prevKeys.length === currKeys.length) {\n\t\t\t\tlet same = true;\n\t\t\t\tfor (const key of currKeys) {\n\t\t\t\t\tif (!Object.is((factsRef.current as Record<string, unknown>)[key], current[key])) {\n\t\t\t\t\t\tsame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (same) return factsRef.current as Record<string, unknown>;\n\t\t\t}\n\t\t}\n\t\tfactsRef.current = current;\n\t\treturn current;\n\t}, [system]);\n\tconst facts = useSyncExternalStore(factsSubscribe, getFactsSnapshot, getFactsSnapshot);\n\n\tif (process.env.NODE_ENV === \"production\") return null;\n\n\tconst positionStyles: Record<string, string | number> = {\n\t\tposition: \"fixed\",\n\t\tzIndex: 99999,\n\t\t...(position.includes(\"bottom\") ? { bottom: 12 } : { top: 12 }),\n\t\t...(position.includes(\"right\") ? { right: 12 } : { left: 12 }),\n\t};\n\n\tif (!isOpen) {\n\t\treturn (\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonClick={() => setIsOpen(true)}\n\t\t\t\taria-label={`Open Directive DevTools${isSettled ? \"\" : \" (system working)\"}`}\n\t\t\t\taria-expanded={false}\n\t\t\t\tstyle={{\n\t\t\t\t\t...positionStyles,\n\t\t\t\t\tbackground: \"#1a1a2e\",\n\t\t\t\t\tcolor: \"#e0e0e0\",\n\t\t\t\t\tborder: \"1px solid #333\",\n\t\t\t\t\tborderRadius: 6,\n\t\t\t\t\tpadding: \"6px 12px\",\n\t\t\t\t\tcursor: \"pointer\",\n\t\t\t\t\tfontFamily: \"monospace\",\n\t\t\t\t\tfontSize: 12,\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t{isSettled ? \"Directive\" : \"Directive...\"}\n\t\t\t</button>\n\t\t);\n\t}\n\n\tconst derivationKeys = Object.keys(system.derive);\n\tconst derivations: Record<string, unknown> = {};\n\tfor (const key of derivationKeys) {\n\t\ttry {\n\t\t\tderivations[key] = system.read(key);\n\t\t} catch {\n\t\t\tderivations[key] = \"<error>\";\n\t\t}\n\t}\n\n\treturn (\n\t\t<div\n\t\t\trole=\"region\"\n\t\t\taria-label=\"Directive DevTools\"\n\t\t\ttabIndex={-1}\n\t\t\tonKeyDown={(e) => {\n\t\t\t\tif (e.key === \"Escape\") setIsOpen(false);\n\t\t\t}}\n\t\t\tstyle={{\n\t\t\t\t...positionStyles,\n\t\t\t\tbackground: \"#1a1a2e\",\n\t\t\t\tcolor: \"#e0e0e0\",\n\t\t\t\tborder: \"1px solid #333\",\n\t\t\t\tborderRadius: 8,\n\t\t\t\tpadding: 12,\n\t\t\t\tfontFamily: \"monospace\",\n\t\t\t\tfontSize: 11,\n\t\t\t\tmaxWidth: 380,\n\t\t\t\tmaxHeight: 500,\n\t\t\t\toverflow: \"auto\",\n\t\t\t\tboxShadow: \"0 4px 20px rgba(0,0,0,0.5)\",\n\t\t\t}}\n\t\t>\n\t\t\t<div style={{ display: \"flex\", justifyContent: \"space-between\", marginBottom: 8 }}>\n\t\t\t\t<strong style={{ color: \"#7c8aff\" }}>Directive DevTools</strong>\n\t\t\t\t<button\n\t\t\t\t\tref={closeButtonRef}\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonClick={() => setIsOpen(false)}\n\t\t\t\t\taria-label=\"Close DevTools\"\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tbackground: \"none\",\n\t\t\t\t\t\tborder: \"none\",\n\t\t\t\t\t\tcolor: \"#888\",\n\t\t\t\t\t\tcursor: \"pointer\",\n\t\t\t\t\t\tfontSize: 14,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t{\"\\u00D7\"}\n\t\t\t\t</button>\n\t\t\t</div>\n\n\t\t\t<div style={{ marginBottom: 6 }} aria-live=\"polite\">\n\t\t\t\t<span style={{ color: isSettled ? \"#4ade80\" : \"#fbbf24\" }}>\n\t\t\t\t\t{isSettled ? \"Settled\" : \"Working...\"}\n\t\t\t\t</span>\n\t\t\t</div>\n\n\t\t\t<details open>\n\t\t\t\t<summary style={{ cursor: \"pointer\", color: \"#7c8aff\", marginBottom: 4 }}>\n\t\t\t\t\tFacts ({Object.keys(facts).length})\n\t\t\t\t</summary>\n\t\t\t\t<table style={{ width: \"100%\", borderCollapse: \"collapse\", fontSize: 11 }}>\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th style={{ textAlign: \"left\", padding: \"2px 4px\", color: \"#7c8aff\" }}>Key</th>\n\t\t\t\t\t\t\t<th style={{ textAlign: \"left\", padding: \"2px 4px\", color: \"#7c8aff\" }}>Value</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t\t{Object.entries(facts).map(([key, value]) => {\n\t\t\t\t\t\t\tlet display: string;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdisplay = typeof value === \"object\" ? JSON.stringify(value) : String(value);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tdisplay = \"<error>\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<tr key={key} style={{ borderBottom: \"1px solid #2a2a4a\" }}>\n\t\t\t\t\t\t\t\t\t<td style={{ padding: \"2px 4px\", color: \"#a0a0c0\" }}>{key}</td>\n\t\t\t\t\t\t\t\t\t<td style={{ padding: \"2px 4px\" }}>{display}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})}\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t</details>\n\n\t\t\t{derivationKeys.length > 0 && (\n\t\t\t\t<details>\n\t\t\t\t\t<summary style={{ cursor: \"pointer\", color: \"#7c8aff\", marginBottom: 4 }}>\n\t\t\t\t\t\tDerivations ({derivationKeys.length})\n\t\t\t\t\t</summary>\n\t\t\t\t\t<table style={{ width: \"100%\", borderCollapse: \"collapse\", fontSize: 11 }}>\n\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th style={{ textAlign: \"left\", padding: \"2px 4px\", color: \"#7c8aff\" }}>Key</th>\n\t\t\t\t\t\t\t\t<th style={{ textAlign: \"left\", padding: \"2px 4px\", color: \"#7c8aff\" }}>Value</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t<tbody>\n\t\t\t\t\t\t\t{Object.entries(derivations).map(([key, value]) => (\n\t\t\t\t\t\t\t\t<tr key={key} style={{ borderBottom: \"1px solid #2a2a4a\" }}>\n\t\t\t\t\t\t\t\t\t<td style={{ padding: \"2px 4px\", color: \"#a0a0c0\" }}>{key}</td>\n\t\t\t\t\t\t\t\t\t<td style={{ padding: \"2px 4px\" }}>\n\t\t\t\t\t\t\t\t\t\t{typeof value === \"object\" ? JSON.stringify(value) : String(value)}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</tbody>\n\t\t\t\t\t</table>\n\t\t\t\t</details>\n\t\t\t)}\n\n\t\t\t{inflight.length > 0 && (\n\t\t\t\t<details open>\n\t\t\t\t\t<summary style={{ cursor: \"pointer\", color: \"#fbbf24\", marginBottom: 4 }}>\n\t\t\t\t\t\tInflight ({inflight.length})\n\t\t\t\t\t</summary>\n\t\t\t\t\t<ul style={{ margin: 0, paddingLeft: 16 }}>\n\t\t\t\t\t\t{inflight.map((r) => (\n\t\t\t\t\t\t\t<li key={r.id} style={{ fontSize: 11 }}>\n\t\t\t\t\t\t\t\t{r.resolverId} ({r.id})\n\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</ul>\n\t\t\t\t</details>\n\t\t\t)}\n\n\t\t\t{unmet.length > 0 && (\n\t\t\t\t<details open>\n\t\t\t\t\t<summary style={{ cursor: \"pointer\", color: \"#f87171\", marginBottom: 4 }}>\n\t\t\t\t\t\tUnmet ({unmet.length})\n\t\t\t\t\t</summary>\n\t\t\t\t\t<ul style={{ margin: 0, paddingLeft: 16 }}>\n\t\t\t\t\t\t{unmet.map((r) => (\n\t\t\t\t\t\t\t<li key={r.id} style={{ fontSize: 11 }}>\n\t\t\t\t\t\t\t\t{r.requirement.type} from {r.fromConstraint}\n\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</ul>\n\t\t\t\t</details>\n\t\t\t)}\n\t\t</div>\n\t);\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\tsystem: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n\tassertSystem(\"useEvents\", system);\n\treturn 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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\trequirementId: string,\n): string | null {\n\tassertSystem(\"useExplain\", system);\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void) => {\n\t\t\tconst unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n\t\t\tconst unsubSettled = system.onSettledChange(onStoreChange);\n\t\t\treturn () => {\n\t\t\t\tunsubFacts();\n\t\t\t\tunsubSettled();\n\t\t\t};\n\t\t},\n\t\t[system],\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\treturn system.explain(requirementId);\n\t}, [system, requirementId]);\n\n\treturn 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\tsystem: SingleModuleSystem<any>,\n): ConstraintInfo[];\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId: string,\n): ConstraintInfo | null;\n/** Implementation */\nexport function useConstraintStatus(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n\tassertSystem(\"useConstraintStatus\", system);\n\tconst inspectState = useInspect(system);\n\n\treturn useMemo(() => {\n\t\tconst inspection = system.inspect();\n\t\tif (!constraintId) return inspection.constraints;\n\t\treturn inspection.constraints.find((c) => c.id === constraintId) ?? null;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [system, constraintId, inspectState]);\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\n/** Result of useOptimisticUpdate */\nexport interface OptimisticUpdateResult {\n\t/** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */\n\tmutate: (updateFn: () => void) => void;\n\t/** Whether a resolver is currently processing the optimistic change */\n\tisPending: boolean;\n\t/** Error if the resolver failed */\n\terror: Error | null;\n\t/** Manually rollback to the pre-mutation snapshot */\n\trollback: () => 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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\tstatusPlugin?: StatusPlugin,\n\trequirementType?: string,\n): OptimisticUpdateResult {\n\tassertSystem(\"useOptimisticUpdate\", system);\n\tconst [isPending, setIsPending] = useState(false);\n\tconst [error, setError] = useState<Error | null>(null);\n\tconst snapshotRef = useRef<SystemSnapshot | null>(null);\n\n\tconst rollback = useCallback(() => {\n\t\tif (snapshotRef.current) {\n\t\t\tsystem.restore(snapshotRef.current);\n\t\t\tsnapshotRef.current = null;\n\t\t}\n\t\tsetIsPending(false);\n\t\tsetError(null);\n\t}, [system]);\n\n\tconst mutate = useCallback(\n\t\t(updateFn: () => void) => {\n\t\t\tsnapshotRef.current = system.getSnapshot();\n\t\t\tsetIsPending(true);\n\t\t\tsetError(null);\n\t\t\tsystem.batch(updateFn);\n\t\t},\n\t\t[system],\n\t);\n\n\t// Watch for resolver completion/failure\n\tuseEffect(() => {\n\t\tif (!statusPlugin || !requirementType || !isPending) return;\n\n\t\treturn statusPlugin.subscribe(() => {\n\t\t\tconst status = statusPlugin.getStatus(requirementType);\n\t\t\tif (!status.isLoading && !status.hasError) {\n\t\t\t\t// Resolved successfully — keep optimistic state\n\t\t\t\tsnapshotRef.current = null;\n\t\t\t\tsetIsPending(false);\n\t\t\t} else if (status.hasError) {\n\t\t\t\t// Failed — rollback\n\t\t\t\tsetError(status.lastError);\n\t\t\t\trollback();\n\t\t\t}\n\t\t});\n\t}, [statusPlugin, requirementType, isPending, rollback]);\n\n\treturn { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// DirectiveHydrator + useHydratedSystem — SSR/RSC hydration\n// ============================================================================\n\n/** Props for DirectiveHydrator component */\nexport interface HydratorProps {\n\tsnapshot: DistributableSnapshot;\n\tchildren: 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\treturn (\n\t\t<HydrationContext.Provider value={snapshot}>\n\t\t\t{children}\n\t\t</HydrationContext.Provider>\n\t);\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\tmoduleDef: ModuleDef<S>,\n\tconfig?: DirectiveRefBaseConfig,\n): SingleModuleSystem<S> {\n\tconst snapshot = useContext(HydrationContext);\n\n\t// Merge snapshot data as initial facts if available\n\tconst mergedConfig = useMemo(() => {\n\t\tif (!snapshot?.data) return config ?? {};\n\t\treturn {\n\t\t\t...(config ?? {}),\n\t\t\tinitialFacts: {\n\t\t\t\t...(config?.initialFacts ?? {}),\n\t\t\t\t...snapshot.data,\n\t\t\t},\n\t\t};\n\t}, [snapshot, config]);\n\n\treturn useDirectiveRef(moduleDef, mergedConfig) as SingleModuleSystem<S>;\n}\n\n"]}
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@directive-run/react",
3
+ "version": "0.1.1",
4
+ "description": "React hooks and components for Directive.",
5
+ "license": "MIT",
6
+ "author": "Jason Comes",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/directive-run/directive",
10
+ "directory": "packages/react"
11
+ },
12
+ "homepage": "https://directive.run",
13
+ "bugs": {
14
+ "url": "https://github.com/directive-run/directive/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "registry": "https://registry.npmjs.org"
19
+ },
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "keywords": [
24
+ "directive",
25
+ "react",
26
+ "hooks",
27
+ "state-management",
28
+ "reactive",
29
+ "constraint-driven"
30
+ ],
31
+ "sideEffects": false,
32
+ "type": "module",
33
+ "main": "./dist/index.cjs",
34
+ "module": "./dist/index.js",
35
+ "types": "./dist/index.d.ts",
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.ts",
39
+ "require": "./dist/index.cjs",
40
+ "import": "./dist/index.js"
41
+ }
42
+ },
43
+ "files": [
44
+ "dist"
45
+ ],
46
+ "peerDependencies": {
47
+ "react": ">=18",
48
+ "@directive-run/core": "0.1.1"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^25.2.0",
52
+ "@types/react": "^18.3.3",
53
+ "react": "^18.3.1",
54
+ "tsup": "^8.3.5",
55
+ "typescript": "^5.7.2",
56
+ "@directive-run/core": "0.1.1"
57
+ },
58
+ "scripts": {
59
+ "build": "tsup",
60
+ "dev": "tsup --watch",
61
+ "test": "vitest run",
62
+ "typecheck": "tsc --noEmit",
63
+ "clean": "rm -rf dist"
64
+ }
65
+ }