@directive-run/react 1.20.1 → 1.21.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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dev-true.ts","../src/index.tsx"],"names":["dev_true_default","useAuditLedger","ledger","filter","opts","requestedPollMs","pollMs","entryCount","tick","setTick","useState","useEffect","id","t","useMemo","UNINITIALIZED","useFact","system","keyOrKeys","assertSystem","_useFacts","_useSingleFact","factKey","subscribe","useCallback","onStoreChange","getSnapshot","useSyncExternalStore","factKeys","cachedValue","useRef","result","key","same","useFactWithDefault","factory","cacheRef","value","useDerived","_useDerivedMulti","_useSingleDerived","derivationId","derivationIds","useSelector","systemArg","selector","defaultValueArg","equalityFnArg","_useNamespacedSelectorImpl","defaultValue","hasDefault","equalityFn","defaultEquality","selectorRef","eqRef","defaultValueRef","prevSelectorRef","selectorVersionRef","selectorVersion","trackedFactKeysRef","trackedDeriveKeysRef","unsubsRef","deriveKeys","runWithTracking","runTrackedSelector","resubscribe","unsub","derivedKeys","updated","depsChanged","effectiveValue","newValue","moduleNames","wildcardKeys","ns","useDispatch","event","useWatch","callback","callbackRef","prevValue","useTickWhile","predicate","eventName","intervalMs","predicateRef","unsubFacts","unsubSettled","active","fn","useInspect","options","syncState","_useInspectSync","throttleMs","deferredState","setDeferredState","throttleRef","createThrottle","args","_buildInspectState","computeInspectState","cachedSnapshot","cachedUnmetIds","cachedInflightIds","cachedIsSettled","state","unmetSame","u","i","inflightSame","f","settledSame","useHistory","cachedRef","buildHistoryState","useRequirementStatus","statusPlugin","typeOrTypes","_useRequirementStatusMulti","_useRequirementStatusSingle","type","status","prev","types","cachedKey","parts","suspenseCacheMap","getSuspenseCache","plugin","cache","useSuspenseRequirement","_useSuspenseRequirementMulti","_useSuspenseRequirementSingle","promise","resolve","unsubscribe","hasLoading","firstError","cacheKey","useDirectiveRef","config","systemRef","statusPluginRef","factoryRef","wantStatus","isNamespaced","modules","rest","plugins","history","trace","errorBoundary","tickMs","zeroConfig","initialFacts","sys","createSystem","isModule","mod","baseOpts","allPlugins","createRequirementStatusPlugin","useNamespacedSelector","keys","keysRef","useDirective","moduleOrOptions","selections","factKeysOpt","derivedKeysOpt","configRest","subscribeAll","refResult","allDerivationKeys","unsubs","cachedFacts","cachedDerived","cachedWrapper","factsResult","derivedResult","effectiveFactKeys","effectiveDerivedKeys","factsSame","derivedSame","stableFacts","stableDerived","values","dispatch","events","useEvents","base","useExplain","requirementId","useConstraintStatus","constraintId","inspectState","inspection","c","useOptimisticUpdate","requirementType","isPending","setIsPending","error","setError","snapshotRef","rollback","mutate","updateFn","HydrationContext","createContext","DirectiveHydrator","snapshot","children","jsx","useHydratedSystem","moduleDef","useContext","mergedConfig","mergedFacts","mergeHydrationFacts","createTypedHooks","_createQuerySystem","getCreateQuerySystem","useQuerySystem","configRef","createQuerySystem","suspensePromiseCache","useSuspenseQuery","queryName","resolvePromise","entry","createDirectiveContext","Ctx","useSystem","Provider","overrideSystem"],"mappings":"4sBAAA,IAAOA,CAAAA,CAAQ,OAAO,OAAA,CAAY,KAChC,OAAA,CAAQ,GAAA,EAAK,QAAA,GAAa,YAAA,CCgHrB,SAASC,EAAAA,CACdC,CAAAA,CACAC,CAAAA,CAAsB,EAAC,CACvBC,EAA4B,EAAC,CACN,CACvB,IAAMC,CAAAA,CAAkBD,CAAAA,CAAK,QAAU,GAAA,CACjCE,CAAAA,CAAS,IAAA,CAAK,GAAA,CAAI,EAAA,CAAID,CAAe,EAE3C,GAAIL,CAAAA,GACEI,CAAAA,CAAK,MAAA,GAAW,MAAA,EAAaA,CAAAA,CAAK,OAAS,EAAA,EAC7C,OAAA,CAAQ,IAAA,CACN,CAAA,oCAAA,EAAuCA,CAAAA,CAAK,MAAM,8CACpD,CAAA,CAEEE,CAAAA,CAAS,GAAA,CAAA,CAAK,CAChB,IAAMC,CAAAA,CAAaL,EAAO,MAAA,EAAO,CAAE,OAAA,CA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production\";\n","/**\n * React Adapter - Consolidated hooks for React integration\n *\n * 20 public exports: useFact, useDerived, useDispatch, useDirective,\n * useDirectiveRef, useSelector, useWatch, useTickWhile, useInspect,\n * useRequirementStatus, useSuspenseRequirement, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, DirectiveHydrator,\n * useHydratedSystem, useHistory, createTypedHooks, shallowEqual\n *\n * @example\n * ```tsx\n * import { useFact, useDerived, useEvents } from '@directive-run/react';\n *\n * const system = createSystem({ module: counterModule });\n * system.start();\n *\n * function Counter() {\n * const count = useFact(system, \"count\");\n * const doubled = useDerived(system, \"doubled\");\n * const events = useEvents(system);\n *\n * return (\n * <div>\n * <p>Count: {count}</p>\n * <p>Doubled: {doubled}</p>\n * <button onClick={() => events.increment()}>+</button>\n * </div>\n * );\n * }\n * ```\n */\n\nimport type {\n DistributableSnapshot,\n ErrorBoundaryConfig,\n HistoryOption,\n HistoryState,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemSnapshot,\n TraceOption,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n mergeHydrationFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport type { ReactNode } from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport isDevelopment from \"#is-development\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n// ============================================================================\n// useAuditLedger — live ledger entries with filter (R4.I + Ship 4)\n// ============================================================================\n\nimport type { AuditEntry, AuditLedger, QueryFilter } from \"@directive-run/core\";\n\n/**\n * Subscribe to an audit ledger and return the latest entries matching\n * `filter`. Re-renders whenever a new matching entry lands.\n *\n * @example\n * ```tsx\n * const entries = useAuditLedger(ledger, { kind: \"constraint.evaluate\", limit: 20 });\n * return (\n * <ul>\n * {entries.map(e => <li key={e.seq}>{e.kind} @ {new Date(e.ts).toISOString()}</li>)}\n * </ul>\n * );\n * ```\n *\n * The hook polls via a small interval (default 250 ms) because the\n * v1 ledger sink doesn't expose a pub/sub channel. Override with\n * `pollMs` if you need higher fidelity (e.g. 50ms for a live demo).\n *\n * **Polling floor:** `pollMs` is clamped to a minimum of 50 ms to prevent\n * accidental DoS from typos like `pollMs: 5`. Values below the floor are\n * silently clamped in production; dev mode logs a warning.\n */\nexport function useAuditLedger(\n ledger: AuditLedger,\n filter: QueryFilter = {},\n opts: { pollMs?: number } = {},\n): readonly AuditEntry[] {\n const requestedPollMs = opts.pollMs ?? 250;\n const pollMs = Math.max(50, requestedPollMs);\n\n if (isDevelopment) {\n if (opts.pollMs !== undefined && opts.pollMs < 50) {\n console.warn(\n `[Directive] useAuditLedger() pollMs=${opts.pollMs} is below the 50 ms floor; clamped to 50 ms.`,\n );\n }\n if (pollMs < 100) {\n const entryCount = ledger.toJSON().entries.length;\n if (entryCount > 1000) {\n console.warn(\n `[Directive] useAuditLedger() polling every ${pollMs} ms against a ${entryCount}-entry ledger — that's a lot of CPU per tick. Consider raising pollMs or tightening the filter.`,\n );\n }\n }\n }\n\n const [tick, setTick] = useState(0);\n\n useEffect(() => {\n const id = setInterval(() => setTick((t) => t + 1), pollMs);\n\n return () => clearInterval(id);\n }, [pollMs]);\n\n // Re-query on every tick — cheap O(N) walk against the in-memory ring.\n // `tick` is the dep; `filter` is captured by closure (caller passes the\n // same object identity unless they intend a refresh).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => ledger.query(filter), [ledger, tick, filter]);\n}\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/** Sentinel value for uninitialized selector cache */\nconst UNINITIALIZED = Symbol(\"directive.uninitialized\");\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;\n\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;\n\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useFact\", system);\n if (isDevelopment && typeof keyOrKeys === \"function\") {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFacts(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return _useSingleFact(system, keyOrKeys);\n}\n\nfunction _useSingleFact(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKey: string,\n): unknown {\n if (isDevelopment) {\n if (!(factKey in system.facts.$store.toObject())) {\n console.warn(\n `[Directive] useFact(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe([factKey], onStoreChange);\n },\n [system, factKey],\n );\n\n const getSnapshot = useCallback(() => {\n return system.facts.$store.get(factKey as never);\n }, [system, factKey]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useFacts(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe(factKeys, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...factKeys],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key as never);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const key of factKeys) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[key],\n result[key],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...factKeys]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useFactWithDefault — stable-identity nullable-fact fallback (RFC-2)\n// ============================================================================\n\n/**\n * Read a fact, falling back to a lazily-computed default with **stable\n * referential identity** when the fact is `null`/`undefined`.\n *\n * **Why this exists:** the natural pattern\n *\n * ```tsx\n * const markedCells = useFact(sys, \"markedCells\") ?? deps.initializeMarkedCells();\n * ```\n *\n * calls `initializeMarkedCells()` on every render where `markedCells` is\n * `null`, producing a fresh array/object identity each time. Anything\n * downstream that memoizes on that identity (`useMemo` deps,\n * `React.memo`, virtualized list keys) re-runs unnecessarily and can\n * trigger re-render storms.\n *\n * `useFactWithDefault` runs `factory` at most once per system instance and\n * caches the result in a ref. While the fact is `null`/`undefined`, every\n * render returns the same cached value. When the fact transitions to a\n * non-null value, that value is returned instead. If the fact later\n * returns to `null`, the originally-cached factory result is reused\n * (the factory is **not** called again).\n *\n * Swapping the `system` argument re-runs the factory on the new system.\n *\n * @example\n * ```tsx\n * const markedCells = useFactWithDefault(\n * sys,\n * \"markedCells\",\n * () => deps.initializeMarkedCells(),\n * );\n * // `markedCells` has stable identity across renders while the fact is null.\n * ```\n *\n * @param system - The system to read the fact from.\n * @param factKey - The fact key.\n * @param factory - Lazy default factory; runs at most once per system instance.\n * @returns The fact value when non-null, otherwise the cached factory result.\n */\nexport function useFactWithDefault<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKey: K,\n factory: () => NonNullable<InferFacts<S>[K]>,\n): NonNullable<InferFacts<S>[K]>;\n\n/** Implementation */\nexport function useFactWithDefault(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n factKey: string,\n factory: () => unknown,\n): unknown {\n assertSystem(\"useFactWithDefault\", system);\n\n // Track factory result keyed by system identity. When the consumer swaps\n // the system, we deliberately re-run the factory on the new instance —\n // a fresh system has a fresh default.\n const cacheRef = useRef<{ system: unknown; value: unknown } | null>(null);\n if (cacheRef.current === null || cacheRef.current.system !== system) {\n cacheRef.current = { system, value: factory() };\n }\n\n const value = useFact(system, factKey);\n if (value === null || value === undefined) {\n return cacheRef.current.value;\n }\n return value;\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];\n\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Pick<InferDerivations<S>, K>;\n\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useDerived\", system);\n if (isDevelopment && typeof keyOrKeys === \"function\") {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(keyOrKeys)) {\n return _useDerivedMulti(system, keyOrKeys);\n }\n\n // Single key path\n return _useSingleDerived(system, keyOrKeys);\n}\n\nfunction _useSingleDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationId: string,\n): unknown {\n if (isDevelopment) {\n if (!(derivationId in system.derive)) {\n console.warn(\n `[Directive] useDerived(\"${derivationId}\") — derivation not found. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe([derivationId], onStoreChange);\n },\n [system, derivationId],\n );\n\n const getSnapshot = useCallback(() => {\n return system.read(derivationId);\n }, [system, derivationId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useDerivedMulti(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe(derivationIds, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...derivationIds],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const id of derivationIds) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[id],\n result[id],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...derivationIds]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSelector — Zustand-style selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations (Zustand-style).\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys. Falls back to subscribeAll\n * if no keys are detected.\n *\n * Supports an optional default value as the 3rd parameter, used when\n * the system is null/undefined or the selector returns undefined.\n * When a default value is provided, the system parameter may be\n * null | undefined — the hook returns the default and recomputes\n * when the system becomes available.\n *\n * An optional equality function can be passed as the 4th parameter\n * to customize when the selector result is considered \"changed\".\n * Defaults to `Object.is`. Use `shallowEqual` (exported from this\n * package) when your selector returns a new object/array each time.\n *\n * @example\n * ```tsx\n * // Basic usage\n * const count = useSelector(system, (s) => s.count);\n *\n * // With default value (allows nullable system)\n * const count = useSelector(system, (s) => s.count, 0);\n *\n * // With default value + custom equality\n * const coords = useSelector(system, (s) => ({ x: s.x, y: s.y }), { x: 0, y: 0 }, shallowEqual);\n * ```\n */\n\n// Non-null system, no default\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n): R;\n\n// Non-null system, with default value and optional equality\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable system, default REQUIRED\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S> | null | undefined,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Namespaced system overloads ---\n\n// Namespaced system, no default\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n): R;\n\n// Namespaced system, with default value and optional equality\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable namespaced system, default REQUIRED\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules> | null | undefined,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Generic fallbacks ---\n\n// Generic fallback: non-null system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue?: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Generic fallback: nullable system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature accepts both system types\n systemArg: SingleModuleSystem<any> | NamespacedSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n // Route to namespaced implementation if system is a NamespacedSystem\n // biome-ignore lint/suspicious/noExplicitAny: Runtime type check\n if (systemArg && (systemArg as any)._mode === \"namespaced\") {\n // biome-ignore lint/suspicious/noExplicitAny: Delegate to namespaced impl\n return _useNamespacedSelectorImpl(\n systemArg as NamespacedSystem<any>,\n selector,\n defaultValueArg,\n equalityFnArg,\n );\n }\n\n // After the namespaced check, system is a SingleModuleSystem\n const system = systemArg as SingleModuleSystem<any> | null | undefined;\n let defaultValue: unknown;\n let hasDefault = false;\n const equalityFn: (a: unknown, b: unknown) => boolean =\n equalityFnArg ?? defaultEquality;\n\n if (defaultValueArg !== undefined) {\n defaultValue = defaultValueArg;\n hasDefault = true;\n }\n\n // Dev-mode warning: null system without a default value\n if (isDevelopment) {\n if (!system && !hasDefault) {\n console.error(\n \"[Directive] useSelector() received a null/undefined system without a default value. \" +\n \"Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)\",\n );\n }\n }\n\n // Store selector/eq/default in refs to avoid resubscription churn\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValue);\n // Track selector identity changes to force resubscription when deps may shift\n const prevSelectorRef = useRef(selector);\n const selectorVersionRef = useRef(0);\n if (prevSelectorRef.current !== selector) {\n prevSelectorRef.current = selector;\n selectorVersionRef.current++;\n }\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValue;\n\n const selectorVersion = selectorVersionRef.current;\n const trackedFactKeysRef = useRef<string[]>([]);\n const trackedDeriveKeysRef = useRef<string[]>([]);\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n const unsubsRef = useRef<Array<() => void>>([]);\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const deriveKeys = useMemo(\n () => (system ? new Set(Object.keys(system.derive)) : new Set<string>()),\n [system],\n );\n\n const runWithTracking = useCallback(() => {\n if (!system) {\n return {\n value: defaultValueRef.current,\n factKeys: [] as string[],\n deriveKeys: [] as string[],\n };\n }\n\n return runTrackedSelector(system, deriveKeys, selectorRef.current);\n }, [system, deriveKeys]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!system) {\n // No system — return noop unsubscribe\n return () => {};\n }\n\n const resubscribe = () => {\n // Cleanup previous subscriptions\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n\n // Run selector with tracking to detect accessed keys\n const { factKeys, deriveKeys: derivedKeys } = runWithTracking();\n trackedFactKeysRef.current = factKeys;\n trackedDeriveKeysRef.current = derivedKeys;\n\n // Subscribe to accessed fact keys\n if (factKeys.length > 0) {\n unsubsRef.current.push(\n system.facts.$store.subscribe(factKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n } else if (derivedKeys.length === 0) {\n // No deps at all — subscribe to everything\n unsubsRef.current.push(\n system.facts.$store.subscribeAll(onStoreChange),\n );\n }\n\n // Subscribe to accessed derivation keys\n if (derivedKeys.length > 0) {\n unsubsRef.current.push(\n system.subscribe(derivedKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- selectorVersion forces resubscription when selector deps change\n [system, runWithTracking, selectorVersion],\n );\n\n const getSnapshot = useCallback(() => {\n let effectiveValue: unknown;\n\n if (!system) {\n effectiveValue = defaultValueRef.current;\n } else {\n const { value: newValue } = runWithTracking();\n\n // When selector returns undefined and we have a default, use it\n effectiveValue =\n newValue === undefined && hasDefault\n ? defaultValueRef.current\n : newValue;\n }\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [runWithTracking, system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// _useNamespacedSelectorImpl — internal namespaced useSelector\n// ============================================================================\n\n/**\n * Internal implementation for useSelector with NamespacedSystem.\n * Subscribes to all module namespaces and runs the selector against the system.\n * Uses equality comparison to prevent unnecessary re-renders.\n */\nfunction _useNamespacedSelectorImpl(\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n system: NamespacedSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n const hasDefault = defaultValueArg !== undefined;\n const equalityFn = equalityFnArg ?? defaultEquality;\n\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValueArg);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValueArg;\n\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n\n // Get all module namespace names for wildcard subscription\n const moduleNames = useMemo(() => Object.keys(system.facts), [system]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n // Subscribe to all modules using wildcard keys\n const wildcardKeys = moduleNames.map((ns) => `${ns}.*`);\n\n return system.subscribe(wildcardKeys, onStoreChange);\n },\n [system, moduleNames],\n );\n\n const getSnapshot = useCallback(() => {\n const newValue = selectorRef.current(system);\n const effectiveValue =\n newValue === undefined && hasDefault ? defaultValueRef.current : newValue;\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return useCallback(\n (event: InferEvents<S>) => {\n system.dispatch(event);\n },\n [system],\n );\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect (no re-render)\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n prevValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n prevValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n callback: (newValue: any, prevValue: any) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n useEffect(() => {\n return system.watch(key, (newValue, prevValue) => {\n callbackRef.current(newValue, prevValue);\n });\n }, [system, key]);\n}\n\n// ============================================================================\n// useTickWhile — interval-driven event dispatch gated by predicate\n// ============================================================================\n\n/**\n * Fires a system event on a recurring interval while a predicate returns true.\n *\n * Replaces the verbatim `setInterval(() => sys.events.TICK(), ms)` /\n * `clearInterval` pattern that appears across components driving status-gated\n * polling, animation, or timer flows. The hook subscribes to all fact and\n * settled-state changes so the predicate is re-evaluated whenever the system\n * mutates; when it flips to true, an interval starts; when it flips to false,\n * the interval is cleared. Cleans up on unmount.\n *\n * @example\n * ```tsx\n * useTickWhile(\n * system,\n * (sys) => sys.facts.status === \"running\",\n * \"TICK\",\n * 1000,\n * );\n * ```\n */\nexport function useTickWhile<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n predicate: (system: SingleModuleSystem<S>) => boolean,\n eventName: keyof S[\"events\"] & string,\n intervalMs: number,\n): void {\n assertSystem(\"useTickWhile\", system);\n\n const predicateRef = useRef(predicate);\n predicateRef.current = predicate;\n\n // Track latest active state via a useState + subscription. We need React to\n // re-render the hook (or rather re-run the effect) whenever the predicate's\n // result flips, so we cache the result and broadcast change to listeners.\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n return predicateRef.current(system);\n }, [system]);\n\n const active = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n useEffect(() => {\n if (!active) return;\n if (!Number.isFinite(intervalMs) || intervalMs <= 0) {\n if (isDevelopment) {\n console.warn(\n `[Directive] useTickWhile() received non-positive intervalMs: ${intervalMs}. Interval will not fire.`,\n );\n }\n return;\n }\n\n const id = setInterval(() => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic event dispatch\n const evts = system.events as Record<string, (...args: any[]) => void>;\n const fn = evts[eventName as string];\n if (typeof fn === \"function\") {\n fn();\n } else if (isDevelopment) {\n console.warn(\n `[Directive] useTickWhile() — event \"${String(eventName)}\" not found on system.events.`,\n );\n }\n }, intervalMs);\n\n return () => clearInterval(id);\n }, [active, system, eventName, intervalMs]);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n// InspectState is imported from ./shared.js and re-exported above\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n /** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */\n throttleMs?: number;\n}\n\n/**\n * Hook to get consolidated system inspection data reactively.\n *\n * Merges isSettled, unmet/inflight requirements, and working state\n * into a single subscription. Optionally throttle updates.\n *\n * @example\n * ```tsx\n * const { isSettled, isWorking, hasUnmet } = useInspect(system);\n * const throttled = useInspect(system, { throttleMs: 200 });\n * ```\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): InspectState {\n assertSystem(\"useInspect\", system);\n // Always call the sync version (useSyncExternalStore path) — no conditional hooks\n const syncState = _useInspectSync(system);\n\n const throttleMs = options?.throttleMs;\n const [deferredState, setDeferredState] = useState(syncState);\n const throttleRef = useRef<{\n throttled: (...args: unknown[]) => void;\n cleanup: () => void;\n } | null>(null);\n\n // Create/recreate throttle when throttleMs changes\n useEffect(() => {\n if (!throttleMs || throttleMs <= 0) {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n return;\n }\n // Clean up old throttle before creating new one\n throttleRef.current?.cleanup();\n throttleRef.current = createThrottle((...args: unknown[]) => {\n setDeferredState(args[0] as InspectState);\n }, throttleMs);\n return () => {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n };\n }, [throttleMs]);\n\n // Feed sync state through throttle after each render\n useEffect(() => {\n if (throttleRef.current) {\n throttleRef.current.throttled(syncState);\n }\n }, [syncState]);\n\n if (!throttleMs || throttleMs <= 0) return syncState;\n return deferredState;\n}\n\nfunction _buildInspectState(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n return computeInspectState(system);\n}\n\nfunction _useInspectSync(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n const cachedSnapshot = useRef<InspectState | null>(null);\n const cachedUnmetIds = useRef<string[]>([]);\n const cachedInflightIds = useRef<string[]>([]);\n const cachedIsSettled = useRef<boolean | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = _buildInspectState(system);\n\n const unmetSame =\n state.unmet.length === cachedUnmetIds.current.length &&\n state.unmet.every((u, i) => u.id === cachedUnmetIds.current[i]);\n const inflightSame =\n state.inflight.length === cachedInflightIds.current.length &&\n state.inflight.every((f, i) => f.id === cachedInflightIds.current[i]);\n const settledSame = state.isSettled === cachedIsSettled.current;\n\n if (unmetSame && inflightSame && settledSame && cachedSnapshot.current) {\n return cachedSnapshot.current;\n }\n\n cachedSnapshot.current = state;\n cachedUnmetIds.current = state.unmet.map((u) => u.id);\n cachedInflightIds.current = state.inflight.map((f) => f.id);\n cachedIsSettled.current = state.isSettled;\n\n return state;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useHistory — reactive history state\n// ============================================================================\n\n/**\n * Reactive history hook. Returns null when history is disabled.\n * Re-renders when snapshots are taken or navigation occurs.\n *\n * @example\n * ```tsx\n * const history = useHistory(system);\n * if (history) {\n * return (\n * <div>\n * <button disabled={!history.canGoBack} onClick={() => history.goBack()}>Undo</button>\n * <button disabled={!history.canGoForward} onClick={() => history.goForward()}>Redo</button>\n * <span>{history.currentIndex + 1} / {history.totalSnapshots}</span>\n * </div>\n * );\n * }\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): HistoryState | null {\n assertSystem(\"useHistory\", system);\n const cachedRef = useRef<HistoryState | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => system.onHistoryChange(onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = buildHistoryState(system);\n if (!state) return null;\n\n // Return stable reference when values haven't changed\n if (\n cachedRef.current &&\n cachedRef.current.canGoBack === state.canGoBack &&\n cachedRef.current.canGoForward === state.canGoForward &&\n cachedRef.current.currentIndex === state.currentIndex &&\n cachedRef.current.totalSnapshots === state.totalSnapshots &&\n cachedRef.current.isPaused === state.isPaused\n ) {\n return cachedRef.current;\n }\n\n cachedRef.current = state;\n return cachedRef.current;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useRequirementStatusMulti(statusPlugin, typeOrTypes);\n }\n return _useRequirementStatusSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useRequirementStatusSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const cachedRef = useRef<RequirementTypeStatus | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const status = statusPlugin.getStatus(type);\n\n if (cachedRef.current !== UNINITIALIZED) {\n const prev = cachedRef.current;\n if (\n prev.pending === status.pending &&\n prev.inflight === status.inflight &&\n prev.failed === status.failed &&\n prev.isLoading === status.isLoading &&\n prev.hasError === status.hasError &&\n prev.lastError === status.lastError\n ) {\n return cachedRef.current;\n }\n }\n\n cachedRef.current = status;\n return status;\n }, [statusPlugin, type]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useRequirementStatusMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const cachedRef = useRef<Record<string, RequirementTypeStatus> | null>(null);\n const cachedKey = useRef<string>(\"\");\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, RequirementTypeStatus> = {};\n const parts: string[] = [];\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n parts.push(\n `${type}:${status.pending}:${status.inflight}:${status.failed}:${status.hasError}:${status.lastError?.message ?? \"\"}`,\n );\n }\n const key = parts.join(\"|\");\n\n if (key !== cachedKey.current) {\n cachedKey.current = key;\n cachedRef.current = result;\n }\n\n return cachedRef.current ?? result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [statusPlugin, ...types]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSuspenseRequirement — single or multi\n// ============================================================================\n\n// Cache for pending promises, scoped per statusPlugin to prevent cross-system leaks.\nconst suspenseCacheMap = new WeakMap<\n StatusPlugin,\n Map<string, Promise<void>>\n>();\n\nfunction getSuspenseCache(plugin: StatusPlugin): Map<string, Promise<void>> {\n let cache = suspenseCacheMap.get(plugin);\n if (!cache) {\n cache = new Map();\n suspenseCacheMap.set(plugin, cache);\n }\n return cache;\n}\n\n/** Single type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useSuspenseRequirementMulti(statusPlugin, typeOrTypes);\n }\n return _useSuspenseRequirementSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useSuspenseRequirementSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const status = statusPlugin.getStatus(type);\n\n if (status.hasError && status.lastError) {\n throw status.lastError;\n }\n\n if (status.isLoading) {\n const cache = getSuspenseCache(statusPlugin);\n let promise = cache.get(type);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const currentStatus = statusPlugin.getStatus(type);\n if (!currentStatus.isLoading) {\n cache.delete(type);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(type, promise);\n }\n\n throw promise;\n }\n\n return status;\n}\n\nfunction _useSuspenseRequirementMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const result: Record<string, RequirementTypeStatus> = {};\n let hasLoading = false;\n let firstError: Error | null = null;\n\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n\n if (status.hasError && status.lastError && !firstError) {\n firstError = status.lastError;\n }\n if (status.isLoading) {\n hasLoading = true;\n }\n }\n\n if (firstError) {\n throw firstError;\n }\n\n if (hasLoading) {\n const cache = getSuspenseCache(statusPlugin);\n const cacheKey = types.slice().sort().join(\",\");\n let promise = cache.get(cacheKey);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const allDone = types.every(\n (t) => !statusPlugin.getStatus(t).isLoading,\n );\n if (allDone) {\n cache.delete(cacheKey);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(cacheKey, promise);\n }\n\n throw promise;\n }\n\n return result;\n}\n\n// ============================================================================\n// useDirectiveRef — scoped system lifecycle\n// ============================================================================\n\n/** Base options for creating a scoped system */\ninterface DirectiveRefBaseConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n history?: HistoryOption;\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n}\n\n/** Options for useDirectiveRef: module directly, or config object */\nexport type UseDirectiveRefOptions<M extends ModuleSchema> =\n | ModuleDef<M>\n | (DirectiveRefBaseConfig & { module: ModuleDef<M> });\n\n/** Options for useDirectiveRef with namespaced modules */\nexport type UseDirectiveRefNamespacedOptions<Modules extends ModulesMap> =\n DirectiveRefBaseConfig & { modules: { [K in keyof Modules]: Modules[K] } };\n\n// --- Single-module overloads ---\n\n/** Without status (no config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n): SingleModuleSystem<M>;\n\n/** Without status (with config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: DirectiveRefBaseConfig,\n): SingleModuleSystem<M>;\n\n/** With status: returns { system, statusPlugin } */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: { status: true } & DirectiveRefBaseConfig,\n): { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin };\n\n// --- Namespaced (multi-module) overloads ---\n\n/** Namespaced: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n): NamespacedSystem<Modules>;\n\n/** Namespaced with config: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n config: DirectiveRefBaseConfig,\n): NamespacedSystem<Modules>;\n\n/** Implementation */\nexport function useDirectiveRef(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature handles both modes\n options: any,\n config?: { status?: boolean } & DirectiveRefBaseConfig,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation return varies by overload\n): any {\n // biome-ignore lint/suspicious/noExplicitAny: System ref holds either system type\n const systemRef = useRef<any>(null);\n const statusPluginRef = useRef<StatusPlugin | null>(null);\n // Factory ref for strict mode re-creation (effects unmount then re-mount)\n // biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\n const factoryRef = useRef<(() => any) | null>(null);\n const wantStatus = config?.status === true;\n const isNamespaced = \"modules\" in options;\n\n if (!systemRef.current) {\n // Build a factory that creates + starts the system.\n // Called once during render and again on strict-mode re-mount.\n factoryRef.current = () => {\n if (isNamespaced) {\n // --- Namespaced mode: { modules: { ... } } ---\n const { modules, ...rest } = options;\n const plugins = config?.plugins ?? rest.plugins ?? [];\n const history = config?.history ?? rest.history;\n const trace = config?.trace ?? rest.trace;\n const errorBoundary = config?.errorBoundary ?? rest.errorBoundary;\n const tickMs = config?.tickMs ?? rest.tickMs;\n const zeroConfig = config?.zeroConfig ?? rest.zeroConfig;\n const initialFacts = config?.initialFacts ?? rest.initialFacts;\n\n const sys = createSystem({\n modules,\n plugins: plugins.length > 0 ? plugins : undefined,\n history,\n trace,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n }\n\n // --- Single-module mode ---\n const isModule = \"id\" in options && \"schema\" in options;\n const mod = isModule ? options : options.module;\n const baseOpts = isModule ? {} : (options as DirectiveRefBaseConfig);\n const plugins = config?.plugins ?? baseOpts.plugins ?? [];\n const history = config?.history ?? baseOpts.history;\n const trace = config?.trace ?? baseOpts.trace;\n const errorBoundary = config?.errorBoundary ?? baseOpts.errorBoundary;\n const tickMs = config?.tickMs ?? baseOpts.tickMs;\n const zeroConfig = config?.zeroConfig ?? baseOpts.zeroConfig;\n const initialFacts = config?.initialFacts ?? baseOpts.initialFacts;\n\n let allPlugins = [...plugins];\n\n if (wantStatus) {\n statusPluginRef.current = createRequirementStatusPlugin();\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins = [\n ...allPlugins,\n statusPluginRef.current.plugin as Plugin<any>,\n ];\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const sys = createSystem({\n module: mod,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n history,\n trace,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n };\n\n // Start synchronously so facts are initialized before the first render\n systemRef.current = factoryRef.current();\n }\n\n useEffect(() => {\n // Strict mode re-mount: system was destroyed in cleanup, recreate it\n if (!systemRef.current && factoryRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n return () => {\n // RFC 0009 follow-up (R18 Tier 2-B): destroyAsync so source\n // unsubscribes complete; fire-and-forget with swallow-catch\n // (React's effect cleanup is sync).\n systemRef.current?.destroyAsync().catch(() => {});\n systemRef.current = null;\n statusPluginRef.current = null;\n };\n }, []);\n\n if (wantStatus && !isNamespaced) {\n return {\n system: systemRef.current!,\n statusPlugin: statusPluginRef.current!,\n };\n }\n\n return systemRef.current!;\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem with useSyncExternalStore\n// ============================================================================\n\n/**\n * React hook to select derived values from a NamespacedSystem.\n * Uses useSyncExternalStore for tear-free reads.\n *\n * @param system - The namespaced system to read from\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```tsx\n * const system = useDirectiveRef({ modules: { auth, data } });\n * const token = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * const count = useNamespacedSelector(system, [\"data.*\"], (s) => s.derive.data.total);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): R {\n const keysRef = useRef(keys);\n keysRef.current = keys;\n const selectorRef = useRef(selector);\n selectorRef.current = selector;\n\n const subscribe = useCallback(\n (onStoreChange: () => void) =>\n system.subscribe(keysRef.current, onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => selectorRef.current(system), [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDirective — scoped system with selected values in containers\n// ============================================================================\n\n/** Options for useDirective hook */\nexport interface UseDirectiveOptions<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n> extends DirectiveRefBaseConfig {\n /** Fact keys to subscribe to */\n facts?: FK[];\n /** Derivation keys to subscribe to */\n derived?: DK[];\n /** Enable status plugin */\n status?: boolean;\n}\n\n/** Return type for useDirective hook (without status) */\nexport type UseDirectiveReturn<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = {\n system: SingleModuleSystem<S>;\n dispatch: (event: InferEvents<S>) => void;\n events: SingleModuleSystem<S>[\"events\"];\n facts: Pick<InferFacts<S>, FK>;\n derived: Pick<InferDerivations<S>, DK>;\n};\n\n/** Return type for useDirective hook (with status) */\nexport type UseDirectiveReturnWithStatus<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = UseDirectiveReturn<S, FK, DK> & {\n statusPlugin: StatusPlugin;\n};\n\n/**\n * Convenience hook that creates a scoped system and reads selected facts/derivations\n * into container objects. When no `facts` or `derived` keys are specified, subscribes\n * to ALL facts and derivations (replacing the former `useModule` hook).\n *\n * @example\n * ```tsx\n * // Selective subscription\n * const { dispatch, facts: { count }, derived: { doubled } } = useDirective(counterModule, {\n * facts: [\"count\"],\n * derived: [\"doubled\"],\n * });\n *\n * // Subscribe to everything (no keys = all facts + all derivations)\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n * ```\n */\nexport function useDirective<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n>(\n moduleOrOptions: UseDirectiveRefOptions<S>,\n selections: UseDirectiveOptions<S, FK, DK> = {} as UseDirectiveOptions<\n S,\n FK,\n DK\n >,\n): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK> {\n const {\n facts: factKeysOpt,\n derived: derivedKeysOpt,\n status,\n ...configRest\n } = selections;\n const factKeys = (factKeysOpt ?? []) as FK[];\n const derivedKeys = (derivedKeysOpt ?? []) as DK[];\n\n // When no keys are specified, subscribe to everything\n const subscribeAll = factKeys.length === 0 && derivedKeys.length === 0;\n\n // Create system via useDirectiveRef (handles lifecycle)\n // biome-ignore lint/suspicious/noExplicitAny: Conditional overload dispatch\n const refResult: any = status\n ? useDirectiveRef(moduleOrOptions, { status: true as const, ...configRest })\n : useDirectiveRef(moduleOrOptions, configRest);\n\n const system: SingleModuleSystem<S> = status ? refResult.system : refResult;\n\n const statusPlugin = status\n ? (\n refResult as {\n system: SingleModuleSystem<S>;\n statusPlugin: StatusPlugin;\n }\n ).statusPlugin\n : undefined;\n\n // For subscribe-all mode, get all derivation keys\n const allDerivationKeys = useMemo(\n () => (subscribeAll ? Object.keys(system.derive) : []),\n [system, subscribeAll],\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubs: Array<() => void> = [];\n if (subscribeAll) {\n // Subscribe to ALL facts and ALL derivations\n unsubs.push(system.facts.$store.subscribeAll(onStoreChange));\n if (allDerivationKeys.length > 0) {\n unsubs.push(system.subscribe(allDerivationKeys, onStoreChange));\n }\n } else {\n if (factKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(factKeys, onStoreChange));\n }\n if (derivedKeys.length > 0) {\n unsubs.push(system.subscribe(derivedKeys, onStoreChange));\n }\n }\n return () => {\n for (const unsub of unsubs) unsub();\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys],\n );\n\n const cachedFacts = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedDerived = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedWrapper = useRef<{\n facts: Record<string, unknown>;\n derived: Record<string, unknown>;\n } | null>(null);\n\n const getSnapshot = useCallback(() => {\n let factsResult: Record<string, unknown>;\n let derivedResult: Record<string, unknown>;\n let effectiveFactKeys: readonly string[];\n let effectiveDerivedKeys: readonly string[];\n\n if (subscribeAll) {\n // Read ALL facts and ALL derivations\n factsResult = system.facts.$store.toObject();\n effectiveFactKeys = Object.keys(factsResult);\n derivedResult = {};\n for (const key of allDerivationKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = allDerivationKeys;\n } else {\n // Read selected keys only\n factsResult = {};\n for (const key of factKeys) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n factsResult[key] = (system.facts as any)[key];\n }\n effectiveFactKeys = factKeys;\n derivedResult = {};\n for (const key of derivedKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = derivedKeys;\n }\n\n // Check facts stability\n let factsSame = cachedFacts.current !== UNINITIALIZED;\n if (factsSame) {\n const prev = cachedFacts.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveFactKeys.length) {\n factsSame = false;\n } else {\n for (const key of effectiveFactKeys) {\n if (!Object.is(prev[key], factsResult[key])) {\n factsSame = false;\n break;\n }\n }\n }\n }\n\n // Check derived stability\n let derivedSame = cachedDerived.current !== UNINITIALIZED;\n if (derivedSame) {\n const prev = cachedDerived.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveDerivedKeys.length) {\n derivedSame = false;\n } else {\n for (const key of effectiveDerivedKeys) {\n if (!Object.is(prev[key], derivedResult[key])) {\n derivedSame = false;\n break;\n }\n }\n }\n }\n\n const stableFacts = factsSame\n ? (cachedFacts.current as Record<string, unknown>)\n : factsResult;\n const stableDerived = derivedSame\n ? (cachedDerived.current as Record<string, unknown>)\n : derivedResult;\n\n if (!factsSame) cachedFacts.current = factsResult;\n if (!derivedSame) cachedDerived.current = derivedResult;\n\n // Return same wrapper reference when both containers are unchanged\n if (factsSame && derivedSame && cachedWrapper.current) {\n return cachedWrapper.current;\n }\n\n cachedWrapper.current = { facts: stableFacts, derived: stableDerived };\n return cachedWrapper.current;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys]);\n\n const values = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const dispatch = useCallback(\n (event: InferEvents<S>) => system.dispatch(event),\n [system],\n );\n\n const events = useEvents(system);\n\n const base = {\n system,\n dispatch,\n events,\n facts: values.facts as Pick<InferFacts<S>, FK>,\n derived: values.derived as Pick<InferDerivations<S>, DK>,\n };\n\n if (status && statusPlugin) {\n return { ...base, statusPlugin } as UseDirectiveReturnWithStatus<S, FK, DK>;\n }\n\n return base as UseDirectiveReturn<S, FK, DK>;\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher. Provides autocomplete for event names\n * and avoids needing useCallback wrappers for event dispatch.\n *\n * @example\n * ```tsx\n * const events = useEvents(system);\n * <button onClick={() => events.increment()}>+</button>\n * ```\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return useMemo(() => system.events, [system]);\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n * Updates whenever system state changes.\n *\n * @example\n * ```tsx\n * const explanation = useExplain(system, \"req-123\");\n * if (explanation) <pre>{explanation}</pre>;\n * ```\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): string | null {\n assertSystem(\"useExplain\", system);\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n return system.explain(requirementId);\n }, [system, requirementId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n// ConstraintInfo is imported from ./shared.js and re-exported above\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): ConstraintInfo[];\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): ConstraintInfo | null;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n assertSystem(\"useConstraintStatus\", system);\n const inspectState = useInspect(system);\n\n return useMemo(() => {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return inspection.constraints.find((c) => c.id === constraintId) ?? null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, constraintId, inspectState]);\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\n/** Result of useOptimisticUpdate */\nexport interface OptimisticUpdateResult {\n /** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */\n mutate: (updateFn: () => void) => void;\n /** Whether a resolver is currently processing the optimistic change */\n isPending: boolean;\n /** Error if the resolver failed */\n error: Error | null;\n /** Manually rollback to the pre-mutation snapshot */\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n *\n * @example\n * ```tsx\n * const { mutate, isPending, error, rollback } = useOptimisticUpdate(\n * system, statusPlugin, \"SAVE_ITEM\"\n * );\n * mutate(() => { system.facts.items = [...system.facts.items, newItem]; });\n * ```\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const snapshotRef = useRef<SystemSnapshot | null>(null);\n\n const rollback = useCallback(() => {\n if (snapshotRef.current) {\n system.restore(snapshotRef.current);\n snapshotRef.current = null;\n }\n setIsPending(false);\n setError(null);\n }, [system]);\n\n const mutate = useCallback(\n (updateFn: () => void) => {\n snapshotRef.current = system.getSnapshot();\n setIsPending(true);\n setError(null);\n system.batch(updateFn);\n },\n [system],\n );\n\n // Watch for resolver completion/failure\n useEffect(() => {\n if (!statusPlugin || !requirementType || !isPending) return;\n\n return statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n // Resolved successfully — keep optimistic state\n snapshotRef.current = null;\n setIsPending(false);\n } else if (status.hasError) {\n // Failed — rollback\n setError(status.lastError);\n rollback();\n }\n });\n }, [statusPlugin, requirementType, isPending, rollback]);\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// DirectiveHydrator + useHydratedSystem — SSR/RSC hydration\n// ============================================================================\n\n/** Props for DirectiveHydrator component */\nexport interface HydratorProps {\n snapshot: DistributableSnapshot;\n children: ReactNode;\n}\n\n/** Context for hydrated snapshot */\nconst HydrationContext = createContext<DistributableSnapshot | null>(null);\n\n/**\n * SSR/RSC hydration component. Wraps children with a snapshot context\n * that `useHydratedSystem` can consume on the client.\n *\n * @example\n * ```tsx\n * // Server component\n * <DirectiveHydrator snapshot={serverSnapshot}>\n * <ClientApp />\n * </DirectiveHydrator>\n * ```\n */\nexport function DirectiveHydrator({ snapshot, children }: HydratorProps) {\n return (\n <HydrationContext.Provider value={snapshot}>\n {children}\n </HydrationContext.Provider>\n );\n}\n\n/**\n * Client-side hook that creates a system hydrated from a server snapshot.\n * Must be used inside a `<DirectiveHydrator>`.\n *\n * @example\n * ```tsx\n * function ClientApp() {\n * const system = useHydratedSystem(counterModule);\n * const count = useFact(system, \"count\");\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useHydratedSystem<S extends ModuleSchema>(\n moduleDef: ModuleDef<S>,\n config?: DirectiveRefBaseConfig,\n): SingleModuleSystem<S> {\n const snapshot = useContext(HydrationContext);\n\n // Merge snapshot data as initial facts via shared adapter utility\n const mergedConfig = useMemo(() => {\n const mergedFacts = mergeHydrationFacts(snapshot, config?.initialFacts);\n\n return {\n ...(config ?? {}),\n initialFacts: mergedFacts,\n };\n }, [snapshot, config]);\n\n return useDirectiveRef(moduleDef, mergedConfig) as SingleModuleSystem<S>;\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\n/**\n * Creates pre-typed versions of the core hooks for a specific module schema.\n * Eliminates the need to pass type parameters on every hook call.\n *\n * @example\n * ```tsx\n * const { useFact, useDerived, useDispatch, useEvents, useWatch } = createTypedHooks<typeof counterModule.schema>();\n *\n * // No type parameters needed — schema is baked in\n * function Counter({ system }: { system: SingleModuleSystem<CounterSchema> }) {\n * const count = useFact(system, \"count\");\n * const doubled = useDerived(system, \"doubled\");\n * const dispatch = useDispatch(system);\n * }\n * ```\n */\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => InferFacts<M>[K] | undefined;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => InferDerivations<M>[K];\n useDispatch: (\n system: SingleModuleSystem<M>,\n ) => (event: InferEvents<M>) => void;\n useEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>[\"events\"];\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) => void;\n} {\n return {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for internal call\n useFact(system as SingleModuleSystem<any>, factKey) as\n | InferFacts<M>[K]\n | undefined,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for internal call\n useDerived(\n system as SingleModuleSystem<any>,\n derivationId,\n ) as InferDerivations<M>[K],\n useDispatch: (system: SingleModuleSystem<M>) => useDispatch<M>(system),\n useEvents: (system: SingleModuleSystem<M>) => useEvents<M>(system),\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for internal call\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useQuerySystem — Stable query system with lifecycle management\n// ============================================================================\n\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nlet _createQuerySystem: ((config: Record<string, unknown>) => any) | null =\n null;\n\nfunction getCreateQuerySystem() {\n if (!_createQuerySystem) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@directive-run/query\");\n _createQuerySystem = mod.createQuerySystem;\n } catch {\n throw new Error(\n \"[Directive] @directive-run/query is not installed. \" +\n \"Install it with: pnpm add @directive-run/query\",\n );\n }\n }\n\n return _createQuerySystem!;\n}\n\n/**\n * React hook to create and manage a query system with proper lifecycle.\n *\n * Accepts either a config object or a factory function:\n * - Config object: calls `createQuerySystem` from `@directive-run/query` automatically\n * - Factory function: calls the factory to create the system (for custom setups)\n *\n * Creates the system once, starts on mount, destroys on unmount.\n * Handles Strict Mode re-creation and SSR safety.\n *\n * @example\n * ```tsx\n * import { useQuerySystem, useDerived } from \"@directive-run/react\";\n *\n * function App() {\n * const app = useQuerySystem({\n * facts: { userId: \"\" },\n * queries: {\n * user: {\n * key: (f) => f.userId ? { userId: f.userId } : null,\n * fetcher: async (p, signal) => {\n * const res = await fetch(`/api/users/${p.userId}`, { signal });\n * return res.json();\n * },\n * },\n * },\n * });\n *\n * const user = useDerived(app, \"user\");\n *\n * return <div>{user.data?.name}</div>;\n * }\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: System type varies based on config\nexport function useQuerySystem<\n T extends {\n start: () => void;\n destroy: () => void;\n isRunning?: boolean;\n [key: string]: any;\n },\n>(config: Record<string, unknown>): T {\n const configRef = useRef(config);\n\n const factory = useMemo(() => {\n const createQuerySystem = getCreateQuerySystem();\n\n return () => {\n return createQuerySystem(configRef.current) as T;\n };\n }, []);\n\n const systemRef = useRef<T | null>(null);\n const factoryRef = useRef(factory);\n factoryRef.current = factory;\n\n if (!systemRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n useEffect(() => {\n // Strict mode re-mount: system was destroyed in cleanup, recreate\n if (!systemRef.current && factoryRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n // Start on mount (SSR safety: only start in browser)\n if (\n typeof window !== \"undefined\" &&\n systemRef.current &&\n !systemRef.current.isRunning\n ) {\n systemRef.current.start();\n }\n\n return () => {\n // RFC 0009 follow-up (R18 Tier 2-B): destroyAsync so source\n // unsubscribes complete; fire-and-forget with swallow-catch.\n systemRef.current?.destroyAsync().catch(() => {});\n systemRef.current = null;\n };\n }, []);\n\n return systemRef.current!;\n}\n\n// ============================================================================\n// useSuspenseQuery — Suspense + Error Boundary integration for queries\n// ============================================================================\n\n// Cache of pending promises per system+key to ensure stable references across renders\nconst suspensePromiseCache = new WeakMap<\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n any,\n Map<string, { promise: Promise<void>; resolve: () => void }>\n>();\n\n/**\n * React hook for reading query data with Suspense support.\n *\n * Throws a Promise while the query is pending (triggers Suspense fallback).\n * Throws the error if the query fails (triggers error boundary).\n * Returns the data directly when available – no isPending/isError checks needed.\n *\n * @example\n * ```tsx\n * import { useSuspenseQuery } from \"@directive-run/react\";\n *\n * function UserProfile({ system }) {\n * const user = useSuspenseQuery(system, \"user\");\n * return <h1>{user.name}</h1>;\n * }\n *\n * <Suspense fallback={<Spinner />}>\n * <ErrorBoundary>\n * <UserProfile system={system} />\n * </ErrorBoundary>\n * </Suspense>\n * ```\n */\nexport function useSuspenseQuery<T = unknown>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n queryName: string,\n): T {\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe([queryName], onStoreChange);\n },\n [system, queryName],\n );\n\n const getSnapshot = useCallback(() => {\n return system.read(queryName);\n }, [system, queryName]);\n\n // biome-ignore lint/suspicious/noExplicitAny: ResourceState shape checked at runtime\n const state = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getSnapshot,\n ) as any;\n\n // Get or create the promise cache for this system\n if (!suspensePromiseCache.has(system)) {\n suspensePromiseCache.set(system, new Map());\n }\n const cache = suspensePromiseCache.get(system)!;\n\n // Success – clean up promise cache and return data directly\n if (state?.status === \"success\" && state?.data !== null) {\n if (cache.has(queryName)) {\n const entry = cache.get(queryName)!;\n entry.resolve();\n cache.delete(queryName);\n }\n\n return state.data as T;\n }\n\n // Error – clean up and throw for error boundary\n if (state?.status === \"error\" && state?.error) {\n if (cache.has(queryName)) {\n const entry = cache.get(queryName)!;\n entry.resolve();\n cache.delete(queryName);\n }\n\n throw state.error;\n }\n\n // Pending – throw a promise for Suspense\n if (!cache.has(queryName)) {\n let resolvePromise: () => void;\n const promise = new Promise<void>((resolve) => {\n resolvePromise = resolve;\n });\n cache.set(queryName, { promise, resolve: resolvePromise! });\n\n // Subscribe to resolve the promise when state changes\n const unsub = system.subscribe([queryName], () => {\n // biome-ignore lint/suspicious/noExplicitAny: ResourceState checked at runtime\n const updated = system.read(queryName) as any;\n if (updated?.status === \"success\" || updated?.status === \"error\") {\n const entry = cache.get(queryName);\n if (entry) {\n entry.resolve();\n cache.delete(queryName);\n }\n unsub();\n }\n });\n }\n\n throw cache.get(queryName)!.promise;\n}\n\n// ============================================================================\n// createDirectiveContext — React Context provider pattern\n// ============================================================================\n\n/**\n * Create a React context for a Directive system, eliminating prop-drilling.\n *\n * Returns a Provider component and context-bound hooks that automatically\n * use the system from context — no need to pass `system` to every hook.\n *\n * **Note:** The returned hooks (e.g., `Counter.useFact(\"count\")`) follow React\n * hook rules but eslint-plugin-react-hooks may not recognize them as hooks since\n * they're object methods. This is the same pattern used by XState's\n * `createActorContext`. Suppress with `// eslint-disable-next-line react-hooks/rules-of-hooks`\n * if your linter flags it.\n *\n * @example\n * ```tsx\n * const Counter = createDirectiveContext(counterSystem);\n *\n * function App() {\n * return (\n * <Counter.Provider>\n * <Display />\n * </Counter.Provider>\n * );\n * }\n *\n * function Display() {\n * const count = Counter.useFact(\"count\");\n * const doubled = Counter.useDerived(\"doubled\");\n * const events = Counter.useEvents();\n * return <button onClick={() => events.increment()}>{count} ({doubled})</button>;\n * }\n * ```\n */\nexport function createDirectiveContext<M extends ModuleSchema>(\n system: SingleModuleSystem<M>,\n) {\n const Ctx = createContext<SingleModuleSystem<M> | null>(null);\n\n function useSystem(): SingleModuleSystem<M> {\n const sys = useContext(Ctx);\n if (!sys) {\n throw new Error(\n \"[Directive] useSystem called outside of <Provider>. Wrap your component tree with the Provider from createDirectiveContext().\",\n );\n }\n\n return sys;\n }\n\n function Provider({\n children,\n system: overrideSystem,\n }: {\n children: ReactNode;\n /** Override the system for testing or conditional logic. */\n system?: SingleModuleSystem<M>;\n }) {\n return (\n <Ctx.Provider value={overrideSystem ?? system}>{children}</Ctx.Provider>\n );\n }\n\n Provider.displayName = \"DirectiveProvider\";\n\n return {\n /** Wrap your component tree to provide the system via context. */\n Provider,\n\n /** Get the underlying system instance from context. */\n useSystem,\n\n /** Read a fact value (reactive — re-renders on change). */\n useFact: <K extends keyof InferFacts<M> & string>(factKey: K) =>\n // biome-ignore lint/suspicious/noExplicitAny: Internal type narrowing\n useFact(useSystem() as SingleModuleSystem<any>, factKey) as\n | InferFacts<M>[K]\n | undefined,\n\n /** Read a derived value (reactive — re-renders on change). */\n useDerived: <K extends keyof InferDerivations<M> & string>(\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Internal type narrowing\n useDerived(\n useSystem() as SingleModuleSystem<any>,\n derivationId,\n ) as InferDerivations<M>[K],\n\n /** Get the typed events accessor. */\n useEvents: () => useEvents<M>(useSystem()),\n\n /** Get a dispatch function for raw events. */\n useDispatch: () => useDispatch<M>(useSystem()),\n\n /** Run a selector with auto-tracked dependencies. */\n useSelector: <R,>(\n selector: (state: InferSelectorState<M>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Internal type narrowing\n useSelector(useSystem() as any, selector as any, equalityFn) as R,\n\n /** Watch a key and call a callback on change. */\n useWatch: <K extends string>(\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) => useWatch(useSystem(), key, callback),\n\n /** Fire a system event on an interval while a predicate returns true. */\n useTickWhile: (\n predicate: (system: SingleModuleSystem<M>) => boolean,\n eventName: keyof M[\"events\"] & string,\n intervalMs: number,\n ) => useTickWhile<M>(useSystem(), predicate, eventName, intervalMs),\n\n /** Get the current inspection state. */\n useInspect: () => useInspect(useSystem()),\n\n /** Explain a requirement. */\n useExplain: (requirementId: string) =>\n useExplain(useSystem(), requirementId),\n\n /** Get history state. */\n useHistory: () => useHistory(useSystem()),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/dev-true.ts","../src/index.tsx"],"names":["dev_true_default","useAuditLedger","ledger","filter","opts","requestedPollMs","pollMs","entryCount","tick","setTick","useState","useEffect","id","t","useMemo","UNINITIALIZED","useFact","system","keyOrKeys","assertSystem","_useFacts","_useSingleFact","factKey","subscribe","useCallback","onStoreChange","getSnapshot","useSyncExternalStore","factKeys","cachedValue","useRef","result","key","same","useFactWithDefault","factory","cacheRef","value","useDerived","_useDerivedMulti","_useSingleDerived","derivationId","derivationIds","useSelector","systemArg","selector","defaultValueArg","equalityFnArg","_useNamespacedSelectorImpl","defaultValue","hasDefault","equalityFn","defaultEquality","selectorRef","eqRef","defaultValueRef","prevSelectorRef","selectorVersionRef","selectorVersion","trackedFactKeysRef","trackedDeriveKeysRef","unsubsRef","deriveKeys","runWithTracking","runTrackedSelector","resubscribe","unsub","derivedKeys","updated","depsChanged","effectiveValue","newValue","moduleNames","wildcardKeys","ns","useDispatch","event","useWatch","callback","callbackRef","prevValue","useTickWhile","predicate","eventName","intervalMs","predicateRef","unsubFacts","unsubSettled","active","fn","useInspect","options","syncState","_useInspectSync","throttleMs","deferredState","setDeferredState","throttleRef","createThrottle","args","_buildInspectState","computeInspectState","cachedSnapshot","cachedUnmetIds","cachedInflightIds","cachedIsSettled","state","unmetSame","u","i","inflightSame","f","settledSame","useHistory","cachedRef","buildHistoryState","useRequirementStatus","statusPlugin","typeOrTypes","_useRequirementStatusMulti","_useRequirementStatusSingle","type","status","prev","types","cachedKey","parts","suspenseCacheMap","getSuspenseCache","plugin","cache","useSuspenseRequirement","_useSuspenseRequirementMulti","_useSuspenseRequirementSingle","promise","resolve","unsubscribe","hasLoading","firstError","cacheKey","useDirectiveRef","config","systemRef","statusPluginRef","factoryRef","wantStatus","isNamespaced","modules","rest","plugins","history","trace","errorBoundary","tickMs","zeroConfig","initialFacts","sys","createSystem","isModule","mod","baseOpts","allPlugins","createRequirementStatusPlugin","err","useNamespacedSelector","keys","keysRef","useDirective","moduleOrOptions","selections","factKeysOpt","derivedKeysOpt","configRest","subscribeAll","refResult","allDerivationKeys","unsubs","cachedFacts","cachedDerived","cachedWrapper","factsResult","derivedResult","effectiveFactKeys","effectiveDerivedKeys","factsSame","derivedSame","stableFacts","stableDerived","values","dispatch","events","useEvents","base","useExplain","requirementId","useConstraintStatus","constraintId","inspectState","inspection","c","useOptimisticUpdate","requirementType","isPending","setIsPending","error","setError","snapshotRef","rollback","mutate","updateFn","HydrationContext","createContext","DirectiveHydrator","snapshot","children","jsx","useHydratedSystem","moduleDef","useContext","mergedConfig","mergedFacts","mergeHydrationFacts","createTypedHooks","_createQuerySystem","getCreateQuerySystem","useQuerySystem","configRef","createQuerySystem","suspensePromiseCache","useSuspenseQuery","queryName","resolvePromise","entry","createDirectiveContext","Ctx","useSystem","Provider","overrideSystem"],"mappings":"4sBAAA,IAAOA,CAAAA,CAAQ,OAAO,OAAA,CAAY,KAChC,OAAA,CAAQ,GAAA,EAAK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,CAAW,IAAMsJ,CAAAA,CAAa4C,CAAAA,EAAW,CAAA,CAGzC,WAAA,CAAa,IAAMhK,EAAegK,CAAAA,EAAW,CAAA,CAG7C,WAAA,CAAa,CACX9L,CAAAA,CACAM,IAGAR,EAAAA,CAAYgM,CAAAA,EAAU,CAAU9L,CAAAA,CAAiBM,CAAU,CAAA,CAG7D,SAAU,CACRnB,CAAAA,CACA8C,CAAAA,GACGD,CAAAA,CAAS8J,CAAAA,EAAU,CAAG3M,EAAK8C,CAAQ,CAAA,CAGxC,YAAA,CAAc,CACZI,CAAAA,CACAC,CAAAA,CACAC,IACGH,EAAAA,CAAgB0J,CAAAA,EAAU,CAAGzJ,CAAAA,CAAWC,CAAAA,CAAWC,CAAU,EAGlE,UAAA,CAAY,IAAMM,EAAAA,CAAWiJ,CAAAA,EAAW,CAAA,CAGxC,WAAazC,CAAAA,EACXD,EAAAA,CAAW0C,CAAAA,EAAU,CAAGzC,CAAa,CAAA,CAGvC,UAAA,CAAY,IAAMjF,EAAAA,CAAW0H,CAAAA,EAAW,CAC1C,CACF","file":"index.js","sourcesContent":["export default typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\";\n","/**\n * React Adapter - Consolidated hooks for React integration\n *\n * 20 public exports: useFact, useDerived, useDispatch, useDirective,\n * useDirectiveRef, useSelector, useWatch, useTickWhile, useInspect,\n * useRequirementStatus, useSuspenseRequirement, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, DirectiveHydrator,\n * useHydratedSystem, useHistory, createTypedHooks, shallowEqual\n *\n * @example\n * ```tsx\n * import { useFact, useDerived, useEvents } from '@directive-run/react';\n *\n * const system = createSystem({ module: counterModule });\n * system.start();\n *\n * function Counter() {\n * const count = useFact(system, \"count\");\n * const doubled = useDerived(system, \"doubled\");\n * const events = useEvents(system);\n *\n * return (\n * <div>\n * <p>Count: {count}</p>\n * <p>Doubled: {doubled}</p>\n * <button onClick={() => events.increment()}>+</button>\n * </div>\n * );\n * }\n * ```\n */\n\nimport type {\n DistributableSnapshot,\n ErrorBoundaryConfig,\n HistoryOption,\n HistoryState,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemSnapshot,\n TraceOption,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n mergeHydrationFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport type { ReactNode } from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport isDevelopment from \"#is-development\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n// ============================================================================\n// useAuditLedger — live ledger entries with filter (R4.I + Ship 4)\n// ============================================================================\n\nimport type { AuditEntry, AuditLedger, QueryFilter } from \"@directive-run/core\";\n\n/**\n * Subscribe to an audit ledger and return the latest entries matching\n * `filter`. Re-renders whenever a new matching entry lands.\n *\n * @example\n * ```tsx\n * const entries = useAuditLedger(ledger, { kind: \"constraint.evaluate\", limit: 20 });\n * return (\n * <ul>\n * {entries.map(e => <li key={e.seq}>{e.kind} @ {new Date(e.ts).toISOString()}</li>)}\n * </ul>\n * );\n * ```\n *\n * The hook polls via a small interval (default 250 ms) because the\n * v1 ledger sink doesn't expose a pub/sub channel. Override with\n * `pollMs` if you need higher fidelity (e.g. 50ms for a live demo).\n *\n * **Polling floor:** `pollMs` is clamped to a minimum of 50 ms to prevent\n * accidental DoS from typos like `pollMs: 5`. Values below the floor are\n * silently clamped in production; dev mode logs a warning.\n */\nexport function useAuditLedger(\n ledger: AuditLedger,\n filter: QueryFilter = {},\n opts: { pollMs?: number } = {},\n): readonly AuditEntry[] {\n const requestedPollMs = opts.pollMs ?? 250;\n const pollMs = Math.max(50, requestedPollMs);\n\n if (isDevelopment) {\n if (opts.pollMs !== undefined && opts.pollMs < 50) {\n console.warn(\n `[Directive] useAuditLedger() pollMs=${opts.pollMs} is below the 50 ms floor; clamped to 50 ms.`,\n );\n }\n if (pollMs < 100) {\n const entryCount = ledger.toJSON().entries.length;\n if (entryCount > 1000) {\n console.warn(\n `[Directive] useAuditLedger() polling every ${pollMs} ms against a ${entryCount}-entry ledger — that's a lot of CPU per tick. Consider raising pollMs or tightening the filter.`,\n );\n }\n }\n }\n\n const [tick, setTick] = useState(0);\n\n useEffect(() => {\n const id = setInterval(() => setTick((t) => t + 1), pollMs);\n\n return () => clearInterval(id);\n }, [pollMs]);\n\n // Re-query on every tick — cheap O(N) walk against the in-memory ring.\n // `tick` is the dep; `filter` is captured by closure (caller passes the\n // same object identity unless they intend a refresh).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => ledger.query(filter), [ledger, tick, filter]);\n}\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/** Sentinel value for uninitialized selector cache */\nconst UNINITIALIZED = Symbol(\"directive.uninitialized\");\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKey: K): InferFacts<S>[K] | undefined;\n\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(system: SingleModuleSystem<S>, factKeys: K[]): Pick<InferFacts<S>, K>;\n\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useFact\", system);\n if (isDevelopment && typeof keyOrKeys === \"function\") {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFacts(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return _useSingleFact(system, keyOrKeys);\n}\n\nfunction _useSingleFact(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKey: string,\n): unknown {\n if (isDevelopment) {\n if (!(factKey in system.facts.$store.toObject())) {\n console.warn(\n `[Directive] useFact(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe([factKey], onStoreChange);\n },\n [system, factKey],\n );\n\n const getSnapshot = useCallback(() => {\n return system.facts.$store.get(factKey as never);\n }, [system, factKey]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useFacts(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.facts.$store.subscribe(factKeys, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...factKeys],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key as never);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const key of factKeys) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[key],\n result[key],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...factKeys]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useFactWithDefault — stable-identity nullable-fact fallback (RFC-2)\n// ============================================================================\n\n/**\n * Read a fact, falling back to a lazily-computed default with **stable\n * referential identity** when the fact is `null`/`undefined`.\n *\n * **Why this exists:** the natural pattern\n *\n * ```tsx\n * const markedCells = useFact(sys, \"markedCells\") ?? deps.initializeMarkedCells();\n * ```\n *\n * calls `initializeMarkedCells()` on every render where `markedCells` is\n * `null`, producing a fresh array/object identity each time. Anything\n * downstream that memoizes on that identity (`useMemo` deps,\n * `React.memo`, virtualized list keys) re-runs unnecessarily and can\n * trigger re-render storms.\n *\n * `useFactWithDefault` runs `factory` at most once per system instance and\n * caches the result in a ref. While the fact is `null`/`undefined`, every\n * render returns the same cached value. When the fact transitions to a\n * non-null value, that value is returned instead. If the fact later\n * returns to `null`, the originally-cached factory result is reused\n * (the factory is **not** called again).\n *\n * Swapping the `system` argument re-runs the factory on the new system.\n *\n * @example\n * ```tsx\n * const markedCells = useFactWithDefault(\n * sys,\n * \"markedCells\",\n * () => deps.initializeMarkedCells(),\n * );\n * // `markedCells` has stable identity across renders while the fact is null.\n * ```\n *\n * @param system - The system to read the fact from.\n * @param factKey - The fact key.\n * @param factory - Lazy default factory; runs at most once per system instance.\n * @returns The fact value when non-null, otherwise the cached factory result.\n */\nexport function useFactWithDefault<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKey: K,\n factory: () => NonNullable<InferFacts<S>[K]>,\n): NonNullable<InferFacts<S>[K]>;\n\n/** Implementation */\nexport function useFactWithDefault(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n factKey: string,\n factory: () => unknown,\n): unknown {\n assertSystem(\"useFactWithDefault\", system);\n\n // Track factory result keyed by system identity. When the consumer swaps\n // the system, we deliberately re-run the factory on the new instance —\n // a fresh system has a fresh default.\n const cacheRef = useRef<{ system: unknown; value: unknown } | null>(null);\n if (cacheRef.current === null || cacheRef.current.system !== system) {\n cacheRef.current = { system, value: factory() };\n }\n\n const value = useFact(system, factKey);\n if (value === null || value === undefined) {\n return cacheRef.current.value;\n }\n return value;\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(system: SingleModuleSystem<S>, derivationId: K): InferDerivations<S>[K];\n\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Pick<InferDerivations<S>, K>;\n\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): unknown {\n assertSystem(\"useDerived\", system);\n if (isDevelopment && typeof keyOrKeys === \"function\") {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(keyOrKeys)) {\n return _useDerivedMulti(system, keyOrKeys);\n }\n\n // Single key path\n return _useSingleDerived(system, keyOrKeys);\n}\n\nfunction _useSingleDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationId: string,\n): unknown {\n if (isDevelopment) {\n if (!(derivationId in system.derive)) {\n console.warn(\n `[Directive] useDerived(\"${derivationId}\") — derivation not found. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe([derivationId], onStoreChange);\n },\n [system, derivationId],\n );\n\n const getSnapshot = useCallback(() => {\n return system.read(derivationId);\n }, [system, derivationId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useDerivedMulti(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Record<string, unknown> {\n const cachedValue = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe(derivationIds, onStoreChange);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, ...derivationIds],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n\n if (cachedValue.current !== UNINITIALIZED) {\n let same = true;\n for (const id of derivationIds) {\n if (\n !Object.is(\n (cachedValue.current as Record<string, unknown>)[id],\n result[id],\n )\n ) {\n same = false;\n break;\n }\n }\n if (same) return cachedValue.current;\n }\n\n cachedValue.current = result;\n return result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, ...derivationIds]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSelector — Zustand-style selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations (Zustand-style).\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys. Falls back to subscribeAll\n * if no keys are detected.\n *\n * Supports an optional default value as the 3rd parameter, used when\n * the system is null/undefined or the selector returns undefined.\n * When a default value is provided, the system parameter may be\n * null | undefined — the hook returns the default and recomputes\n * when the system becomes available.\n *\n * An optional equality function can be passed as the 4th parameter\n * to customize when the selector result is considered \"changed\".\n * Defaults to `Object.is`. Use `shallowEqual` (exported from this\n * package) when your selector returns a new object/array each time.\n *\n * @example\n * ```tsx\n * // Basic usage\n * const count = useSelector(system, (s) => s.count);\n *\n * // With default value (allows nullable system)\n * const count = useSelector(system, (s) => s.count, 0);\n *\n * // With default value + custom equality\n * const coords = useSelector(system, (s) => ({ x: s.x, y: s.y }), { x: 0, y: 0 }, shallowEqual);\n * ```\n */\n\n// Non-null system, no default\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n): R;\n\n// Non-null system, with default value and optional equality\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable system, default REQUIRED\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S> | null | undefined,\n selector: (state: InferSelectorState<S>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Namespaced system overloads ---\n\n// Namespaced system, no default\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n): R;\n\n// Namespaced system, with default value and optional equality\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Nullable namespaced system, default REQUIRED\nexport function useSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules> | null | undefined,\n selector: (state: NamespacedSystem<Modules>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// --- Generic fallbacks ---\n\n// Generic fallback: non-null system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue?: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\n// Generic fallback: nullable system\nexport function useSelector<R>(\n // biome-ignore lint/suspicious/noExplicitAny: Generic fallback\n system: SingleModuleSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n selector: (state: Record<string, any>) => R,\n defaultValue: R,\n equalityFn?: (a: R, b: R) => boolean,\n): R;\n\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature accepts both system types\n systemArg: SingleModuleSystem<any> | NamespacedSystem<any> | null | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n // Route to namespaced implementation if system is a NamespacedSystem\n // biome-ignore lint/suspicious/noExplicitAny: Runtime type check\n if (systemArg && (systemArg as any)._mode === \"namespaced\") {\n // biome-ignore lint/suspicious/noExplicitAny: Delegate to namespaced impl\n return _useNamespacedSelectorImpl(\n systemArg as NamespacedSystem<any>,\n selector,\n defaultValueArg,\n equalityFnArg,\n );\n }\n\n // After the namespaced check, system is a SingleModuleSystem\n const system = systemArg as SingleModuleSystem<any> | null | undefined;\n let defaultValue: unknown;\n let hasDefault = false;\n const equalityFn: (a: unknown, b: unknown) => boolean =\n equalityFnArg ?? defaultEquality;\n\n if (defaultValueArg !== undefined) {\n defaultValue = defaultValueArg;\n hasDefault = true;\n }\n\n // Dev-mode warning: null system without a default value\n if (isDevelopment) {\n if (!system && !hasDefault) {\n console.error(\n \"[Directive] useSelector() received a null/undefined system without a default value. \" +\n \"Provide a default value as the 3rd parameter: useSelector(system, selector, defaultValue)\",\n );\n }\n }\n\n // Store selector/eq/default in refs to avoid resubscription churn\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValue);\n // Track selector identity changes to force resubscription when deps may shift\n const prevSelectorRef = useRef(selector);\n const selectorVersionRef = useRef(0);\n if (prevSelectorRef.current !== selector) {\n prevSelectorRef.current = selector;\n selectorVersionRef.current++;\n }\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValue;\n\n const selectorVersion = selectorVersionRef.current;\n const trackedFactKeysRef = useRef<string[]>([]);\n const trackedDeriveKeysRef = useRef<string[]>([]);\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n const unsubsRef = useRef<Array<() => void>>([]);\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const deriveKeys = useMemo(\n () => (system ? new Set(Object.keys(system.derive)) : new Set<string>()),\n [system],\n );\n\n const runWithTracking = useCallback(() => {\n if (!system) {\n return {\n value: defaultValueRef.current,\n factKeys: [] as string[],\n deriveKeys: [] as string[],\n };\n }\n\n return runTrackedSelector(system, deriveKeys, selectorRef.current);\n }, [system, deriveKeys]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!system) {\n // No system — return noop unsubscribe\n return () => {};\n }\n\n const resubscribe = () => {\n // Cleanup previous subscriptions\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n\n // Run selector with tracking to detect accessed keys\n const { factKeys, deriveKeys: derivedKeys } = runWithTracking();\n trackedFactKeysRef.current = factKeys;\n trackedDeriveKeysRef.current = derivedKeys;\n\n // Subscribe to accessed fact keys\n if (factKeys.length > 0) {\n unsubsRef.current.push(\n system.facts.$store.subscribe(factKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n } else if (derivedKeys.length === 0) {\n // No deps at all — subscribe to everything\n unsubsRef.current.push(\n system.facts.$store.subscribeAll(onStoreChange),\n );\n }\n\n // Subscribe to accessed derivation keys\n if (derivedKeys.length > 0) {\n unsubsRef.current.push(\n system.subscribe(derivedKeys, () => {\n // Re-track on notification for dynamic deps\n const updated = runWithTracking();\n if (\n depsChanged(\n trackedFactKeysRef.current,\n updated.factKeys,\n trackedDeriveKeysRef.current,\n updated.deriveKeys,\n )\n )\n resubscribe();\n onStoreChange();\n }),\n );\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubsRef.current) unsub();\n unsubsRef.current = [];\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- selectorVersion forces resubscription when selector deps change\n [system, runWithTracking, selectorVersion],\n );\n\n const getSnapshot = useCallback(() => {\n let effectiveValue: unknown;\n\n if (!system) {\n effectiveValue = defaultValueRef.current;\n } else {\n const { value: newValue } = runWithTracking();\n\n // When selector returns undefined and we have a default, use it\n effectiveValue =\n newValue === undefined && hasDefault\n ? defaultValueRef.current\n : newValue;\n }\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [runWithTracking, system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// _useNamespacedSelectorImpl — internal namespaced useSelector\n// ============================================================================\n\n/**\n * Internal implementation for useSelector with NamespacedSystem.\n * Subscribes to all module namespaces and runs the selector against the system.\n * Uses equality comparison to prevent unnecessary re-renders.\n */\nfunction _useNamespacedSelectorImpl(\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n system: NamespacedSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Internal impl\n selector: (state: any) => unknown,\n defaultValueArg?: unknown,\n equalityFnArg?: (a: unknown, b: unknown) => boolean,\n): unknown {\n const hasDefault = defaultValueArg !== undefined;\n const equalityFn = equalityFnArg ?? defaultEquality;\n\n const selectorRef = useRef(selector);\n const eqRef = useRef(equalityFn);\n const defaultValueRef = useRef(defaultValueArg);\n selectorRef.current = selector;\n eqRef.current = equalityFn;\n defaultValueRef.current = defaultValueArg;\n\n const cachedValue = useRef<unknown>(UNINITIALIZED);\n\n // Get all module namespace names for wildcard subscription\n const moduleNames = useMemo(() => Object.keys(system.facts), [system]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n // Subscribe to all modules using wildcard keys\n const wildcardKeys = moduleNames.map((ns) => `${ns}.*`);\n\n return system.subscribe(wildcardKeys, onStoreChange);\n },\n [system, moduleNames],\n );\n\n const getSnapshot = useCallback(() => {\n const newValue = selectorRef.current(system);\n const effectiveValue =\n newValue === undefined && hasDefault ? defaultValueRef.current : newValue;\n\n if (\n cachedValue.current !== UNINITIALIZED &&\n eqRef.current(cachedValue.current, effectiveValue)\n ) {\n return cachedValue.current;\n }\n\n cachedValue.current = effectiveValue;\n\n return effectiveValue;\n }, [system, hasDefault]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return useCallback(\n (event: InferEvents<S>) => {\n system.dispatch(event);\n },\n [system],\n );\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect (no re-render)\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n prevValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n prevValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation overload dispatch\n callback: (newValue: any, prevValue: any) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n useEffect(() => {\n return system.watch(key, (newValue, prevValue) => {\n callbackRef.current(newValue, prevValue);\n });\n }, [system, key]);\n}\n\n// ============================================================================\n// useTickWhile — interval-driven event dispatch gated by predicate\n// ============================================================================\n\n/**\n * Fires a system event on a recurring interval while a predicate returns true.\n *\n * Replaces the verbatim `setInterval(() => sys.events.TICK(), ms)` /\n * `clearInterval` pattern that appears across components driving status-gated\n * polling, animation, or timer flows. The hook subscribes to all fact and\n * settled-state changes so the predicate is re-evaluated whenever the system\n * mutates; when it flips to true, an interval starts; when it flips to false,\n * the interval is cleared. Cleans up on unmount.\n *\n * @example\n * ```tsx\n * useTickWhile(\n * system,\n * (sys) => sys.facts.status === \"running\",\n * \"TICK\",\n * 1000,\n * );\n * ```\n */\nexport function useTickWhile<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n predicate: (system: SingleModuleSystem<S>) => boolean,\n eventName: keyof S[\"events\"] & string,\n intervalMs: number,\n): void {\n assertSystem(\"useTickWhile\", system);\n\n const predicateRef = useRef(predicate);\n predicateRef.current = predicate;\n\n // Track latest active state via a useState + subscription. We need React to\n // re-render the hook (or rather re-run the effect) whenever the predicate's\n // result flips, so we cache the result and broadcast change to listeners.\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n return predicateRef.current(system);\n }, [system]);\n\n const active = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n useEffect(() => {\n if (!active) return;\n if (!Number.isFinite(intervalMs) || intervalMs <= 0) {\n if (isDevelopment) {\n console.warn(\n `[Directive] useTickWhile() received non-positive intervalMs: ${intervalMs}. Interval will not fire.`,\n );\n }\n return;\n }\n\n const id = setInterval(() => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic event dispatch\n const evts = system.events as Record<string, (...args: any[]) => void>;\n const fn = evts[eventName as string];\n if (typeof fn === \"function\") {\n fn();\n } else if (isDevelopment) {\n console.warn(\n `[Directive] useTickWhile() — event \"${String(eventName)}\" not found on system.events.`,\n );\n }\n }, intervalMs);\n\n return () => clearInterval(id);\n }, [active, system, eventName, intervalMs]);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n// InspectState is imported from ./shared.js and re-exported above\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n /** Throttle updates to this interval (ms). When set, uses useState instead of useSyncExternalStore. */\n throttleMs?: number;\n}\n\n/**\n * Hook to get consolidated system inspection data reactively.\n *\n * Merges isSettled, unmet/inflight requirements, and working state\n * into a single subscription. Optionally throttle updates.\n *\n * @example\n * ```tsx\n * const { isSettled, isWorking, hasUnmet } = useInspect(system);\n * const throttled = useInspect(system, { throttleMs: 200 });\n * ```\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): InspectState {\n assertSystem(\"useInspect\", system);\n // Always call the sync version (useSyncExternalStore path) — no conditional hooks\n const syncState = _useInspectSync(system);\n\n const throttleMs = options?.throttleMs;\n const [deferredState, setDeferredState] = useState(syncState);\n const throttleRef = useRef<{\n throttled: (...args: unknown[]) => void;\n cleanup: () => void;\n } | null>(null);\n\n // Create/recreate throttle when throttleMs changes\n useEffect(() => {\n if (!throttleMs || throttleMs <= 0) {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n return;\n }\n // Clean up old throttle before creating new one\n throttleRef.current?.cleanup();\n throttleRef.current = createThrottle((...args: unknown[]) => {\n setDeferredState(args[0] as InspectState);\n }, throttleMs);\n return () => {\n throttleRef.current?.cleanup();\n throttleRef.current = null;\n };\n }, [throttleMs]);\n\n // Feed sync state through throttle after each render\n useEffect(() => {\n if (throttleRef.current) {\n throttleRef.current.throttled(syncState);\n }\n }, [syncState]);\n\n if (!throttleMs || throttleMs <= 0) return syncState;\n return deferredState;\n}\n\nfunction _buildInspectState(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n return computeInspectState(system);\n}\n\nfunction _useInspectSync(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n): InspectState {\n const cachedSnapshot = useRef<InspectState | null>(null);\n const cachedUnmetIds = useRef<string[]>([]);\n const cachedInflightIds = useRef<string[]>([]);\n const cachedIsSettled = useRef<boolean | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = _buildInspectState(system);\n\n const unmetSame =\n state.unmet.length === cachedUnmetIds.current.length &&\n state.unmet.every((u, i) => u.id === cachedUnmetIds.current[i]);\n const inflightSame =\n state.inflight.length === cachedInflightIds.current.length &&\n state.inflight.every((f, i) => f.id === cachedInflightIds.current[i]);\n const settledSame = state.isSettled === cachedIsSettled.current;\n\n if (unmetSame && inflightSame && settledSame && cachedSnapshot.current) {\n return cachedSnapshot.current;\n }\n\n cachedSnapshot.current = state;\n cachedUnmetIds.current = state.unmet.map((u) => u.id);\n cachedInflightIds.current = state.inflight.map((f) => f.id);\n cachedIsSettled.current = state.isSettled;\n\n return state;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useHistory — reactive history state\n// ============================================================================\n\n/**\n * Reactive history hook. Returns null when history is disabled.\n * Re-renders when snapshots are taken or navigation occurs.\n *\n * @example\n * ```tsx\n * const history = useHistory(system);\n * if (history) {\n * return (\n * <div>\n * <button disabled={!history.canGoBack} onClick={() => history.goBack()}>Undo</button>\n * <button disabled={!history.canGoForward} onClick={() => history.goForward()}>Redo</button>\n * <span>{history.currentIndex + 1} / {history.totalSnapshots}</span>\n * </div>\n * );\n * }\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): HistoryState | null {\n assertSystem(\"useHistory\", system);\n const cachedRef = useRef<HistoryState | null>(null);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => system.onHistoryChange(onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n const state = buildHistoryState(system);\n if (!state) return null;\n\n // Return stable reference when values haven't changed\n if (\n cachedRef.current &&\n cachedRef.current.canGoBack === state.canGoBack &&\n cachedRef.current.canGoForward === state.canGoForward &&\n cachedRef.current.currentIndex === state.currentIndex &&\n cachedRef.current.totalSnapshots === state.totalSnapshots &&\n cachedRef.current.isPaused === state.isPaused\n ) {\n return cachedRef.current;\n }\n\n cachedRef.current = state;\n return cachedRef.current;\n }, [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useRequirementStatusMulti(statusPlugin, typeOrTypes);\n }\n return _useRequirementStatusSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useRequirementStatusSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const cachedRef = useRef<RequirementTypeStatus | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const status = statusPlugin.getStatus(type);\n\n if (cachedRef.current !== UNINITIALIZED) {\n const prev = cachedRef.current;\n if (\n prev.pending === status.pending &&\n prev.inflight === status.inflight &&\n prev.failed === status.failed &&\n prev.isLoading === status.isLoading &&\n prev.hasError === status.hasError &&\n prev.lastError === status.lastError\n ) {\n return cachedRef.current;\n }\n }\n\n cachedRef.current = status;\n return status;\n }, [statusPlugin, type]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\nfunction _useRequirementStatusMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const cachedRef = useRef<Record<string, RequirementTypeStatus> | null>(null);\n const cachedKey = useRef<string>(\"\");\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return statusPlugin.subscribe(onStoreChange);\n },\n [statusPlugin],\n );\n\n const getSnapshot = useCallback(() => {\n const result: Record<string, RequirementTypeStatus> = {};\n const parts: string[] = [];\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n parts.push(\n `${type}:${status.pending}:${status.inflight}:${status.failed}:${status.hasError}:${status.lastError?.message ?? \"\"}`,\n );\n }\n const key = parts.join(\"|\");\n\n if (key !== cachedKey.current) {\n cachedKey.current = key;\n cachedRef.current = result;\n }\n\n return cachedRef.current ?? result;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [statusPlugin, ...types]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useSuspenseRequirement — single or multi\n// ============================================================================\n\n// Cache for pending promises, scoped per statusPlugin to prevent cross-system leaks.\nconst suspenseCacheMap = new WeakMap<\n StatusPlugin,\n Map<string, Promise<void>>\n>();\n\nfunction getSuspenseCache(plugin: StatusPlugin): Map<string, Promise<void>> {\n let cache = suspenseCacheMap.get(plugin);\n if (!cache) {\n cache = new Map();\n suspenseCacheMap.set(plugin, cache);\n }\n return cache;\n}\n\n/** Single type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus;\n\n/** Multi-type overload */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus>;\n\n/** Implementation */\nexport function useSuspenseRequirement(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n): RequirementTypeStatus | Record<string, RequirementTypeStatus> {\n if (Array.isArray(typeOrTypes)) {\n return _useSuspenseRequirementMulti(statusPlugin, typeOrTypes);\n }\n return _useSuspenseRequirementSingle(statusPlugin, typeOrTypes);\n}\n\nfunction _useSuspenseRequirementSingle(\n statusPlugin: StatusPlugin,\n type: string,\n): RequirementTypeStatus {\n const status = statusPlugin.getStatus(type);\n\n if (status.hasError && status.lastError) {\n throw status.lastError;\n }\n\n if (status.isLoading) {\n const cache = getSuspenseCache(statusPlugin);\n let promise = cache.get(type);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const currentStatus = statusPlugin.getStatus(type);\n if (!currentStatus.isLoading) {\n cache.delete(type);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(type, promise);\n }\n\n throw promise;\n }\n\n return status;\n}\n\nfunction _useSuspenseRequirementMulti(\n statusPlugin: StatusPlugin,\n types: string[],\n): Record<string, RequirementTypeStatus> {\n const result: Record<string, RequirementTypeStatus> = {};\n let hasLoading = false;\n let firstError: Error | null = null;\n\n for (const type of types) {\n const status = statusPlugin.getStatus(type);\n result[type] = status;\n\n if (status.hasError && status.lastError && !firstError) {\n firstError = status.lastError;\n }\n if (status.isLoading) {\n hasLoading = true;\n }\n }\n\n if (firstError) {\n throw firstError;\n }\n\n if (hasLoading) {\n const cache = getSuspenseCache(statusPlugin);\n const cacheKey = types.slice().sort().join(\",\");\n let promise = cache.get(cacheKey);\n\n if (!promise) {\n promise = new Promise<void>((resolve) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n const allDone = types.every(\n (t) => !statusPlugin.getStatus(t).isLoading,\n );\n if (allDone) {\n cache.delete(cacheKey);\n unsubscribe();\n resolve();\n }\n });\n });\n cache.set(cacheKey, promise);\n }\n\n throw promise;\n }\n\n return result;\n}\n\n// ============================================================================\n// useDirectiveRef — scoped system lifecycle\n// ============================================================================\n\n/** Base options for creating a scoped system */\ninterface DirectiveRefBaseConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n history?: HistoryOption;\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n}\n\n/** Options for useDirectiveRef: module directly, or config object */\nexport type UseDirectiveRefOptions<M extends ModuleSchema> =\n | ModuleDef<M>\n | (DirectiveRefBaseConfig & { module: ModuleDef<M> });\n\n/** Options for useDirectiveRef with namespaced modules */\nexport type UseDirectiveRefNamespacedOptions<Modules extends ModulesMap> =\n DirectiveRefBaseConfig & { modules: { [K in keyof Modules]: Modules[K] } };\n\n// --- Single-module overloads ---\n\n/** Without status (no config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n): SingleModuleSystem<M>;\n\n/** Without status (with config): returns system directly */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: DirectiveRefBaseConfig,\n): SingleModuleSystem<M>;\n\n/** With status: returns { system, statusPlugin } */\nexport function useDirectiveRef<M extends ModuleSchema>(\n options: UseDirectiveRefOptions<M>,\n config: { status: true } & DirectiveRefBaseConfig,\n): { system: SingleModuleSystem<M>; statusPlugin: StatusPlugin };\n\n// --- Namespaced (multi-module) overloads ---\n\n/** Namespaced: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n): NamespacedSystem<Modules>;\n\n/** Namespaced with config: returns NamespacedSystem directly */\nexport function useDirectiveRef<const Modules extends ModulesMap>(\n options: UseDirectiveRefNamespacedOptions<Modules>,\n config: DirectiveRefBaseConfig,\n): NamespacedSystem<Modules>;\n\n/** Implementation */\nexport function useDirectiveRef(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature handles both modes\n options: any,\n config?: { status?: boolean } & DirectiveRefBaseConfig,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation return varies by overload\n): any {\n // biome-ignore lint/suspicious/noExplicitAny: System ref holds either system type\n const systemRef = useRef<any>(null);\n const statusPluginRef = useRef<StatusPlugin | null>(null);\n // Factory ref for strict mode re-creation (effects unmount then re-mount)\n // biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\n const factoryRef = useRef<(() => any) | null>(null);\n const wantStatus = config?.status === true;\n const isNamespaced = \"modules\" in options;\n\n if (!systemRef.current) {\n // Build a factory that creates + starts the system.\n // Called once during render and again on strict-mode re-mount.\n factoryRef.current = () => {\n if (isNamespaced) {\n // --- Namespaced mode: { modules: { ... } } ---\n const { modules, ...rest } = options;\n const plugins = config?.plugins ?? rest.plugins ?? [];\n const history = config?.history ?? rest.history;\n const trace = config?.trace ?? rest.trace;\n const errorBoundary = config?.errorBoundary ?? rest.errorBoundary;\n const tickMs = config?.tickMs ?? rest.tickMs;\n const zeroConfig = config?.zeroConfig ?? rest.zeroConfig;\n const initialFacts = config?.initialFacts ?? rest.initialFacts;\n\n const sys = createSystem({\n modules,\n plugins: plugins.length > 0 ? plugins : undefined,\n history,\n trace,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n }\n\n // --- Single-module mode ---\n const isModule = \"id\" in options && \"schema\" in options;\n const mod = isModule ? options : options.module;\n const baseOpts = isModule ? {} : (options as DirectiveRefBaseConfig);\n const plugins = config?.plugins ?? baseOpts.plugins ?? [];\n const history = config?.history ?? baseOpts.history;\n const trace = config?.trace ?? baseOpts.trace;\n const errorBoundary = config?.errorBoundary ?? baseOpts.errorBoundary;\n const tickMs = config?.tickMs ?? baseOpts.tickMs;\n const zeroConfig = config?.zeroConfig ?? baseOpts.zeroConfig;\n const initialFacts = config?.initialFacts ?? baseOpts.initialFacts;\n\n let allPlugins = [...plugins];\n\n if (wantStatus) {\n statusPluginRef.current = createRequirementStatusPlugin();\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins = [\n ...allPlugins,\n statusPluginRef.current.plugin as Plugin<any>,\n ];\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const sys = createSystem({\n module: mod,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n history,\n trace,\n errorBoundary,\n tickMs,\n zeroConfig,\n initialFacts,\n } as any);\n // Always initialize facts/derivations (safe for SSR).\n // Only start reconciliation on the client.\n sys.initialize();\n if (typeof window !== \"undefined\") {\n sys.start();\n }\n\n return sys;\n };\n\n // Start synchronously so facts are initialized before the first render\n systemRef.current = factoryRef.current();\n }\n\n useEffect(() => {\n // Strict mode re-mount: system was destroyed in cleanup, recreate it\n if (!systemRef.current && factoryRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n return () => {\n // RFC 0009 follow-up (R18 Tier 2-B): destroyAsync so source\n // unsubscribes complete; fire-and-forget with swallow-catch\n // (React's effect cleanup is sync).\n systemRef.current?.destroyAsync().catch((err: unknown) => {\n if (isDevelopment)\n console.warn(\n \"[Directive] destroyAsync rejected during unmount:\",\n err,\n );\n });\n systemRef.current = null;\n statusPluginRef.current = null;\n };\n }, []);\n\n if (wantStatus && !isNamespaced) {\n return {\n system: systemRef.current!,\n statusPlugin: statusPluginRef.current!,\n };\n }\n\n return systemRef.current!;\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem with useSyncExternalStore\n// ============================================================================\n\n/**\n * React hook to select derived values from a NamespacedSystem.\n * Uses useSyncExternalStore for tear-free reads.\n *\n * @param system - The namespaced system to read from\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```tsx\n * const system = useDirectiveRef({ modules: { auth, data } });\n * const token = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * const count = useNamespacedSelector(system, [\"data.*\"], (s) => s.derive.data.total);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): R {\n const keysRef = useRef(keys);\n keysRef.current = keys;\n const selectorRef = useRef(selector);\n selectorRef.current = selector;\n\n const subscribe = useCallback(\n (onStoreChange: () => void) =>\n system.subscribe(keysRef.current, onStoreChange),\n [system],\n );\n\n const getSnapshot = useCallback(() => selectorRef.current(system), [system]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useDirective — scoped system with selected values in containers\n// ============================================================================\n\n/** Options for useDirective hook */\nexport interface UseDirectiveOptions<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n> extends DirectiveRefBaseConfig {\n /** Fact keys to subscribe to */\n facts?: FK[];\n /** Derivation keys to subscribe to */\n derived?: DK[];\n /** Enable status plugin */\n status?: boolean;\n}\n\n/** Return type for useDirective hook (without status) */\nexport type UseDirectiveReturn<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = {\n system: SingleModuleSystem<S>;\n dispatch: (event: InferEvents<S>) => void;\n events: SingleModuleSystem<S>[\"events\"];\n facts: Pick<InferFacts<S>, FK>;\n derived: Pick<InferDerivations<S>, DK>;\n};\n\n/** Return type for useDirective hook (with status) */\nexport type UseDirectiveReturnWithStatus<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string,\n DK extends keyof InferDerivations<S> & string,\n> = UseDirectiveReturn<S, FK, DK> & {\n statusPlugin: StatusPlugin;\n};\n\n/**\n * Convenience hook that creates a scoped system and reads selected facts/derivations\n * into container objects. When no `facts` or `derived` keys are specified, subscribes\n * to ALL facts and derivations (replacing the former `useModule` hook).\n *\n * @example\n * ```tsx\n * // Selective subscription\n * const { dispatch, facts: { count }, derived: { doubled } } = useDirective(counterModule, {\n * facts: [\"count\"],\n * derived: [\"doubled\"],\n * });\n *\n * // Subscribe to everything (no keys = all facts + all derivations)\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n * ```\n */\nexport function useDirective<\n S extends ModuleSchema,\n FK extends keyof InferFacts<S> & string = never,\n DK extends keyof InferDerivations<S> & string = never,\n>(\n moduleOrOptions: UseDirectiveRefOptions<S>,\n selections: UseDirectiveOptions<S, FK, DK> = {} as UseDirectiveOptions<\n S,\n FK,\n DK\n >,\n): UseDirectiveReturn<S, FK, DK> | UseDirectiveReturnWithStatus<S, FK, DK> {\n const {\n facts: factKeysOpt,\n derived: derivedKeysOpt,\n status,\n ...configRest\n } = selections;\n const factKeys = (factKeysOpt ?? []) as FK[];\n const derivedKeys = (derivedKeysOpt ?? []) as DK[];\n\n // When no keys are specified, subscribe to everything\n const subscribeAll = factKeys.length === 0 && derivedKeys.length === 0;\n\n // Create system via useDirectiveRef (handles lifecycle)\n // biome-ignore lint/suspicious/noExplicitAny: Conditional overload dispatch\n const refResult: any = status\n ? useDirectiveRef(moduleOrOptions, { status: true as const, ...configRest })\n : useDirectiveRef(moduleOrOptions, configRest);\n\n const system: SingleModuleSystem<S> = status ? refResult.system : refResult;\n\n const statusPlugin = status\n ? (\n refResult as {\n system: SingleModuleSystem<S>;\n statusPlugin: StatusPlugin;\n }\n ).statusPlugin\n : undefined;\n\n // For subscribe-all mode, get all derivation keys\n const allDerivationKeys = useMemo(\n () => (subscribeAll ? Object.keys(system.derive) : []),\n [system, subscribeAll],\n );\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubs: Array<() => void> = [];\n if (subscribeAll) {\n // Subscribe to ALL facts and ALL derivations\n unsubs.push(system.facts.$store.subscribeAll(onStoreChange));\n if (allDerivationKeys.length > 0) {\n unsubs.push(system.subscribe(allDerivationKeys, onStoreChange));\n }\n } else {\n if (factKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(factKeys, onStoreChange));\n }\n if (derivedKeys.length > 0) {\n unsubs.push(system.subscribe(derivedKeys, onStoreChange));\n }\n }\n return () => {\n for (const unsub of unsubs) unsub();\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys],\n );\n\n const cachedFacts = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedDerived = useRef<Record<string, unknown> | typeof UNINITIALIZED>(\n UNINITIALIZED,\n );\n const cachedWrapper = useRef<{\n facts: Record<string, unknown>;\n derived: Record<string, unknown>;\n } | null>(null);\n\n const getSnapshot = useCallback(() => {\n let factsResult: Record<string, unknown>;\n let derivedResult: Record<string, unknown>;\n let effectiveFactKeys: readonly string[];\n let effectiveDerivedKeys: readonly string[];\n\n if (subscribeAll) {\n // Read ALL facts and ALL derivations\n factsResult = system.facts.$store.toObject();\n effectiveFactKeys = Object.keys(factsResult);\n derivedResult = {};\n for (const key of allDerivationKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = allDerivationKeys;\n } else {\n // Read selected keys only\n factsResult = {};\n for (const key of factKeys) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic fact access\n factsResult[key] = (system.facts as any)[key];\n }\n effectiveFactKeys = factKeys;\n derivedResult = {};\n for (const key of derivedKeys) {\n derivedResult[key] = system.read(key);\n }\n effectiveDerivedKeys = derivedKeys;\n }\n\n // Check facts stability\n let factsSame = cachedFacts.current !== UNINITIALIZED;\n if (factsSame) {\n const prev = cachedFacts.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveFactKeys.length) {\n factsSame = false;\n } else {\n for (const key of effectiveFactKeys) {\n if (!Object.is(prev[key], factsResult[key])) {\n factsSame = false;\n break;\n }\n }\n }\n }\n\n // Check derived stability\n let derivedSame = cachedDerived.current !== UNINITIALIZED;\n if (derivedSame) {\n const prev = cachedDerived.current as Record<string, unknown>;\n const prevKeys = Object.keys(prev);\n if (prevKeys.length !== effectiveDerivedKeys.length) {\n derivedSame = false;\n } else {\n for (const key of effectiveDerivedKeys) {\n if (!Object.is(prev[key], derivedResult[key])) {\n derivedSame = false;\n break;\n }\n }\n }\n }\n\n const stableFacts = factsSame\n ? (cachedFacts.current as Record<string, unknown>)\n : factsResult;\n const stableDerived = derivedSame\n ? (cachedDerived.current as Record<string, unknown>)\n : derivedResult;\n\n if (!factsSame) cachedFacts.current = factsResult;\n if (!derivedSame) cachedDerived.current = derivedResult;\n\n // Return same wrapper reference when both containers are unchanged\n if (factsSame && derivedSame && cachedWrapper.current) {\n return cachedWrapper.current;\n }\n\n cachedWrapper.current = { facts: stableFacts, derived: stableDerived };\n return cachedWrapper.current;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, subscribeAll, ...factKeys, ...derivedKeys, ...allDerivationKeys]);\n\n const values = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const dispatch = useCallback(\n (event: InferEvents<S>) => system.dispatch(event),\n [system],\n );\n\n const events = useEvents(system);\n\n const base = {\n system,\n dispatch,\n events,\n facts: values.facts as Pick<InferFacts<S>, FK>,\n derived: values.derived as Pick<InferDerivations<S>, DK>,\n };\n\n if (status && statusPlugin) {\n return { ...base, statusPlugin } as UseDirectiveReturnWithStatus<S, FK, DK>;\n }\n\n return base as UseDirectiveReturn<S, FK, DK>;\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher. Provides autocomplete for event names\n * and avoids needing useCallback wrappers for event dispatch.\n *\n * @example\n * ```tsx\n * const events = useEvents(system);\n * <button onClick={() => events.increment()}>+</button>\n * ```\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return useMemo(() => system.events, [system]);\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n * Updates whenever system state changes.\n *\n * @example\n * ```tsx\n * const explanation = useExplain(system, \"req-123\");\n * if (explanation) <pre>{explanation}</pre>;\n * ```\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): string | null {\n assertSystem(\"useExplain\", system);\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const unsubFacts = system.facts.$store.subscribeAll(onStoreChange);\n const unsubSettled = system.onSettledChange(onStoreChange);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n [system],\n );\n\n const getSnapshot = useCallback(() => {\n return system.explain(requirementId);\n }, [system, requirementId]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n// ConstraintInfo is imported from ./shared.js and re-exported above\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): ConstraintInfo[];\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): ConstraintInfo | null;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n assertSystem(\"useConstraintStatus\", system);\n const inspectState = useInspect(system);\n\n return useMemo(() => {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return inspection.constraints.find((c) => c.id === constraintId) ?? null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [system, constraintId, inspectState]);\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\n/** Result of useOptimisticUpdate */\nexport interface OptimisticUpdateResult {\n /** Apply an optimistic update (saves snapshot, then runs updateFn in batch) */\n mutate: (updateFn: () => void) => void;\n /** Whether a resolver is currently processing the optimistic change */\n isPending: boolean;\n /** Error if the resolver failed */\n error: Error | null;\n /** Manually rollback to the pre-mutation snapshot */\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n *\n * @example\n * ```tsx\n * const { mutate, isPending, error, rollback } = useOptimisticUpdate(\n * system, statusPlugin, \"SAVE_ITEM\"\n * );\n * mutate(() => { system.facts.items = [...system.facts.items, newItem]; });\n * ```\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const snapshotRef = useRef<SystemSnapshot | null>(null);\n\n const rollback = useCallback(() => {\n if (snapshotRef.current) {\n system.restore(snapshotRef.current);\n snapshotRef.current = null;\n }\n setIsPending(false);\n setError(null);\n }, [system]);\n\n const mutate = useCallback(\n (updateFn: () => void) => {\n snapshotRef.current = system.getSnapshot();\n setIsPending(true);\n setError(null);\n system.batch(updateFn);\n },\n [system],\n );\n\n // Watch for resolver completion/failure\n useEffect(() => {\n if (!statusPlugin || !requirementType || !isPending) return;\n\n return statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n // Resolved successfully — keep optimistic state\n snapshotRef.current = null;\n setIsPending(false);\n } else if (status.hasError) {\n // Failed — rollback\n setError(status.lastError);\n rollback();\n }\n });\n }, [statusPlugin, requirementType, isPending, rollback]);\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// DirectiveHydrator + useHydratedSystem — SSR/RSC hydration\n// ============================================================================\n\n/** Props for DirectiveHydrator component */\nexport interface HydratorProps {\n snapshot: DistributableSnapshot;\n children: ReactNode;\n}\n\n/** Context for hydrated snapshot */\nconst HydrationContext = createContext<DistributableSnapshot | null>(null);\n\n/**\n * SSR/RSC hydration component. Wraps children with a snapshot context\n * that `useHydratedSystem` can consume on the client.\n *\n * @example\n * ```tsx\n * // Server component\n * <DirectiveHydrator snapshot={serverSnapshot}>\n * <ClientApp />\n * </DirectiveHydrator>\n * ```\n */\nexport function DirectiveHydrator({ snapshot, children }: HydratorProps) {\n return (\n <HydrationContext.Provider value={snapshot}>\n {children}\n </HydrationContext.Provider>\n );\n}\n\n/**\n * Client-side hook that creates a system hydrated from a server snapshot.\n * Must be used inside a `<DirectiveHydrator>`.\n *\n * @example\n * ```tsx\n * function ClientApp() {\n * const system = useHydratedSystem(counterModule);\n * const count = useFact(system, \"count\");\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useHydratedSystem<S extends ModuleSchema>(\n moduleDef: ModuleDef<S>,\n config?: DirectiveRefBaseConfig,\n): SingleModuleSystem<S> {\n const snapshot = useContext(HydrationContext);\n\n // Merge snapshot data as initial facts via shared adapter utility\n const mergedConfig = useMemo(() => {\n const mergedFacts = mergeHydrationFacts(snapshot, config?.initialFacts);\n\n return {\n ...(config ?? {}),\n initialFacts: mergedFacts,\n };\n }, [snapshot, config]);\n\n return useDirectiveRef(moduleDef, mergedConfig) as SingleModuleSystem<S>;\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\n/**\n * Creates pre-typed versions of the core hooks for a specific module schema.\n * Eliminates the need to pass type parameters on every hook call.\n *\n * @example\n * ```tsx\n * const { useFact, useDerived, useDispatch, useEvents, useWatch } = createTypedHooks<typeof counterModule.schema>();\n *\n * // No type parameters needed — schema is baked in\n * function Counter({ system }: { system: SingleModuleSystem<CounterSchema> }) {\n * const count = useFact(system, \"count\");\n * const doubled = useDerived(system, \"doubled\");\n * const dispatch = useDispatch(system);\n * }\n * ```\n */\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => InferFacts<M>[K] | undefined;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => InferDerivations<M>[K];\n useDispatch: (\n system: SingleModuleSystem<M>,\n ) => (event: InferEvents<M>) => void;\n useEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>[\"events\"];\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) => void;\n} {\n return {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for internal call\n useFact(system as SingleModuleSystem<any>, factKey) as\n | InferFacts<M>[K]\n | undefined,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for internal call\n useDerived(\n system as SingleModuleSystem<any>,\n derivationId,\n ) as InferDerivations<M>[K],\n useDispatch: (system: SingleModuleSystem<M>) => useDispatch<M>(system),\n useEvents: (system: SingleModuleSystem<M>) => useEvents<M>(system),\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for internal call\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useQuerySystem — Stable query system with lifecycle management\n// ============================================================================\n\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nlet _createQuerySystem: ((config: Record<string, unknown>) => any) | null =\n null;\n\nfunction getCreateQuerySystem() {\n if (!_createQuerySystem) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@directive-run/query\");\n _createQuerySystem = mod.createQuerySystem;\n } catch {\n throw new Error(\n \"[Directive] @directive-run/query is not installed. \" +\n \"Install it with: pnpm add @directive-run/query\",\n );\n }\n }\n\n return _createQuerySystem!;\n}\n\n/**\n * React hook to create and manage a query system with proper lifecycle.\n *\n * Accepts either a config object or a factory function:\n * - Config object: calls `createQuerySystem` from `@directive-run/query` automatically\n * - Factory function: calls the factory to create the system (for custom setups)\n *\n * Creates the system once, starts on mount, destroys on unmount.\n * Handles Strict Mode re-creation and SSR safety.\n *\n * @example\n * ```tsx\n * import { useQuerySystem, useDerived } from \"@directive-run/react\";\n *\n * function App() {\n * const app = useQuerySystem({\n * facts: { userId: \"\" },\n * queries: {\n * user: {\n * key: (f) => f.userId ? { userId: f.userId } : null,\n * fetcher: async (p, signal) => {\n * const res = await fetch(`/api/users/${p.userId}`, { signal });\n * return res.json();\n * },\n * },\n * },\n * });\n *\n * const user = useDerived(app, \"user\");\n *\n * return <div>{user.data?.name}</div>;\n * }\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: System type varies based on config\nexport function useQuerySystem<\n T extends {\n start: () => void;\n destroy: () => void;\n isRunning?: boolean;\n [key: string]: any;\n },\n>(config: Record<string, unknown>): T {\n const configRef = useRef(config);\n\n const factory = useMemo(() => {\n const createQuerySystem = getCreateQuerySystem();\n\n return () => {\n return createQuerySystem(configRef.current) as T;\n };\n }, []);\n\n const systemRef = useRef<T | null>(null);\n const factoryRef = useRef(factory);\n factoryRef.current = factory;\n\n if (!systemRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n useEffect(() => {\n // Strict mode re-mount: system was destroyed in cleanup, recreate\n if (!systemRef.current && factoryRef.current) {\n systemRef.current = factoryRef.current();\n }\n\n // Start on mount (SSR safety: only start in browser)\n if (\n typeof window !== \"undefined\" &&\n systemRef.current &&\n !systemRef.current.isRunning\n ) {\n systemRef.current.start();\n }\n\n return () => {\n // RFC 0009 follow-up (R18 Tier 2-B): destroyAsync so source\n // unsubscribes complete; fire-and-forget with swallow-catch.\n systemRef.current?.destroyAsync().catch((err: unknown) => {\n if (isDevelopment)\n console.warn(\n \"[Directive] destroyAsync rejected during unmount:\",\n err,\n );\n });\n systemRef.current = null;\n };\n }, []);\n\n return systemRef.current!;\n}\n\n// ============================================================================\n// useSuspenseQuery — Suspense + Error Boundary integration for queries\n// ============================================================================\n\n// Cache of pending promises per system+key to ensure stable references across renders\nconst suspensePromiseCache = new WeakMap<\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n any,\n Map<string, { promise: Promise<void>; resolve: () => void }>\n>();\n\n/**\n * React hook for reading query data with Suspense support.\n *\n * Throws a Promise while the query is pending (triggers Suspense fallback).\n * Throws the error if the query fails (triggers error boundary).\n * Returns the data directly when available – no isPending/isError checks needed.\n *\n * @example\n * ```tsx\n * import { useSuspenseQuery } from \"@directive-run/react\";\n *\n * function UserProfile({ system }) {\n * const user = useSuspenseQuery(system, \"user\");\n * return <h1>{user.name}</h1>;\n * }\n *\n * <Suspense fallback={<Spinner />}>\n * <ErrorBoundary>\n * <UserProfile system={system} />\n * </ErrorBoundary>\n * </Suspense>\n * ```\n */\nexport function useSuspenseQuery<T = unknown>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n queryName: string,\n): T {\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n return system.subscribe([queryName], onStoreChange);\n },\n [system, queryName],\n );\n\n const getSnapshot = useCallback(() => {\n return system.read(queryName);\n }, [system, queryName]);\n\n // biome-ignore lint/suspicious/noExplicitAny: ResourceState shape checked at runtime\n const state = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getSnapshot,\n ) as any;\n\n // Get or create the promise cache for this system\n if (!suspensePromiseCache.has(system)) {\n suspensePromiseCache.set(system, new Map());\n }\n const cache = suspensePromiseCache.get(system)!;\n\n // Success – clean up promise cache and return data directly\n if (state?.status === \"success\" && state?.data !== null) {\n if (cache.has(queryName)) {\n const entry = cache.get(queryName)!;\n entry.resolve();\n cache.delete(queryName);\n }\n\n return state.data as T;\n }\n\n // Error – clean up and throw for error boundary\n if (state?.status === \"error\" && state?.error) {\n if (cache.has(queryName)) {\n const entry = cache.get(queryName)!;\n entry.resolve();\n cache.delete(queryName);\n }\n\n throw state.error;\n }\n\n // Pending – throw a promise for Suspense\n if (!cache.has(queryName)) {\n let resolvePromise: () => void;\n const promise = new Promise<void>((resolve) => {\n resolvePromise = resolve;\n });\n cache.set(queryName, { promise, resolve: resolvePromise! });\n\n // Subscribe to resolve the promise when state changes\n const unsub = system.subscribe([queryName], () => {\n // biome-ignore lint/suspicious/noExplicitAny: ResourceState checked at runtime\n const updated = system.read(queryName) as any;\n if (updated?.status === \"success\" || updated?.status === \"error\") {\n const entry = cache.get(queryName);\n if (entry) {\n entry.resolve();\n cache.delete(queryName);\n }\n unsub();\n }\n });\n }\n\n throw cache.get(queryName)!.promise;\n}\n\n// ============================================================================\n// createDirectiveContext — React Context provider pattern\n// ============================================================================\n\n/**\n * Create a React context for a Directive system, eliminating prop-drilling.\n *\n * Returns a Provider component and context-bound hooks that automatically\n * use the system from context — no need to pass `system` to every hook.\n *\n * **Note:** The returned hooks (e.g., `Counter.useFact(\"count\")`) follow React\n * hook rules but eslint-plugin-react-hooks may not recognize them as hooks since\n * they're object methods. This is the same pattern used by XState's\n * `createActorContext`. Suppress with `// eslint-disable-next-line react-hooks/rules-of-hooks`\n * if your linter flags it.\n *\n * @example\n * ```tsx\n * const Counter = createDirectiveContext(counterSystem);\n *\n * function App() {\n * return (\n * <Counter.Provider>\n * <Display />\n * </Counter.Provider>\n * );\n * }\n *\n * function Display() {\n * const count = Counter.useFact(\"count\");\n * const doubled = Counter.useDerived(\"doubled\");\n * const events = Counter.useEvents();\n * return <button onClick={() => events.increment()}>{count} ({doubled})</button>;\n * }\n * ```\n */\nexport function createDirectiveContext<M extends ModuleSchema>(\n system: SingleModuleSystem<M>,\n) {\n const Ctx = createContext<SingleModuleSystem<M> | null>(null);\n\n function useSystem(): SingleModuleSystem<M> {\n const sys = useContext(Ctx);\n if (!sys) {\n throw new Error(\n \"[Directive] useSystem called outside of <Provider>. Wrap your component tree with the Provider from createDirectiveContext().\",\n );\n }\n\n return sys;\n }\n\n function Provider({\n children,\n system: overrideSystem,\n }: {\n children: ReactNode;\n /** Override the system for testing or conditional logic. */\n system?: SingleModuleSystem<M>;\n }) {\n return (\n <Ctx.Provider value={overrideSystem ?? system}>{children}</Ctx.Provider>\n );\n }\n\n Provider.displayName = \"DirectiveProvider\";\n\n return {\n /** Wrap your component tree to provide the system via context. */\n Provider,\n\n /** Get the underlying system instance from context. */\n useSystem,\n\n /** Read a fact value (reactive — re-renders on change). */\n useFact: <K extends keyof InferFacts<M> & string>(factKey: K) =>\n // biome-ignore lint/suspicious/noExplicitAny: Internal type narrowing\n useFact(useSystem() as SingleModuleSystem<any>, factKey) as\n | InferFacts<M>[K]\n | undefined,\n\n /** Read a derived value (reactive — re-renders on change). */\n useDerived: <K extends keyof InferDerivations<M> & string>(\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Internal type narrowing\n useDerived(\n useSystem() as SingleModuleSystem<any>,\n derivationId,\n ) as InferDerivations<M>[K],\n\n /** Get the typed events accessor. */\n useEvents: () => useEvents<M>(useSystem()),\n\n /** Get a dispatch function for raw events. */\n useDispatch: () => useDispatch<M>(useSystem()),\n\n /** Run a selector with auto-tracked dependencies. */\n useSelector: <R,>(\n selector: (state: InferSelectorState<M>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Internal type narrowing\n useSelector(useSystem() as any, selector as any, equalityFn) as R,\n\n /** Watch a key and call a callback on change. */\n useWatch: <K extends string>(\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) => useWatch(useSystem(), key, callback),\n\n /** Fire a system event on an interval while a predicate returns true. */\n useTickWhile: (\n predicate: (system: SingleModuleSystem<M>) => boolean,\n eventName: keyof M[\"events\"] & string,\n intervalMs: number,\n ) => useTickWhile<M>(useSystem(), predicate, eventName, intervalMs),\n\n /** Get the current inspection state. */\n useInspect: () => useInspect(useSystem()),\n\n /** Explain a requirement. */\n useExplain: (requirementId: string) =>\n useExplain(useSystem(), requirementId),\n\n /** Get history state. */\n useHistory: () => useHistory(useSystem()),\n };\n}\n"]}