@directive-run/react 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -11,6 +11,47 @@ type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;
11
11
  declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;
12
12
  /** Multi-key overload */
13
13
  declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;
14
+ /**
15
+ * Read a fact, falling back to a lazily-computed default with **stable
16
+ * referential identity** when the fact is `null`/`undefined`.
17
+ *
18
+ * **Why this exists:** the natural pattern
19
+ *
20
+ * ```tsx
21
+ * const markedCells = useFact(sys, "markedCells") ?? deps.initializeMarkedCells();
22
+ * ```
23
+ *
24
+ * calls `initializeMarkedCells()` on every render where `markedCells` is
25
+ * `null`, producing a fresh array/object identity each time. Anything
26
+ * downstream that memoizes on that identity (`useMemo` deps,
27
+ * `React.memo`, virtualized list keys) re-runs unnecessarily and can
28
+ * trigger re-render storms.
29
+ *
30
+ * `useFactWithDefault` runs `factory` at most once per system instance and
31
+ * caches the result in a ref. While the fact is `null`/`undefined`, every
32
+ * render returns the same cached value. When the fact transitions to a
33
+ * non-null value, that value is returned instead. If the fact later
34
+ * returns to `null`, the originally-cached factory result is reused
35
+ * (the factory is **not** called again).
36
+ *
37
+ * Swapping the `system` argument re-runs the factory on the new system.
38
+ *
39
+ * @example
40
+ * ```tsx
41
+ * const markedCells = useFactWithDefault(
42
+ * sys,
43
+ * "markedCells",
44
+ * () => deps.initializeMarkedCells(),
45
+ * );
46
+ * // `markedCells` has stable identity across renders while the fact is null.
47
+ * ```
48
+ *
49
+ * @param system - The system to read the fact from.
50
+ * @param factKey - The fact key.
51
+ * @param factory - Lazy default factory; runs at most once per system instance.
52
+ * @returns The fact value when non-null, otherwise the cached factory result.
53
+ */
54
+ declare function useFactWithDefault<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K, factory: () => NonNullable<InferFacts<S>[K]>): NonNullable<InferFacts<S>[K]>;
14
55
  /** Single key overload */
15
56
  declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];
16
57
  /** Multi-key overload */
@@ -450,4 +491,4 @@ declare function createDirectiveContext<M extends ModuleSchema>(system: SingleMo
450
491
  useHistory: () => HistoryState | null;
451
492
  };
452
493
 
453
- export { DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefNamespacedOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, createDirectiveContext, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useHistory, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useSuspenseQuery, useSuspenseRequirement, useTickWhile, useWatch };
494
+ export { DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefNamespacedOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, createDirectiveContext, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useFactWithDefault, useHistory, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useSuspenseQuery, useSuspenseRequirement, useTickWhile, useWatch };
package/dist/index.d.ts CHANGED
@@ -11,6 +11,47 @@ type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;
11
11
  declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;
12
12
  /** Multi-key overload */
13
13
  declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;
14
+ /**
15
+ * Read a fact, falling back to a lazily-computed default with **stable
16
+ * referential identity** when the fact is `null`/`undefined`.
17
+ *
18
+ * **Why this exists:** the natural pattern
19
+ *
20
+ * ```tsx
21
+ * const markedCells = useFact(sys, "markedCells") ?? deps.initializeMarkedCells();
22
+ * ```
23
+ *
24
+ * calls `initializeMarkedCells()` on every render where `markedCells` is
25
+ * `null`, producing a fresh array/object identity each time. Anything
26
+ * downstream that memoizes on that identity (`useMemo` deps,
27
+ * `React.memo`, virtualized list keys) re-runs unnecessarily and can
28
+ * trigger re-render storms.
29
+ *
30
+ * `useFactWithDefault` runs `factory` at most once per system instance and
31
+ * caches the result in a ref. While the fact is `null`/`undefined`, every
32
+ * render returns the same cached value. When the fact transitions to a
33
+ * non-null value, that value is returned instead. If the fact later
34
+ * returns to `null`, the originally-cached factory result is reused
35
+ * (the factory is **not** called again).
36
+ *
37
+ * Swapping the `system` argument re-runs the factory on the new system.
38
+ *
39
+ * @example
40
+ * ```tsx
41
+ * const markedCells = useFactWithDefault(
42
+ * sys,
43
+ * "markedCells",
44
+ * () => deps.initializeMarkedCells(),
45
+ * );
46
+ * // `markedCells` has stable identity across renders while the fact is null.
47
+ * ```
48
+ *
49
+ * @param system - The system to read the fact from.
50
+ * @param factKey - The fact key.
51
+ * @param factory - Lazy default factory; runs at most once per system instance.
52
+ * @returns The fact value when non-null, otherwise the cached factory result.
53
+ */
54
+ declare function useFactWithDefault<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K, factory: () => NonNullable<InferFacts<S>[K]>): NonNullable<InferFacts<S>[K]>;
14
55
  /** Single key overload */
15
56
  declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];
16
57
  /** Multi-key overload */
@@ -450,4 +491,4 @@ declare function createDirectiveContext<M extends ModuleSchema>(system: SingleMo
450
491
  useHistory: () => HistoryState | null;
451
492
  };
452
493
 
453
- export { DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefNamespacedOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, createDirectiveContext, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useHistory, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useSuspenseQuery, useSuspenseRequirement, useTickWhile, useWatch };
494
+ export { DirectiveHydrator, type HydratorProps, type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveOptions, type UseDirectiveRefNamespacedOptions, type UseDirectiveRefOptions, type UseDirectiveReturn, type UseDirectiveReturnWithStatus, type UseInspectOptions, createDirectiveContext, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDirectiveRef, useDispatch, useEvents, useExplain, useFact, useFactWithDefault, useHistory, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useSuspenseQuery, useSuspenseRequirement, useTickWhile, useWatch };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {createSystem,createRequirementStatusPlugin}from'@directive-run/core';import {assertSystem,defaultEquality,runTrackedSelector,createThrottle,buildHistoryState,mergeHydrationFacts,depsChanged,computeInspectState}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {createContext,useCallback,useSyncExternalStore,useRef,useMemo,useEffect,useState,useContext}from'react';import {jsx}from'react/jsx-runtime';var ue=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x=Symbol("directive.uninitialized");function G(e,t){return assertSystem("useFact",e),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)?pe(e,t):Se(e,t)}function Se(e,t){(t in e.facts.$store.toObject()||console.warn(`[Directive] useFact("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`));let r=useCallback(n=>e.facts.$store.subscribe([t],n),[e,t]),s=useCallback(()=>e.facts.$store.get(t),[e,t]);return useSyncExternalStore(r,s,s)}function pe(e,t){let r=useRef(x),s=useCallback(u=>e.facts.$store.subscribe(t,u),[e,...t]),n=useCallback(()=>{let u={};for(let o of t)u[o]=e.facts.$store.get(o);if(r.current!==x){let o=true;for(let i of t)if(!Object.is(r.current[i],u[i])){o=false;break}if(o)return r.current}return r.current=u,u},[e,...t]);return useSyncExternalStore(s,n,n)}function J(e,t){return assertSystem("useDerived",e),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)?ye(e,t):ge(e,t)}function ge(e,t){(t in e.derive||console.warn(`[Directive] useDerived("${t}") \u2014 derivation not found. Check that "${t}" is defined in your module's derive property.`));let r=useCallback(n=>e.subscribe([t],n),[e,t]),s=useCallback(()=>e.read(t),[e,t]);return useSyncExternalStore(r,s,s)}function ye(e,t){let r=useRef(x),s=useCallback(u=>e.subscribe(t,u),[e,...t]),n=useCallback(()=>{let u={};for(let o of t)u[o]=e.read(o);if(r.current!==x){let o=true;for(let i of t)if(!Object.is(r.current[i],u[i])){o=false;break}if(o)return r.current}return r.current=u,u},[e,...t]);return useSyncExternalStore(s,n,n)}function ve(e,t,r,s){if(e&&e._mode==="namespaced")return Me(e,t,r,s);let n=e,u,o=false,i=s??defaultEquality;r!==void 0&&(u=r,o=true),!n&&!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 f=useRef(t),a=useRef(i),c=useRef(u),g=useRef(t),y=useRef(0);g.current!==t&&(g.current=t,y.current++),f.current=t,a.current=i,c.current=u;let F=y.current,v=useRef([]),k=useRef([]),D=useRef(x),m=useRef([]),P=useMemo(()=>n?new Set(Object.keys(n.derive)):new Set,[n]),E=useCallback(()=>n?runTrackedSelector(n,P,f.current):{value:c.current,factKeys:[],deriveKeys:[]},[n,P]),I=useCallback(S=>{if(!n)return ()=>{};let p=()=>{for(let M of m.current)M();m.current=[];let{factKeys:R,deriveKeys:w}=E();v.current=R,k.current=w,R.length>0?m.current.push(n.facts.$store.subscribe(R,()=>{let M=E();depsChanged(v.current,M.factKeys,k.current,M.deriveKeys)&&p(),S();})):w.length===0&&m.current.push(n.facts.$store.subscribeAll(S)),w.length>0&&m.current.push(n.subscribe(w,()=>{let M=E();depsChanged(v.current,M.factKeys,k.current,M.deriveKeys)&&p(),S();}));};return p(),()=>{for(let R of m.current)R();m.current=[];}},[n,E,F]),C=useCallback(()=>{let S;if(!n)S=c.current;else {let{value:p}=E();S=p===void 0&&o?c.current:p;}return D.current!==x&&a.current(D.current,S)?D.current:(D.current=S,S)},[E,n,o]);return useSyncExternalStore(I,C,C)}function Me(e,t,r,s){let n=r!==void 0,u=s??defaultEquality,o=useRef(t),i=useRef(u),f=useRef(r);o.current=t,i.current=u,f.current=r;let a=useRef(x),c=useMemo(()=>Object.keys(e.facts),[e]),g=useCallback(F=>{let v=c.map(k=>`${k}.*`);return e.subscribe(v,F)},[e,c]),y=useCallback(()=>{let F=o.current(e),v=F===void 0&&n?f.current:F;return a.current!==x&&i.current(a.current,v)?a.current:(a.current=v,v)},[e,n]);return useSyncExternalStore(g,y,y)}function X(e){return assertSystem("useDispatch",e),useCallback(t=>{e.dispatch(t);},[e])}function Y(e,t,r){assertSystem("useWatch",e);let s=useRef(r);s.current=r,useEffect(()=>e.watch(t,(n,u)=>{s.current(n,u);}),[e,t]);}function me(e,t,r,s){assertSystem("useTickWhile",e);let n=useRef(t);n.current=t;let u=useCallback(f=>{let a=e.facts.$store.subscribeAll(f),c=e.onSettledChange(f);return ()=>{a(),c();}},[e]),o=useCallback(()=>n.current(e),[e]),i=useSyncExternalStore(u,o,o);useEffect(()=>{if(!i)return;if(!Number.isFinite(s)||s<=0){console.warn(`[Directive] useTickWhile() received non-positive intervalMs: ${s}. Interval will not fire.`);return}let f=setInterval(()=>{let c=e.events[r];typeof c=="function"?c():console.warn(`[Directive] useTickWhile() \u2014 event "${String(r)}" not found on system.events.`);},s);return ()=>clearInterval(f)},[i,e,r,s]);}function ee(e,t){assertSystem("useInspect",e);let r=Re(e),s=t?.throttleMs,[n,u]=useState(r),o=useRef(null);return useEffect(()=>{if(!s||s<=0){o.current?.cleanup(),o.current=null;return}return o.current?.cleanup(),o.current=createThrottle((...i)=>{u(i[0]);},s),()=>{o.current?.cleanup(),o.current=null;}},[s]),useEffect(()=>{o.current&&o.current.throttled(r);},[r]),!s||s<=0?r:n}function he(e){return computeInspectState(e)}function Re(e){let t=useRef(null),r=useRef([]),s=useRef([]),n=useRef(null),u=useCallback(i=>{let f=e.facts.$store.subscribeAll(i),a=e.onSettledChange(i);return ()=>{f(),a();}},[e]),o=useCallback(()=>{let i=he(e),f=i.unmet.length===r.current.length&&i.unmet.every((g,y)=>g.id===r.current[y]),a=i.inflight.length===s.current.length&&i.inflight.every((g,y)=>g.id===s.current[y]),c=i.isSettled===n.current;return f&&a&&c&&t.current?t.current:(t.current=i,r.current=i.unmet.map(g=>g.id),s.current=i.inflight.map(g=>g.id),n.current=i.isSettled,i)},[e]);return useSyncExternalStore(u,o,o)}function be(e){assertSystem("useHistory",e);let t=useRef(null),r=useCallback(n=>e.onHistoryChange(n),[e]),s=useCallback(()=>{let n=buildHistoryState(e);return n?(t.current&&t.current.canGoBack===n.canGoBack&&t.current.canGoForward===n.canGoForward&&t.current.currentIndex===n.currentIndex&&t.current.totalSnapshots===n.totalSnapshots&&t.current.isPaused===n.isPaused||(t.current=n),t.current):null},[e]);return useSyncExternalStore(r,s,s)}function $e(e,t){return Array.isArray(t)?ke(e,t):xe(e,t)}function xe(e,t){let r=useRef(x),s=useCallback(u=>e.subscribe(u),[e]),n=useCallback(()=>{let u=e.getStatus(t);if(r.current!==x){let o=r.current;if(o.pending===u.pending&&o.inflight===u.inflight&&o.failed===u.failed&&o.isLoading===u.isLoading&&o.hasError===u.hasError&&o.lastError===u.lastError)return r.current}return r.current=u,u},[e,t]);return useSyncExternalStore(s,n,n)}function ke(e,t){let r=useRef(null),s=useRef(""),n=useCallback(o=>e.subscribe(o),[e]),u=useCallback(()=>{let o={},i=[];for(let a of t){let c=e.getStatus(a);o[a]=c,i.push(`${a}:${c.pending}:${c.inflight}:${c.failed}:${c.hasError}:${c.lastError?.message??""}`);}let f=i.join("|");return f!==s.current&&(s.current=f,r.current=o),r.current??o},[e,...t]);return useSyncExternalStore(n,u,u)}var _=new WeakMap;function te(e){let t=_.get(e);return t||(t=new Map,_.set(e,t)),t}function qe(e,t){return Array.isArray(t)?Ie(e,t):De(e,t)}function De(e,t){let r=e.getStatus(t);if(r.hasError&&r.lastError)throw r.lastError;if(r.isLoading){let s=te(e),n=s.get(t);throw n||(n=new Promise(u=>{let o=e.subscribe(()=>{e.getStatus(t).isLoading||(s.delete(t),o(),u());});}),s.set(t,n)),n}return r}function Ie(e,t){let r={},s=false,n=null;for(let u of t){let o=e.getStatus(u);r[u]=o,o.hasError&&o.lastError&&!n&&(n=o.lastError),o.isLoading&&(s=true);}if(n)throw n;if(s){let u=te(e),o=t.slice().sort().join(","),i=u.get(o);throw i||(i=new Promise(f=>{let a=e.subscribe(()=>{t.every(g=>!e.getStatus(g).isLoading)&&(u.delete(o),a(),f());});}),u.set(o,i)),i}return r}function H(e,t){let r=useRef(null),s=useRef(null),n=useRef(null),u=t?.status===true,o="modules"in e;return r.current||(n.current=()=>{if(o){let{modules:E,...I}=e,C=t?.plugins??I.plugins??[],S=t?.history??I.history,p=t?.trace??I.trace,R=t?.errorBoundary??I.errorBoundary,w=t?.tickMs??I.tickMs,M=t?.zeroConfig??I.zeroConfig,T=t?.initialFacts??I.initialFacts,q=createSystem({modules:E,plugins:C.length>0?C:void 0,history:S,trace:p,errorBoundary:R,tickMs:w,zeroConfig:M,initialFacts:T});return q.initialize(),typeof window<"u"&&q.start(),q}let i="id"in e&&"schema"in e,f=i?e:e.module,a=i?{}:e,c=t?.plugins??a.plugins??[],g=t?.history??a.history,y=t?.trace??a.trace,F=t?.errorBoundary??a.errorBoundary,v=t?.tickMs??a.tickMs,k=t?.zeroConfig??a.zeroConfig,D=t?.initialFacts??a.initialFacts,m=[...c];u&&(s.current=createRequirementStatusPlugin(),m=[...m,s.current.plugin]);let P=createSystem({module:f,plugins:m.length>0?m:void 0,history:g,trace:y,errorBoundary:F,tickMs:v,zeroConfig:k,initialFacts:D});return P.initialize(),typeof window<"u"&&P.start(),P},r.current=n.current()),useEffect(()=>(!r.current&&n.current&&(r.current=n.current()),()=>{r.current?.destroy(),r.current=null,s.current=null;}),[]),u&&!o?{system:r.current,statusPlugin:s.current}:r.current}function Oe(e,t,r){let s=useRef(t);s.current=t;let n=useRef(r);n.current=r;let u=useCallback(i=>e.subscribe(s.current,i),[e]),o=useCallback(()=>n.current(e),[e]);return useSyncExternalStore(u,o,o)}function Be(e,t={}){let{facts:r,derived:s,status:n,...u}=t,o=r??[],i=s??[],f=o.length===0&&i.length===0,a=n?H(e,{status:true,...u}):H(e,u),c=n?a.system:a,g=n?a.statusPlugin:void 0,y=useMemo(()=>f?Object.keys(c.derive):[],[c,f]),F=useCallback(S=>{let p=[];return f?(p.push(c.facts.$store.subscribeAll(S)),y.length>0&&p.push(c.subscribe(y,S))):(o.length>0&&p.push(c.facts.$store.subscribe(o,S)),i.length>0&&p.push(c.subscribe(i,S))),()=>{for(let R of p)R();}},[c,f,...o,...i,...y]),v=useRef(x),k=useRef(x),D=useRef(null),m=useCallback(()=>{let S,p,R,w;if(f){S=c.facts.$store.toObject(),R=Object.keys(S),p={};for(let b of y)p[b]=c.read(b);w=y;}else {S={};for(let b of o)S[b]=c.facts[b];R=o,p={};for(let b of i)p[b]=c.read(b);w=i;}let M=v.current!==x;if(M){let b=v.current;if(Object.keys(b).length!==R.length)M=false;else for(let O of R)if(!Object.is(b[O],S[O])){M=false;break}}let T=k.current!==x;if(T){let b=k.current;if(Object.keys(b).length!==w.length)T=false;else for(let O of w)if(!Object.is(b[O],p[O])){T=false;break}}let q=M?v.current:S,se=T?k.current:p;return M||(v.current=S),T||(k.current=p),M&&T&&D.current||(D.current={facts:q,derived:se}),D.current},[c,f,...o,...i,...y]),P=useSyncExternalStore(F,m,m),E=useCallback(S=>c.dispatch(S),[c]),I=A(c),C={system:c,dispatch:E,events:I,facts:P.facts,derived:P.derived};return n&&g?{...C,statusPlugin:g}:C}function A(e){return assertSystem("useEvents",e),useMemo(()=>e.events,[e])}function we(e,t){assertSystem("useExplain",e);let r=useCallback(n=>{let u=e.facts.$store.subscribeAll(n),o=e.onSettledChange(n);return ()=>{u(),o();}},[e]),s=useCallback(()=>e.explain(t),[e,t]);return useSyncExternalStore(r,s,s)}function Ne(e,t){assertSystem("useConstraintStatus",e);let r=ee(e);return useMemo(()=>{let s=e.inspect();return t?s.constraints.find(n=>n.id===t)??null:s.constraints},[e,t,r])}function We(e,t,r){assertSystem("useOptimisticUpdate",e);let[s,n]=useState(false),[u,o]=useState(null),i=useRef(null),f=useCallback(()=>{i.current&&(e.restore(i.current),i.current=null),n(false),o(null);},[e]),a=useCallback(c=>{i.current=e.getSnapshot(),n(true),o(null),e.batch(c);},[e]);return useEffect(()=>{if(!(!t||!r||!s))return t.subscribe(()=>{let c=t.getStatus(r);!c.isLoading&&!c.hasError?(i.current=null,n(false)):c.hasError&&(o(c.lastError),f());})},[t,r,s,f]),{mutate:a,isPending:s,error:u,rollback:f}}var ne=createContext(null);function He({snapshot:e,children:t}){return jsx(ne.Provider,{value:e,children:t})}function Ae(e,t){let r=useContext(ne),s=useMemo(()=>{let n=mergeHydrationFacts(r,t?.initialFacts);return {...t??{},initialFacts:n}},[r,t]);return H(e,s)}function Le(){return {useFact:(e,t)=>G(e,t),useDerived:(e,t)=>J(e,t),useDispatch:e=>X(e),useEvents:e=>A(e),useWatch:(e,t,r)=>Y(e,t,r)}}var B=null;function Ke(){if(!B)try{B=ue("@directive-run/query").createQuerySystem;}catch{throw new Error("[Directive] @directive-run/query is not installed. Install it with: pnpm add @directive-run/query")}return B}function je(e){let t=useRef(e),r=useMemo(()=>{let u=Ke();return ()=>u(t.current)},[]),s=useRef(null),n=useRef(r);return n.current=r,s.current||(s.current=n.current()),useEffect(()=>(!s.current&&n.current&&(s.current=n.current()),typeof window<"u"&&s.current&&!s.current.isRunning&&s.current.start(),()=>{s.current?.destroy(),s.current=null;}),[]),s.current}var N=new WeakMap;function _e(e,t){let r=useCallback(o=>e.subscribe([t],o),[e,t]),s=useCallback(()=>e.read(t),[e,t]),n=useSyncExternalStore(r,s,s);N.has(e)||N.set(e,new Map);let u=N.get(e);if(n?.status==="success"&&n?.data!==null)return u.has(t)&&(u.get(t).resolve(),u.delete(t)),n.data;if(n?.status==="error"&&n?.error)throw u.has(t)&&(u.get(t).resolve(),u.delete(t)),n.error;if(!u.has(t)){let o,i=new Promise(a=>{o=a;});u.set(t,{promise:i,resolve:o});let f=e.subscribe([t],()=>{let a=e.read(t);if(a?.status==="success"||a?.status==="error"){let c=u.get(t);c&&(c.resolve(),u.delete(t)),f();}});}throw u.get(t).promise}function ze(e){let t=createContext(null);function r(){let n=useContext(t);if(!n)throw new Error("[Directive] useSystem called outside of <Provider>. Wrap your component tree with the Provider from createDirectiveContext().");return n}function s({children:n,system:u}){return jsx(t.Provider,{value:u??e,children:n})}return s.displayName="DirectiveProvider",{Provider:s,useSystem:r,useFact:n=>G(r(),n),useDerived:n=>J(r(),n),useEvents:()=>A(r()),useDispatch:()=>X(r()),useSelector:(n,u)=>ve(r(),n,u),useWatch:(n,u)=>Y(r(),n,u),useTickWhile:(n,u,o)=>me(r(),n,u,o),useInspect:()=>ee(r()),useExplain:n=>we(r(),n),useHistory:()=>be(r())}}export{He as DirectiveHydrator,ze as createDirectiveContext,Le as createTypedHooks,Ne as useConstraintStatus,J as useDerived,Be as useDirective,H as useDirectiveRef,X as useDispatch,A as useEvents,we as useExplain,G as useFact,be as useHistory,Ae as useHydratedSystem,ee as useInspect,Oe as useNamespacedSelector,We as useOptimisticUpdate,je as useQuerySystem,$e as useRequirementStatus,ve as useSelector,_e as useSuspenseQuery,qe as useSuspenseRequirement,me as useTickWhile,Y as useWatch};//# sourceMappingURL=index.js.map
1
+ import {createSystem,createRequirementStatusPlugin}from'@directive-run/core';import {assertSystem,defaultEquality,runTrackedSelector,createThrottle,buildHistoryState,mergeHydrationFacts,depsChanged,computeInspectState}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {createContext,useCallback,useSyncExternalStore,useRef,useMemo,useEffect,useState,useContext}from'react';import {jsx}from'react/jsx-runtime';var ue=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var k=Symbol("directive.uninitialized");function A(e,t){return assertSystem("useFact",e),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)?pe(e,t):Se(e,t)}function Se(e,t){(t in e.facts.$store.toObject()||console.warn(`[Directive] useFact("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`));let r=useCallback(n=>e.facts.$store.subscribe([t],n),[e,t]),s=useCallback(()=>e.facts.$store.get(t),[e,t]);return useSyncExternalStore(r,s,s)}function pe(e,t){let r=useRef(k),s=useCallback(u=>e.facts.$store.subscribe(t,u),[e,...t]),n=useCallback(()=>{let u={};for(let o of t)u[o]=e.facts.$store.get(o);if(r.current!==k){let o=true;for(let i of t)if(!Object.is(r.current[i],u[i])){o=false;break}if(o)return r.current}return r.current=u,u},[e,...t]);return useSyncExternalStore(s,n,n)}function $e(e,t,r){assertSystem("useFactWithDefault",e);let s=useRef(null);(s.current===null||s.current.system!==e)&&(s.current={system:e,value:r()});let n=A(e,t);return n??s.current.value}function J(e,t){return assertSystem("useDerived",e),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)?ye(e,t):ge(e,t)}function ge(e,t){(t in e.derive||console.warn(`[Directive] useDerived("${t}") \u2014 derivation not found. Check that "${t}" is defined in your module's derive property.`));let r=useCallback(n=>e.subscribe([t],n),[e,t]),s=useCallback(()=>e.read(t),[e,t]);return useSyncExternalStore(r,s,s)}function ye(e,t){let r=useRef(k),s=useCallback(u=>e.subscribe(t,u),[e,...t]),n=useCallback(()=>{let u={};for(let o of t)u[o]=e.read(o);if(r.current!==k){let o=true;for(let i of t)if(!Object.is(r.current[i],u[i])){o=false;break}if(o)return r.current}return r.current=u,u},[e,...t]);return useSyncExternalStore(s,n,n)}function ve(e,t,r,s){if(e&&e._mode==="namespaced")return Me(e,t,r,s);let n=e,u,o=false,i=s??defaultEquality;r!==void 0&&(u=r,o=true),!n&&!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 f=useRef(t),a=useRef(i),c=useRef(u),g=useRef(t),y=useRef(0);g.current!==t&&(g.current=t,y.current++),f.current=t,a.current=i,c.current=u;let F=y.current,v=useRef([]),x=useRef([]),I=useRef(k),m=useRef([]),P=useMemo(()=>n?new Set(Object.keys(n.derive)):new Set,[n]),E=useCallback(()=>n?runTrackedSelector(n,P,f.current):{value:c.current,factKeys:[],deriveKeys:[]},[n,P]),w=useCallback(S=>{if(!n)return ()=>{};let p=()=>{for(let M of m.current)M();m.current=[];let{factKeys:R,deriveKeys:K}=E();v.current=R,x.current=K,R.length>0?m.current.push(n.facts.$store.subscribe(R,()=>{let M=E();depsChanged(v.current,M.factKeys,x.current,M.deriveKeys)&&p(),S();})):K.length===0&&m.current.push(n.facts.$store.subscribeAll(S)),K.length>0&&m.current.push(n.subscribe(K,()=>{let M=E();depsChanged(v.current,M.factKeys,x.current,M.deriveKeys)&&p(),S();}));};return p(),()=>{for(let R of m.current)R();m.current=[];}},[n,E,F]),C=useCallback(()=>{let S;if(!n)S=c.current;else {let{value:p}=E();S=p===void 0&&o?c.current:p;}return I.current!==k&&a.current(I.current,S)?I.current:(I.current=S,S)},[E,n,o]);return useSyncExternalStore(w,C,C)}function Me(e,t,r,s){let n=r!==void 0,u=s??defaultEquality,o=useRef(t),i=useRef(u),f=useRef(r);o.current=t,i.current=u,f.current=r;let a=useRef(k),c=useMemo(()=>Object.keys(e.facts),[e]),g=useCallback(F=>{let v=c.map(x=>`${x}.*`);return e.subscribe(v,F)},[e,c]),y=useCallback(()=>{let F=o.current(e),v=F===void 0&&n?f.current:F;return a.current!==k&&i.current(a.current,v)?a.current:(a.current=v,v)},[e,n]);return useSyncExternalStore(g,y,y)}function X(e){return assertSystem("useDispatch",e),useCallback(t=>{e.dispatch(t);},[e])}function Y(e,t,r){assertSystem("useWatch",e);let s=useRef(r);s.current=r,useEffect(()=>e.watch(t,(n,u)=>{s.current(n,u);}),[e,t]);}function me(e,t,r,s){assertSystem("useTickWhile",e);let n=useRef(t);n.current=t;let u=useCallback(f=>{let a=e.facts.$store.subscribeAll(f),c=e.onSettledChange(f);return ()=>{a(),c();}},[e]),o=useCallback(()=>n.current(e),[e]),i=useSyncExternalStore(u,o,o);useEffect(()=>{if(!i)return;if(!Number.isFinite(s)||s<=0){console.warn(`[Directive] useTickWhile() received non-positive intervalMs: ${s}. Interval will not fire.`);return}let f=setInterval(()=>{let c=e.events[r];typeof c=="function"?c():console.warn(`[Directive] useTickWhile() \u2014 event "${String(r)}" not found on system.events.`);},s);return ()=>clearInterval(f)},[i,e,r,s]);}function ee(e,t){assertSystem("useInspect",e);let r=Re(e),s=t?.throttleMs,[n,u]=useState(r),o=useRef(null);return useEffect(()=>{if(!s||s<=0){o.current?.cleanup(),o.current=null;return}return o.current?.cleanup(),o.current=createThrottle((...i)=>{u(i[0]);},s),()=>{o.current?.cleanup(),o.current=null;}},[s]),useEffect(()=>{o.current&&o.current.throttled(r);},[r]),!s||s<=0?r:n}function he(e){return computeInspectState(e)}function Re(e){let t=useRef(null),r=useRef([]),s=useRef([]),n=useRef(null),u=useCallback(i=>{let f=e.facts.$store.subscribeAll(i),a=e.onSettledChange(i);return ()=>{f(),a();}},[e]),o=useCallback(()=>{let i=he(e),f=i.unmet.length===r.current.length&&i.unmet.every((g,y)=>g.id===r.current[y]),a=i.inflight.length===s.current.length&&i.inflight.every((g,y)=>g.id===s.current[y]),c=i.isSettled===n.current;return f&&a&&c&&t.current?t.current:(t.current=i,r.current=i.unmet.map(g=>g.id),s.current=i.inflight.map(g=>g.id),n.current=i.isSettled,i)},[e]);return useSyncExternalStore(u,o,o)}function be(e){assertSystem("useHistory",e);let t=useRef(null),r=useCallback(n=>e.onHistoryChange(n),[e]),s=useCallback(()=>{let n=buildHistoryState(e);return n?(t.current&&t.current.canGoBack===n.canGoBack&&t.current.canGoForward===n.canGoForward&&t.current.currentIndex===n.currentIndex&&t.current.totalSnapshots===n.totalSnapshots&&t.current.isPaused===n.isPaused||(t.current=n),t.current):null},[e]);return useSyncExternalStore(r,s,s)}function qe(e,t){return Array.isArray(t)?xe(e,t):ke(e,t)}function ke(e,t){let r=useRef(k),s=useCallback(u=>e.subscribe(u),[e]),n=useCallback(()=>{let u=e.getStatus(t);if(r.current!==k){let o=r.current;if(o.pending===u.pending&&o.inflight===u.inflight&&o.failed===u.failed&&o.isLoading===u.isLoading&&o.hasError===u.hasError&&o.lastError===u.lastError)return r.current}return r.current=u,u},[e,t]);return useSyncExternalStore(s,n,n)}function xe(e,t){let r=useRef(null),s=useRef(""),n=useCallback(o=>e.subscribe(o),[e]),u=useCallback(()=>{let o={},i=[];for(let a of t){let c=e.getStatus(a);o[a]=c,i.push(`${a}:${c.pending}:${c.inflight}:${c.failed}:${c.hasError}:${c.lastError?.message??""}`);}let f=i.join("|");return f!==s.current&&(s.current=f,r.current=o),r.current??o},[e,...t]);return useSyncExternalStore(n,u,u)}var z=new WeakMap;function te(e){let t=z.get(e);return t||(t=new Map,z.set(e,t)),t}function Ne(e,t){return Array.isArray(t)?Ie(e,t):De(e,t)}function De(e,t){let r=e.getStatus(t);if(r.hasError&&r.lastError)throw r.lastError;if(r.isLoading){let s=te(e),n=s.get(t);throw n||(n=new Promise(u=>{let o=e.subscribe(()=>{e.getStatus(t).isLoading||(s.delete(t),o(),u());});}),s.set(t,n)),n}return r}function Ie(e,t){let r={},s=false,n=null;for(let u of t){let o=e.getStatus(u);r[u]=o,o.hasError&&o.lastError&&!n&&(n=o.lastError),o.isLoading&&(s=true);}if(n)throw n;if(s){let u=te(e),o=t.slice().sort().join(","),i=u.get(o);throw i||(i=new Promise(f=>{let a=e.subscribe(()=>{t.every(g=>!e.getStatus(g).isLoading)&&(u.delete(o),a(),f());});}),u.set(o,i)),i}return r}function H(e,t){let r=useRef(null),s=useRef(null),n=useRef(null),u=t?.status===true,o="modules"in e;return r.current||(n.current=()=>{if(o){let{modules:E,...w}=e,C=t?.plugins??w.plugins??[],S=t?.history??w.history,p=t?.trace??w.trace,R=t?.errorBoundary??w.errorBoundary,K=t?.tickMs??w.tickMs,M=t?.zeroConfig??w.zeroConfig,T=t?.initialFacts??w.initialFacts,q=createSystem({modules:E,plugins:C.length>0?C:void 0,history:S,trace:p,errorBoundary:R,tickMs:K,zeroConfig:M,initialFacts:T});return q.initialize(),typeof window<"u"&&q.start(),q}let i="id"in e&&"schema"in e,f=i?e:e.module,a=i?{}:e,c=t?.plugins??a.plugins??[],g=t?.history??a.history,y=t?.trace??a.trace,F=t?.errorBoundary??a.errorBoundary,v=t?.tickMs??a.tickMs,x=t?.zeroConfig??a.zeroConfig,I=t?.initialFacts??a.initialFacts,m=[...c];u&&(s.current=createRequirementStatusPlugin(),m=[...m,s.current.plugin]);let P=createSystem({module:f,plugins:m.length>0?m:void 0,history:g,trace:y,errorBoundary:F,tickMs:v,zeroConfig:x,initialFacts:I});return P.initialize(),typeof window<"u"&&P.start(),P},r.current=n.current()),useEffect(()=>(!r.current&&n.current&&(r.current=n.current()),()=>{r.current?.destroy(),r.current=null,s.current=null;}),[]),u&&!o?{system:r.current,statusPlugin:s.current}:r.current}function Oe(e,t,r){let s=useRef(t);s.current=t;let n=useRef(r);n.current=r;let u=useCallback(i=>e.subscribe(s.current,i),[e]),o=useCallback(()=>n.current(e),[e]);return useSyncExternalStore(u,o,o)}function We(e,t={}){let{facts:r,derived:s,status:n,...u}=t,o=r??[],i=s??[],f=o.length===0&&i.length===0,a=n?H(e,{status:true,...u}):H(e,u),c=n?a.system:a,g=n?a.statusPlugin:void 0,y=useMemo(()=>f?Object.keys(c.derive):[],[c,f]),F=useCallback(S=>{let p=[];return f?(p.push(c.facts.$store.subscribeAll(S)),y.length>0&&p.push(c.subscribe(y,S))):(o.length>0&&p.push(c.facts.$store.subscribe(o,S)),i.length>0&&p.push(c.subscribe(i,S))),()=>{for(let R of p)R();}},[c,f,...o,...i,...y]),v=useRef(k),x=useRef(k),I=useRef(null),m=useCallback(()=>{let S,p,R,K;if(f){S=c.facts.$store.toObject(),R=Object.keys(S),p={};for(let b of y)p[b]=c.read(b);K=y;}else {S={};for(let b of o)S[b]=c.facts[b];R=o,p={};for(let b of i)p[b]=c.read(b);K=i;}let M=v.current!==k;if(M){let b=v.current;if(Object.keys(b).length!==R.length)M=false;else for(let N of R)if(!Object.is(b[N],S[N])){M=false;break}}let T=x.current!==k;if(T){let b=x.current;if(Object.keys(b).length!==K.length)T=false;else for(let N of K)if(!Object.is(b[N],p[N])){T=false;break}}let q=M?v.current:S,se=T?x.current:p;return M||(v.current=S),T||(x.current=p),M&&T&&I.current||(I.current={facts:q,derived:se}),I.current},[c,f,...o,...i,...y]),P=useSyncExternalStore(F,m,m),E=useCallback(S=>c.dispatch(S),[c]),w=L(c),C={system:c,dispatch:E,events:w,facts:P.facts,derived:P.derived};return n&&g?{...C,statusPlugin:g}:C}function L(e){return assertSystem("useEvents",e),useMemo(()=>e.events,[e])}function we(e,t){assertSystem("useExplain",e);let r=useCallback(n=>{let u=e.facts.$store.subscribeAll(n),o=e.onSettledChange(n);return ()=>{u(),o();}},[e]),s=useCallback(()=>e.explain(t),[e,t]);return useSyncExternalStore(r,s,s)}function Be(e,t){assertSystem("useConstraintStatus",e);let r=ee(e);return useMemo(()=>{let s=e.inspect();return t?s.constraints.find(n=>n.id===t)??null:s.constraints},[e,t,r])}function He(e,t,r){assertSystem("useOptimisticUpdate",e);let[s,n]=useState(false),[u,o]=useState(null),i=useRef(null),f=useCallback(()=>{i.current&&(e.restore(i.current),i.current=null),n(false),o(null);},[e]),a=useCallback(c=>{i.current=e.getSnapshot(),n(true),o(null),e.batch(c);},[e]);return useEffect(()=>{if(!(!t||!r||!s))return t.subscribe(()=>{let c=t.getStatus(r);!c.isLoading&&!c.hasError?(i.current=null,n(false)):c.hasError&&(o(c.lastError),f());})},[t,r,s,f]),{mutate:a,isPending:s,error:u,rollback:f}}var ne=createContext(null);function Ae({snapshot:e,children:t}){return jsx(ne.Provider,{value:e,children:t})}function Le(e,t){let r=useContext(ne),s=useMemo(()=>{let n=mergeHydrationFacts(r,t?.initialFacts);return {...t??{},initialFacts:n}},[r,t]);return H(e,s)}function je(){return {useFact:(e,t)=>A(e,t),useDerived:(e,t)=>J(e,t),useDispatch:e=>X(e),useEvents:e=>L(e),useWatch:(e,t,r)=>Y(e,t,r)}}var O=null;function Ke(){if(!O)try{O=ue("@directive-run/query").createQuerySystem;}catch{throw new Error("[Directive] @directive-run/query is not installed. Install it with: pnpm add @directive-run/query")}return O}function _e(e){let t=useRef(e),r=useMemo(()=>{let u=Ke();return ()=>u(t.current)},[]),s=useRef(null),n=useRef(r);return n.current=r,s.current||(s.current=n.current()),useEffect(()=>(!s.current&&n.current&&(s.current=n.current()),typeof window<"u"&&s.current&&!s.current.isRunning&&s.current.start(),()=>{s.current?.destroy(),s.current=null;}),[]),s.current}var W=new WeakMap;function ze(e,t){let r=useCallback(o=>e.subscribe([t],o),[e,t]),s=useCallback(()=>e.read(t),[e,t]),n=useSyncExternalStore(r,s,s);W.has(e)||W.set(e,new Map);let u=W.get(e);if(n?.status==="success"&&n?.data!==null)return u.has(t)&&(u.get(t).resolve(),u.delete(t)),n.data;if(n?.status==="error"&&n?.error)throw u.has(t)&&(u.get(t).resolve(),u.delete(t)),n.error;if(!u.has(t)){let o,i=new Promise(a=>{o=a;});u.set(t,{promise:i,resolve:o});let f=e.subscribe([t],()=>{let a=e.read(t);if(a?.status==="success"||a?.status==="error"){let c=u.get(t);c&&(c.resolve(),u.delete(t)),f();}});}throw u.get(t).promise}function Qe(e){let t=createContext(null);function r(){let n=useContext(t);if(!n)throw new Error("[Directive] useSystem called outside of <Provider>. Wrap your component tree with the Provider from createDirectiveContext().");return n}function s({children:n,system:u}){return jsx(t.Provider,{value:u??e,children:n})}return s.displayName="DirectiveProvider",{Provider:s,useSystem:r,useFact:n=>A(r(),n),useDerived:n=>J(r(),n),useEvents:()=>L(r()),useDispatch:()=>X(r()),useSelector:(n,u)=>ve(r(),n,u),useWatch:(n,u)=>Y(r(),n,u),useTickWhile:(n,u,o)=>me(r(),n,u,o),useInspect:()=>ee(r()),useExplain:n=>we(r(),n),useHistory:()=>be(r())}}export{Ae as DirectiveHydrator,Qe as createDirectiveContext,je as createTypedHooks,Be as useConstraintStatus,J as useDerived,We as useDirective,H as useDirectiveRef,X as useDispatch,L as useEvents,we as useExplain,A as useFact,$e as useFactWithDefault,be as useHistory,Le as useHydratedSystem,ee as useInspect,Oe as useNamespacedSelector,He as useOptimisticUpdate,_e as useQuerySystem,qe as useRequirementStatus,ve as useSelector,ze as useSuspenseQuery,Ne as useSuspenseRequirement,me as useTickWhile,Y as useWatch};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map