@directive-run/svelte 0.8.2 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +5 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +46 -14
- package/dist/index.d.ts +46 -14
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/LICENSE
CHANGED
|
@@ -2,6 +2,11 @@ MIT License
|
|
|
2
2
|
|
|
3
3
|
Copyright (c) 2026 Sizls LLC
|
|
4
4
|
|
|
5
|
+
This project is dual-licensed under MIT OR Apache-2.0. You may choose
|
|
6
|
+
either license. See LICENSE-APACHE for the Apache License, Version 2.0.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
5
10
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
11
|
of this software and associated documentation files (the "Software"), to deal
|
|
7
12
|
in the Software without restriction, including without limitation the rights
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils'),svelte=require('svelte'),store=require('svelte/store');function
|
|
1
|
+
'use strict';var core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils'),svelte=require('svelte'),store=require('svelte/store');function E(e,t){return process.env.NODE_ENV!=="production"&&e.read(t)===void 0&&console.warn(`[Directive] createDerivedStore("${t}") returned undefined. Check that "${t}" is defined in your module's derive property.`),store.readable(e.read(t),n=>e.subscribe([t],()=>{n(e.read(t));}))}function C(e,t){let n=()=>{let s={};for(let r of t)s[r]=e.read(r);return s};return store.readable(n(),s=>e.subscribe(t,()=>{s(n());}))}function T(e,t){return process.env.NODE_ENV!=="production"&&(e.facts.$store.has(t)||console.warn(`[Directive] createFactStore("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`)),store.readable(e.facts.$store.get(t),n=>e.facts.$store.subscribe([t],()=>{n(e.facts.$store.get(t));}))}function _(e){return store.readable(e.inspect(),t=>{let n=()=>t(e.inspect()),s=e.facts.$store.subscribeAll(n),r=e.onSettledChange(n);return ()=>{s(),r();}})}function V(e,t){return adapterUtils.assertSystem("useFact",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useFact() received a function. Did you mean useSelector()? useFact() takes a string key or array of keys, not a selector function."),Array.isArray(t)?$(e,t):T(e,t)}function $(e,t){let n=()=>{let s={};for(let r of t)s[r]=e.facts.$store.get(r);return s};return store.readable(n(),s=>e.facts.$store.subscribe(t,()=>{s(n());}))}function P(e,t){return adapterUtils.assertSystem("useDerived",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useDerived() received a function. Did you mean useSelector()? useDerived() takes a string key or array of keys, not a selector function."),Array.isArray(t)?C(e,t):E(e,t)}function B(e,t,n=adapterUtils.defaultEquality){adapterUtils.assertSystem("useSelector",e);let s=new Set(Object.keys(e.derive??{})),r=()=>adapterUtils.runTrackedSelector(e,s,t),o=r();return store.readable(o.value,l=>{let g=o.value,p=o.factKeys,S=o.deriveKeys,d=[],y=()=>{for(let c of d)c();d.length=0;let f=()=>{let c=r();n(g,c.value)||(g=c.value,l(c.value)),adapterUtils.depsChanged(p,c.factKeys,S,c.deriveKeys)&&(p=c.factKeys,S=c.deriveKeys,y());};p.length>0?d.push(e.facts.$store.subscribe(p,f)):S.length===0&&d.push(e.facts.$store.subscribeAll(f)),S.length>0&&d.push(e.subscribe(S,f));};return y(),()=>{for(let f of d)f();}})}function j(e){return adapterUtils.assertSystem("useDispatch",e),t=>{e.dispatch(t);}}function q(e){return adapterUtils.assertSystem("useEvents",e),e.events}function A(e,t,n){adapterUtils.assertSystem("useWatch",e);let s=e.watch(t,n);svelte.onDestroy(s);}function z(e,t){return adapterUtils.assertSystem("useInspect",e),t?.throttleMs&&t.throttleMs>0?store.readable(adapterUtils.computeInspectState(e),n=>{let{throttled:s,cleanup:r}=adapterUtils.createThrottle(()=>{n(adapterUtils.computeInspectState(e));},t.throttleMs),o=e.facts.$store.subscribeAll(s),l=e.onSettledChange(s);return ()=>{r(),o(),l();}}):store.readable(adapterUtils.computeInspectState(e),n=>{let s=()=>n(adapterUtils.computeInspectState(e)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function L(e,t){if(Array.isArray(t)){let n=()=>{let s={};for(let r of t)s[r]=e.getStatus(r);return s};return store.readable(n(),s=>e.subscribe(()=>{s(n());}))}return store.readable(e.getStatus(t),n=>e.subscribe(()=>{n(e.getStatus(t));}))}function Q(e,t){return adapterUtils.assertSystem("useExplain",e),store.readable(e.explain(t),n=>{let s=()=>n(e.explain(t)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function G(e,t){return adapterUtils.assertSystem("useConstraintStatus",e),store.readable(x(e,t),n=>{let s=()=>n(x(e,t)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function x(e,t){let n=e.inspect();return t?n.constraints.find(s=>s.id===t)??null:n.constraints}function J(e,t,n){adapterUtils.assertSystem("useOptimisticUpdate",e);let s=false,r=null,o=null,l=null,g=new Set,p=new Set,S={subscribe(u){return u(s),g.add(u),()=>g.delete(u)}},d={subscribe(u){return u(r),p.add(u),()=>p.delete(u)}},y=u=>{s=u;for(let M of g)M(u);},f=u=>{r=u;for(let M of p)M(u);},c=()=>{o&&(e.restore(o),o=null),y(false),f(null),l?.(),l=null;},a=u=>{o=e.getSnapshot(),y(true),f(null),e.batch(u),t&&n&&(l?.(),l=t.subscribe(()=>{let M=t.getStatus(n);!M.isLoading&&!M.hasError?(o=null,y(false),l?.(),l=null):M.hasError&&(f(M.lastError),c());}));};return svelte.onDestroy(()=>{l?.();}),{mutate:a,isPending:S,error:d,rollback:c}}function X(e){return adapterUtils.assertSystem("useHistory",e),store.readable(adapterUtils.buildHistoryState(e),t=>e.onHistoryChange(()=>t(adapterUtils.buildHistoryState(e))))}function Y(e,t){let n=[...t?.plugins??[]],s;if(t?.status){let a=core.createRequirementStatusPlugin();s=a,n.push(a.plugin);}let r=core.createSystem({module:e,plugins:n.length>0?n:void 0,trace:t?.trace,errorBoundary:t?.errorBoundary,tickMs:t?.tickMs,zeroConfig:t?.zeroConfig,initialFacts:t?.initialFacts});typeof window<"u"?r.start():r.initialize(),svelte.onDestroy(()=>{r.destroy();});let o=t?.facts,l=t?.derived,g=!o&&!l,p=g?store.readable(r.facts.$store.toObject(),a=>r.facts.$store.subscribeAll(()=>{a(r.facts.$store.toObject());})):store.readable(adapterUtils.pickFacts(r,o??[]),a=>!o||o.length===0?()=>{}:r.facts.$store.subscribe(o,()=>{a(adapterUtils.pickFacts(r,o));})),S=g?Object.keys(r.derive??{}):l??[],d=()=>{let a={};for(let u of S)a[u]=r.read(u);return a},y=S.length>0?store.readable(d(),a=>r.subscribe(S,()=>{a(d());})):store.readable(d(),()=>()=>{}),f=r.events;return {system:r,facts:p,derived:y,events:f,dispatch:a=>r.dispatch(a),statusPlugin:s}}function Z(){return {useFact:(e,t)=>V(e,t),useDerived:(e,t)=>P(e,t),useDispatch:e=>t=>{e.dispatch(t);},useEvents:e=>q(e),useWatch:(e,t,n)=>A(e,t,n)}}function ee(e,t,n){return store.readable(n(e),s=>e.subscribe(t,()=>{s(n(e));}))}function te(e){let t=e();return typeof window<"u"&&!t.isRunning&&t.start(),svelte.onDestroy(()=>{t.destroy();}),t}Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return adapterUtils.shallowEqual}});exports.createDerivedStore=E;exports.createDerivedsStore=C;exports.createFactStore=T;exports.createInspectStore=_;exports.createTypedHooks=Z;exports.useConstraintStatus=G;exports.useDerived=P;exports.useDirective=Y;exports.useDispatch=j;exports.useEvents=q;exports.useExplain=Q;exports.useFact=V;exports.useHistory=X;exports.useInspect=z;exports.useNamespacedSelector=ee;exports.useOptimisticUpdate=J;exports.useQuerySystem=te;exports.useRequirementStatus=L;exports.useSelector=B;exports.useWatch=A;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["createDerivedStore","system","derivationId","readable","set","createDerivedsStore","derivationIds","getValues","result","id","createFactStore","factKey","createInspectStore","update","unsubFacts","unsubSettled","useFact","keyOrKeys","assertSystem","_useFactMulti","factKeys","key","useDerived","idOrIds","useSelector","selector","equalityFn","defaultEquality","deriveKeySet","runWithTracking","runTrackedSelector","initial","currentSelected","trackedFactKeys","trackedDeriveKeys","unsubs","resubscribe","unsub","onUpdate","depsChanged","useDispatch","event","useEvents","useWatch","callback","unsubscribe","onDestroy","useInspect","options","computeInspectState","throttled","cleanup","createThrottle","useRequirementStatus","statusPlugin","typeOrTypes","type","useExplain","requirementId","useConstraintStatus","constraintId","_getConstraintValue","inspection","c","useOptimisticUpdate","requirementType","isPendingValue","errorValue","snapshot","statusUnsub","pendingSubscribers","errorSubscribers","isPending","fn","error","setPending","v","setError","rollback","mutate","updateFn","status","useHistory","buildHistoryState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks","useNamespacedSelector","keys"],"mappings":"sKA+DO,SAASA,CAAAA,CAEdC,CAAAA,CACAC,EACa,CACb,OAAI,OAAA,CAAQ,GAAA,CAAI,WAAa,YAAA,EACND,CAAAA,CAAO,IAAA,CAAKC,CAAY,IACxB,MAAA,EACnB,OAAA,CAAQ,IAAA,CACN,CAAA,gCAAA,EAAmCA,CAAY,CAAA,mCAAA,EAC9BA,CAAY,gDAC/B,CAAA,CAIGC,cAAAA,CAAYF,EAAO,IAAA,CAAKC,CAAY,CAAA,CAASE,CAAAA,EAC9BH,EAAO,SAAA,CAAU,CAACC,CAAY,CAAA,CAAG,IAAM,CACzDE,CAA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ACa,CACb,OAAOtB,eAAYsB,CAAAA,CAASxB,CAAM,CAAA,CAAIG,CAAAA,EAChBH,EAAO,SAAA,CAAUoG,CAAAA,CAAM,IAAM,CAC/CjG,EAAIqB,CAAAA,CAASxB,CAAM,CAAC,EACtB,CAAC,CAGF,CACH","file":"index.cjs","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n TraceOption,\n ErrorBoundaryConfig,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemInspection,\n SystemSnapshot,\n HistoryState,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { onDestroy } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationId: string,\n): Readable<T> {\n if (process.env.NODE_ENV !== \"production\") {\n const initialValue = system.read(derivationId);\n if (initialValue === undefined) {\n console.warn(\n `[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n return readable<T>(system.read(derivationId) as T, (set) => {\n const unsubscribe = system.subscribe([derivationId], () => {\n set(system.read(derivationId) as T);\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Readable<T> {\n const getValues = (): T => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n return result as T;\n };\n\n return readable<T>(getValues(), (set) => {\n const unsubscribe = system.subscribe(derivationIds, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n factKey: string,\n): Readable<T | undefined> {\n if (process.env.NODE_ENV !== \"production\") {\n if (!system.facts.$store.has(factKey)) {\n console.warn(\n `[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n return readable<T | undefined>(\n system.facts.$store.get(factKey) as T | undefined,\n (set) => {\n const unsubscribe = system.facts.$store.subscribe([factKey], () => {\n set(system.facts.$store.get(factKey) as T | undefined);\n });\n return unsubscribe;\n },\n );\n}\n\n/**\n * Create a Svelte store for system inspection data.\n * NOTE: This updates on every fact change. Use sparingly in production.\n */\nexport function createInspectStore(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n return readable<SystemInspection>(system.inspect(), (set) => {\n const update = () => set(system.inspect());\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\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>(\n system: SingleModuleSystem<S>,\n factKey: K,\n): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKeys: K[],\n): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): Readable<unknown> {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFactMulti(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Readable<Record<string, unknown>> {\n const getValues = (): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n set(getValues());\n });\n return unsubscribe;\n });\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>(\n system: SingleModuleSystem<S>,\n derivationId: K,\n): Readable<InferDerivations<S>[K]>;\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): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n idOrIds: string | string[],\n): Readable<unknown> {\n assertSystem(\"useDerived\", system);\n if (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"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(idOrIds)) {\n return createDerivedsStore(system, idOrIds);\n }\n\n // Single key path\n return createDerivedStore(system, idOrIds);\n}\n\n// ============================================================================\n// useSelector — auto-tracking selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations.\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys.\n */\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n equalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n assertSystem(\"useSelector\", system);\n const deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const runWithTracking = () =>\n runTrackedSelector(system, deriveKeySet, selector);\n\n const initial = runWithTracking();\n\n return readable(initial.value, (set) => {\n let currentSelected = initial.value;\n let trackedFactKeys = initial.factKeys;\n let trackedDeriveKeys = initial.deriveKeys;\n const unsubs: Array<() => void> = [];\n\n const resubscribe = () => {\n for (const unsub of unsubs) unsub();\n unsubs.length = 0;\n\n const onUpdate = () => {\n const result = runWithTracking();\n if (!equalityFn(currentSelected, result.value)) {\n currentSelected = result.value;\n set(result.value);\n }\n // Re-track: check if deps changed\n if (\n depsChanged(\n trackedFactKeys,\n result.factKeys,\n trackedDeriveKeys,\n result.deriveKeys,\n )\n ) {\n trackedFactKeys = result.factKeys;\n trackedDeriveKeys = result.deriveKeys;\n resubscribe();\n }\n };\n\n if (trackedFactKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n } else if (trackedDeriveKeys.length === 0) {\n unsubs.push(system.facts.$store.subscribeAll(onUpdate));\n }\n if (trackedDeriveKeys.length > 0) {\n unsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n });\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 (event: InferEvents<S>) => {\n system.dispatch(event);\n };\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher.\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return system.events;\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect\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 previousValue: 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 previousValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n callback: (newValue: unknown, prevValue: unknown) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const unsubscribe = system.watch(key, callback);\n onDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n throttleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): Readable<InspectState> {\n assertSystem(\"useInspect\", system);\n if (options?.throttleMs && options.throttleMs > 0) {\n return readable<InspectState>(computeInspectState(system), (set) => {\n const { throttled, cleanup } = createThrottle(() => {\n set(computeInspectState(system));\n }, options.throttleMs!);\n\n const unsubFacts = system.facts.$store.subscribeAll(throttled);\n const unsubSettled = system.onSettledChange(throttled);\n\n return () => {\n cleanup();\n unsubFacts();\n unsubSettled();\n };\n });\n }\n\n return readable<InspectState>(computeInspectState(system), (set) => {\n const update = () => set(computeInspectState(system));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n):\n | Readable<RequirementTypeStatus>\n | Readable<Record<string, RequirementTypeStatus>> {\n if (Array.isArray(typeOrTypes)) {\n const getValues = (): Record<string, RequirementTypeStatus> => {\n const result: Record<string, RequirementTypeStatus> = {};\n for (const type of typeOrTypes) {\n result[type] = statusPlugin.getStatus(type);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(getValues());\n });\n return unsubscribe;\n });\n }\n\n return readable<RequirementTypeStatus>(\n statusPlugin.getStatus(typeOrTypes),\n (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(statusPlugin.getStatus(typeOrTypes));\n });\n return unsubscribe;\n },\n );\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): Readable<string | null> {\n assertSystem(\"useExplain\", system);\n return readable<string | null>(system.explain(requirementId), (set) => {\n const update = () => set(system.explain(requirementId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): Readable<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): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n assertSystem(\"useConstraintStatus\", system);\n return readable<ConstraintInfo[] | ConstraintInfo | null>(\n _getConstraintValue(system, constraintId),\n (set) => {\n const update = () => set(_getConstraintValue(system, constraintId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n );\n}\n\nfunction _getConstraintValue(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return (\n inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ??\n null\n );\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n mutate: (updateFn: () => void) => void;\n isPending: Readable<boolean>;\n error: Readable<Error | null>;\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 */\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 let isPendingValue = false;\n let errorValue: Error | null = null;\n let snapshot: SystemSnapshot | null = null;\n let statusUnsub: (() => void) | null = null;\n\n // We track subscribers manually since we need imperative push\n const pendingSubscribers = new Set<(v: boolean) => void>();\n const errorSubscribers = new Set<(v: Error | null) => void>();\n\n const isPending: Readable<boolean> = {\n subscribe(fn) {\n fn(isPendingValue);\n pendingSubscribers.add(fn);\n return () => pendingSubscribers.delete(fn);\n },\n };\n\n const error: Readable<Error | null> = {\n subscribe(fn) {\n fn(errorValue);\n errorSubscribers.add(fn);\n return () => errorSubscribers.delete(fn);\n },\n };\n\n const setPending = (v: boolean) => {\n isPendingValue = v;\n for (const fn of pendingSubscribers) fn(v);\n };\n\n const setError = (v: Error | null) => {\n errorValue = v;\n for (const fn of errorSubscribers) fn(v);\n };\n\n const rollback = () => {\n if (snapshot) {\n system.restore(snapshot);\n snapshot = null;\n }\n setPending(false);\n setError(null);\n statusUnsub?.();\n statusUnsub = null;\n };\n\n const mutate = (updateFn: () => void) => {\n snapshot = system.getSnapshot();\n setPending(true);\n setError(null);\n system.batch(updateFn);\n\n if (statusPlugin && requirementType) {\n statusUnsub?.();\n statusUnsub = statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n snapshot = null;\n setPending(false);\n statusUnsub?.();\n statusUnsub = null;\n } else if (status.hasError) {\n setError(status.lastError);\n rollback();\n }\n });\n }\n };\n\n onDestroy(() => {\n statusUnsub?.();\n });\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useHistory — reactive history store\n// ============================================================================\n\n/**\n * Reactive history Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const history = useHistory(system);\n * <button disabled={!$history?.canGoBack} on:click={() => $history?.goBack()}>Undo</button>\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): Readable<HistoryState | null> {\n assertSystem(\"useHistory\", system);\n return readable<HistoryState | null>(\n buildHistoryState(system),\n (set) => {\n return system.onHistoryChange(() => set(buildHistoryState(system)));\n },\n );\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\ninterface UseDirectiveConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\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 status?: boolean;\n /** Fact keys to subscribe to (omit for all) */\n facts?: string[];\n /** Derivation keys to subscribe to (omit for all) */\n derived?: string[];\n}\n\n/**\n * Create a scoped Directive system with automatic lifecycle management.\n * When no `facts` or `derived` keys are specified, subscribes to ALL\n * facts and derivations and returns Svelte readable stores.\n *\n * @example\n * ```svelte\n * // Subscribe to everything\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n *\n * // Selective keys\n * const { facts, derived } = useDirective(counterModule, { facts: [\"count\"], derived: [\"doubled\"] });\n * ```\n */\nexport function useDirective<M extends ModuleSchema>(\n moduleDef: ModuleDef<M>,\n config?: UseDirectiveConfig,\n) {\n const allPlugins = [...(config?.plugins ?? [])];\n let statusPlugin: StatusPlugin | undefined;\n\n if (config?.status) {\n const sp = createRequirementStatusPlugin();\n statusPlugin = sp;\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins.push(sp.plugin as Plugin<any>);\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: moduleDef,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n trace: config?.trace,\n errorBoundary: config?.errorBoundary,\n tickMs: config?.tickMs,\n zeroConfig: config?.zeroConfig,\n initialFacts: config?.initialFacts,\n } as any) as unknown as SingleModuleSystem<M>;\n\n system.start();\n\n onDestroy(() => {\n system.destroy();\n });\n\n const factKeys = config?.facts;\n const derivedKeys = config?.derived;\n const subscribeAll = !factKeys && !derivedKeys;\n\n // Subscribe to facts\n const factsStore: Readable<InferFacts<M>> = subscribeAll\n ? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n return system.facts.$store.subscribeAll(() => {\n set(system.facts.$store.toObject() as InferFacts<M>);\n });\n })\n : readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n if (!factKeys || factKeys.length === 0) return () => {};\n return system.facts.$store.subscribe(factKeys, () => {\n set(pickFacts(system, factKeys) as InferFacts<M>);\n });\n });\n\n // Subscribe to derivations\n const allDerivationKeys = subscribeAll\n ? Object.keys(system.derive ?? {})\n : (derivedKeys ?? []);\n const getDerived = (): InferDerivations<M> => {\n const result: Record<string, unknown> = {};\n for (const key of allDerivationKeys) {\n result[key] = system.read(key);\n }\n return result as InferDerivations<M>;\n };\n const derivedStore: Readable<InferDerivations<M>> =\n allDerivationKeys.length > 0\n ? readable(getDerived(), (set) => {\n return system.subscribe(allDerivationKeys, () => {\n set(getDerived());\n });\n })\n : readable(getDerived(), () => () => {});\n\n const events = system.events;\n const dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n return {\n system,\n facts: factsStore,\n derived: derivedStore,\n events,\n dispatch,\n statusPlugin,\n };\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => Readable<InferFacts<M>[K] | undefined>;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => Readable<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: Cast for overload compatibility\n useFact(system as SingleModuleSystem<any>, factKey) as Readable<\n InferFacts<M>[K] | undefined\n >,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useDerived(system as SingleModuleSystem<any>, derivationId) as Readable<\n InferDerivations<M>[K]\n >,\n useDispatch: (system: SingleModuleSystem<M>) => {\n return (event: InferEvents<M>) => {\n system.dispatch(event);\n };\n },\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: Cast for overload compatibility\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem\n// ============================================================================\n\n/**\n * Svelte readable store that selects from a NamespacedSystem.\n * Subscribes to specified keys and provides reactive updates.\n *\n * @param system - The namespaced system\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 * ```svelte\n * const token$ = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): Readable<R> {\n return readable<R>(selector(system), (set) => {\n const unsubscribe = system.subscribe(keys, () => {\n set(selector(system));\n });\n\n return unsubscribe;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["createDerivedStore","system","derivationId","readable","set","createDerivedsStore","derivationIds","getValues","result","id","createFactStore","factKey","createInspectStore","update","unsubFacts","unsubSettled","useFact","keyOrKeys","assertSystem","_useFactMulti","factKeys","key","useDerived","idOrIds","useSelector","selector","equalityFn","defaultEquality","deriveKeySet","runWithTracking","runTrackedSelector","initial","currentSelected","trackedFactKeys","trackedDeriveKeys","unsubs","resubscribe","unsub","onUpdate","depsChanged","useDispatch","event","useEvents","useWatch","callback","unsubscribe","onDestroy","useInspect","options","computeInspectState","throttled","cleanup","createThrottle","useRequirementStatus","statusPlugin","typeOrTypes","type","useExplain","requirementId","useConstraintStatus","constraintId","_getConstraintValue","inspection","c","useOptimisticUpdate","requirementType","isPendingValue","errorValue","snapshot","statusUnsub","pendingSubscribers","errorSubscribers","isPending","fn","error","setPending","v","setError","rollback","mutate","updateFn","status","useHistory","buildHistoryState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks","useNamespacedSelector","keys","useQuerySystem","factory"],"mappings":"sKA+DO,SAASA,EAEdC,CAAAA,CACAC,CAAAA,CACa,CACb,OAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,GAAa,cACND,CAAAA,CAAO,IAAA,CAAKC,CAAY,CAAA,GACxB,QACnB,OAAA,CAAQ,IAAA,CACN,CAAA,gCAAA,EAAmCA,CAAY,sCAC9BA,CAAY,CAAA,8CAAA,CAC/B,EAIGC,cAAAA,CAAYF,CAAAA,CAAO,KAAKC,CAAY,CAAA,CAASE,CAAAA,EAC9BH,CAAAA,CAAO,UAAU,CAACC,CAAY,EAAG,IAAM,CACzDE,EAAIH,CAAAA,CAAO,IAAA,CAAKC,CAAY,CAAM,EACpC,CAAC,CAEF,CACH,CAKO,SAASG,EAEdJ,CAAAA,CACAK,CAAAA,CACa,CACb,IAAMC,EAAY,IAAS,CACzB,IAAMC,CAAAA,CAAkC,EAAC,CACzC,IAAA,IAAWC,CAAAA,IAAMH,CAAAA,CACfE,EAAOC,CAAE,CAAA,CAAIR,EAAO,IAAA,CAAKQ,CAAE,EAE7B,OAAOD,CACT,CAAA,CAEA,OAAOL,eAAYI,CAAAA,EAAU,CAAIH,GACXH,CAAAA,CAAO,SAAA,CAAUK,EAAe,IAAM,CACxDF,CAAAA,CAAIG,CAAAA,EAAW,EACjB,CAAC,CAEF,CACH,CAKO,SAASG,CAAAA,CAEdT,CAAAA,CACAU,CAAAA,CACyB,CACzB,OAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,GAAa,YAAA,GACtBV,EAAO,KAAA,CAAM,MAAA,CAAO,GAAA,CAAIU,CAAO,GAClC,OAAA,CAAQ,IAAA,CACN,gCAAgCA,CAAO,CAAA,+CAAA,EACtBA,CAAO,CAAA,qCAAA,CAC1B,CAAA,CAAA,CAIGR,cAAAA,CACLF,CAAAA,CAAO,MAAM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Qf,CAAAA,CAAmCU,CAAO,EAGpD,UAAA,CAAY,CACVV,CAAAA,CACAC,CAAAA,GAGAoB,EAAWrB,CAAAA,CAAmCC,CAAY,CAAA,CAG5D,WAAA,CAAcD,GACJwC,CAAAA,EAA0B,CAChCxC,CAAAA,CAAO,QAAA,CAASwC,CAAK,EACvB,CAAA,CAEF,UAAYxC,CAAAA,EAAkCyC,CAAAA,CAAazC,CAAM,CAAA,CACjE,QAAA,CAAU,CACRA,CAAAA,CACAoB,EACAuB,CAAAA,GAGAD,CAAAA,CAAS1C,EAAmCoB,CAAAA,CAAKuB,CAAQ,CAC7D,CACF,CAmBO,SAASwD,EAAAA,CACdnG,EACAoG,CAAAA,CACA5E,CAAAA,CACa,CACb,OAAOtB,cAAAA,CAAYsB,EAASxB,CAAM,CAAA,CAAIG,CAAAA,EAChBH,CAAAA,CAAO,UAAUoG,CAAAA,CAAM,IAAM,CAC/CjG,CAAAA,CAAIqB,EAASxB,CAAM,CAAC,EACtB,CAAC,CAGF,CACH,CA+BO,SAASqG,EAAAA,CACdC,CAAAA,CACG,CACH,IAAMtG,CAAAA,CAASsG,CAAAA,EAAQ,CAEvB,OAAI,OAAO,MAAA,CAAW,KAAe,CAACtG,CAAAA,CAAO,WAC3CA,CAAAA,CAAO,KAAA,EAAM,CAGf6C,gBAAAA,CAAU,IAAM,CACd7C,CAAAA,CAAO,UACT,CAAC,EAEMA,CACT","file":"index.cjs","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n TraceOption,\n ErrorBoundaryConfig,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemInspection,\n SystemSnapshot,\n HistoryState,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { onDestroy } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationId: string,\n): Readable<T> {\n if (process.env.NODE_ENV !== \"production\") {\n const initialValue = system.read(derivationId);\n if (initialValue === undefined) {\n console.warn(\n `[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n return readable<T>(system.read(derivationId) as T, (set) => {\n const unsubscribe = system.subscribe([derivationId], () => {\n set(system.read(derivationId) as T);\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Readable<T> {\n const getValues = (): T => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n return result as T;\n };\n\n return readable<T>(getValues(), (set) => {\n const unsubscribe = system.subscribe(derivationIds, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n factKey: string,\n): Readable<T | undefined> {\n if (process.env.NODE_ENV !== \"production\") {\n if (!system.facts.$store.has(factKey)) {\n console.warn(\n `[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n return readable<T | undefined>(\n system.facts.$store.get(factKey) as T | undefined,\n (set) => {\n const unsubscribe = system.facts.$store.subscribe([factKey], () => {\n set(system.facts.$store.get(factKey) as T | undefined);\n });\n return unsubscribe;\n },\n );\n}\n\n/**\n * Create a Svelte store for system inspection data.\n * NOTE: This updates on every fact change. Use sparingly in production.\n */\nexport function createInspectStore(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n return readable<SystemInspection>(system.inspect(), (set) => {\n const update = () => set(system.inspect());\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\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>(\n system: SingleModuleSystem<S>,\n factKey: K,\n): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKeys: K[],\n): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): Readable<unknown> {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFactMulti(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Readable<Record<string, unknown>> {\n const getValues = (): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n set(getValues());\n });\n return unsubscribe;\n });\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>(\n system: SingleModuleSystem<S>,\n derivationId: K,\n): Readable<InferDerivations<S>[K]>;\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): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n idOrIds: string | string[],\n): Readable<unknown> {\n assertSystem(\"useDerived\", system);\n if (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"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(idOrIds)) {\n return createDerivedsStore(system, idOrIds);\n }\n\n // Single key path\n return createDerivedStore(system, idOrIds);\n}\n\n// ============================================================================\n// useSelector — auto-tracking selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations.\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys.\n */\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n equalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n assertSystem(\"useSelector\", system);\n const deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const runWithTracking = () =>\n runTrackedSelector(system, deriveKeySet, selector);\n\n const initial = runWithTracking();\n\n return readable(initial.value, (set) => {\n let currentSelected = initial.value;\n let trackedFactKeys = initial.factKeys;\n let trackedDeriveKeys = initial.deriveKeys;\n const unsubs: Array<() => void> = [];\n\n const resubscribe = () => {\n for (const unsub of unsubs) unsub();\n unsubs.length = 0;\n\n const onUpdate = () => {\n const result = runWithTracking();\n if (!equalityFn(currentSelected, result.value)) {\n currentSelected = result.value;\n set(result.value);\n }\n // Re-track: check if deps changed\n if (\n depsChanged(\n trackedFactKeys,\n result.factKeys,\n trackedDeriveKeys,\n result.deriveKeys,\n )\n ) {\n trackedFactKeys = result.factKeys;\n trackedDeriveKeys = result.deriveKeys;\n resubscribe();\n }\n };\n\n if (trackedFactKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n } else if (trackedDeriveKeys.length === 0) {\n unsubs.push(system.facts.$store.subscribeAll(onUpdate));\n }\n if (trackedDeriveKeys.length > 0) {\n unsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n });\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 (event: InferEvents<S>) => {\n system.dispatch(event);\n };\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher.\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return system.events;\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect\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 previousValue: 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 previousValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n callback: (newValue: unknown, prevValue: unknown) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const unsubscribe = system.watch(key, callback);\n onDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n throttleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): Readable<InspectState> {\n assertSystem(\"useInspect\", system);\n if (options?.throttleMs && options.throttleMs > 0) {\n return readable<InspectState>(computeInspectState(system), (set) => {\n const { throttled, cleanup } = createThrottle(() => {\n set(computeInspectState(system));\n }, options.throttleMs!);\n\n const unsubFacts = system.facts.$store.subscribeAll(throttled);\n const unsubSettled = system.onSettledChange(throttled);\n\n return () => {\n cleanup();\n unsubFacts();\n unsubSettled();\n };\n });\n }\n\n return readable<InspectState>(computeInspectState(system), (set) => {\n const update = () => set(computeInspectState(system));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n):\n | Readable<RequirementTypeStatus>\n | Readable<Record<string, RequirementTypeStatus>> {\n if (Array.isArray(typeOrTypes)) {\n const getValues = (): Record<string, RequirementTypeStatus> => {\n const result: Record<string, RequirementTypeStatus> = {};\n for (const type of typeOrTypes) {\n result[type] = statusPlugin.getStatus(type);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(getValues());\n });\n return unsubscribe;\n });\n }\n\n return readable<RequirementTypeStatus>(\n statusPlugin.getStatus(typeOrTypes),\n (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(statusPlugin.getStatus(typeOrTypes));\n });\n return unsubscribe;\n },\n );\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): Readable<string | null> {\n assertSystem(\"useExplain\", system);\n return readable<string | null>(system.explain(requirementId), (set) => {\n const update = () => set(system.explain(requirementId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): Readable<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): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n assertSystem(\"useConstraintStatus\", system);\n return readable<ConstraintInfo[] | ConstraintInfo | null>(\n _getConstraintValue(system, constraintId),\n (set) => {\n const update = () => set(_getConstraintValue(system, constraintId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n );\n}\n\nfunction _getConstraintValue(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return (\n inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ??\n null\n );\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n mutate: (updateFn: () => void) => void;\n isPending: Readable<boolean>;\n error: Readable<Error | null>;\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 */\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 let isPendingValue = false;\n let errorValue: Error | null = null;\n let snapshot: SystemSnapshot | null = null;\n let statusUnsub: (() => void) | null = null;\n\n // We track subscribers manually since we need imperative push\n const pendingSubscribers = new Set<(v: boolean) => void>();\n const errorSubscribers = new Set<(v: Error | null) => void>();\n\n const isPending: Readable<boolean> = {\n subscribe(fn) {\n fn(isPendingValue);\n pendingSubscribers.add(fn);\n return () => pendingSubscribers.delete(fn);\n },\n };\n\n const error: Readable<Error | null> = {\n subscribe(fn) {\n fn(errorValue);\n errorSubscribers.add(fn);\n return () => errorSubscribers.delete(fn);\n },\n };\n\n const setPending = (v: boolean) => {\n isPendingValue = v;\n for (const fn of pendingSubscribers) fn(v);\n };\n\n const setError = (v: Error | null) => {\n errorValue = v;\n for (const fn of errorSubscribers) fn(v);\n };\n\n const rollback = () => {\n if (snapshot) {\n system.restore(snapshot);\n snapshot = null;\n }\n setPending(false);\n setError(null);\n statusUnsub?.();\n statusUnsub = null;\n };\n\n const mutate = (updateFn: () => void) => {\n snapshot = system.getSnapshot();\n setPending(true);\n setError(null);\n system.batch(updateFn);\n\n if (statusPlugin && requirementType) {\n statusUnsub?.();\n statusUnsub = statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n snapshot = null;\n setPending(false);\n statusUnsub?.();\n statusUnsub = null;\n } else if (status.hasError) {\n setError(status.lastError);\n rollback();\n }\n });\n }\n };\n\n onDestroy(() => {\n statusUnsub?.();\n });\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useHistory — reactive history store\n// ============================================================================\n\n/**\n * Reactive history Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const history = useHistory(system);\n * <button disabled={!$history?.canGoBack} on:click={() => $history?.goBack()}>Undo</button>\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): Readable<HistoryState | null> {\n assertSystem(\"useHistory\", system);\n return readable<HistoryState | null>(\n buildHistoryState(system),\n (set) => {\n return system.onHistoryChange(() => set(buildHistoryState(system)));\n },\n );\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\ninterface UseDirectiveConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\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 status?: boolean;\n /** Fact keys to subscribe to (omit for all) */\n facts?: string[];\n /** Derivation keys to subscribe to (omit for all) */\n derived?: string[];\n}\n\n/**\n * Create a scoped Directive system with automatic lifecycle management.\n * When no `facts` or `derived` keys are specified, subscribes to ALL\n * facts and derivations and returns Svelte readable stores.\n *\n * @example\n * ```svelte\n * // Subscribe to everything\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n *\n * // Selective keys\n * const { facts, derived } = useDirective(counterModule, { facts: [\"count\"], derived: [\"doubled\"] });\n * ```\n */\nexport function useDirective<M extends ModuleSchema>(\n moduleDef: ModuleDef<M>,\n config?: UseDirectiveConfig,\n): {\n system: SingleModuleSystem<M>;\n facts: Readable<InferFacts<M>>;\n derived: Readable<InferDerivations<M>>;\n events: SingleModuleSystem<M>[\"events\"];\n dispatch: (event: InferEvents<M>) => void;\n statusPlugin: StatusPlugin | undefined;\n} {\n const allPlugins = [...(config?.plugins ?? [])];\n let statusPlugin: StatusPlugin | undefined;\n\n if (config?.status) {\n const sp = createRequirementStatusPlugin();\n statusPlugin = sp;\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins.push(sp.plugin as Plugin<any>);\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: moduleDef,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n trace: config?.trace,\n errorBoundary: config?.errorBoundary,\n tickMs: config?.tickMs,\n zeroConfig: config?.zeroConfig,\n initialFacts: config?.initialFacts,\n } as any) as unknown as SingleModuleSystem<M>;\n\n // SSR guard: initialize facts for SSR rendering, start reconciliation only in the browser\n if (typeof window !== \"undefined\") {\n system.start();\n } else {\n system.initialize();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n const factKeys = config?.facts;\n const derivedKeys = config?.derived;\n const subscribeAll = !factKeys && !derivedKeys;\n\n // Subscribe to facts\n const factsStore: Readable<InferFacts<M>> = subscribeAll\n ? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n return system.facts.$store.subscribeAll(() => {\n set(system.facts.$store.toObject() as InferFacts<M>);\n });\n })\n : readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n if (!factKeys || factKeys.length === 0) return () => {};\n return system.facts.$store.subscribe(factKeys, () => {\n set(pickFacts(system, factKeys) as InferFacts<M>);\n });\n });\n\n // Subscribe to derivations\n const allDerivationKeys = subscribeAll\n ? Object.keys(system.derive ?? {})\n : (derivedKeys ?? []);\n const getDerived = (): InferDerivations<M> => {\n const result: Record<string, unknown> = {};\n for (const key of allDerivationKeys) {\n result[key] = system.read(key);\n }\n return result as InferDerivations<M>;\n };\n const derivedStore: Readable<InferDerivations<M>> =\n allDerivationKeys.length > 0\n ? readable(getDerived(), (set) => {\n return system.subscribe(allDerivationKeys, () => {\n set(getDerived());\n });\n })\n : readable(getDerived(), () => () => {});\n\n const events = system.events;\n const dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n return {\n system,\n facts: factsStore,\n derived: derivedStore,\n events,\n dispatch,\n statusPlugin,\n };\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => Readable<InferFacts<M>[K] | undefined>;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => Readable<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: Cast for overload compatibility\n useFact(system as SingleModuleSystem<any>, factKey) as Readable<\n InferFacts<M>[K] | undefined\n >,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useDerived(system as SingleModuleSystem<any>, derivationId) as Readable<\n InferDerivations<M>[K]\n >,\n useDispatch: (system: SingleModuleSystem<M>) => {\n return (event: InferEvents<M>) => {\n system.dispatch(event);\n };\n },\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: Cast for overload compatibility\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem\n// ============================================================================\n\n/**\n * Svelte readable store that selects from a NamespacedSystem.\n * Subscribes to specified keys and provides reactive updates.\n *\n * @param system - The namespaced system\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 * ```svelte\n * const token$ = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): Readable<R> {\n return readable<R>(selector(system), (set) => {\n const unsubscribe = system.subscribe(keys, () => {\n set(selector(system));\n });\n\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useQuerySystem — Stable query system with lifecycle management\n// ============================================================================\n\n/**\n * Svelte composable to create and manage a query system with proper lifecycle.\n *\n * Accepts a factory function that creates the system.\n * Handles cleanup on component destroy.\n *\n * @example\n * ```svelte\n * <script>\n * import { useQuerySystem, useDerived } from \"@directive-run/svelte\";\n * import { createQuerySystem } from \"@directive-run/query\";\n *\n * const app = useQuerySystem(() =>\n * createQuerySystem({\n * facts: { userId: \"\" },\n * queries: { user: { key: ..., fetcher: ... } },\n * autoStart: false,\n * })\n * );\n *\n * const user = useDerived(app, \"user\");\n * </script>\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nexport function useQuerySystem<T extends { start: () => void; destroy: () => void; isRunning?: boolean; [key: string]: any }>(\n factory: () => T,\n): T {\n const system = factory();\n\n if (typeof window !== \"undefined\" && !system.isRunning) {\n system.start();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n return system;\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,10 +1,20 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { createRequirementStatusPlugin, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, Plugin, TraceOption, ErrorBoundaryConfig, RequirementTypeStatus, HistoryState, ModulesMap, NamespacedSystem, InferSelectorState } from '@directive-run/core';
|
|
1
|
+
import { createRequirementStatusPlugin, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, Plugin, TraceOption, ErrorBoundaryConfig, HistoryState, ModulesMap, NamespacedSystem, RequirementTypeStatus, InferSelectorState } from '@directive-run/core';
|
|
3
2
|
export { RequirementTypeStatus } from '@directive-run/core';
|
|
4
3
|
import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
|
|
5
4
|
export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
|
|
6
5
|
import { Readable } from 'svelte/store';
|
|
7
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Svelte Adapter - Consolidated Svelte stores for Directive
|
|
9
|
+
*
|
|
10
|
+
* 15 active exports: useFact, useDerived, useDispatch, useSelector,
|
|
11
|
+
* useWatch, useInspect, useRequirementStatus, useEvents, useExplain,
|
|
12
|
+
* useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,
|
|
13
|
+
* createTypedHooks, shallowEqual
|
|
14
|
+
*
|
|
15
|
+
* Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore
|
|
16
|
+
*/
|
|
17
|
+
|
|
8
18
|
/** Type for the requirement status plugin return value */
|
|
9
19
|
type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;
|
|
10
20
|
/**
|
|
@@ -120,19 +130,11 @@ interface UseDirectiveConfig {
|
|
|
120
130
|
*/
|
|
121
131
|
declare function useDirective<M extends ModuleSchema>(moduleDef: ModuleDef<M>, config?: UseDirectiveConfig): {
|
|
122
132
|
system: SingleModuleSystem<M>;
|
|
123
|
-
facts: Readable<
|
|
133
|
+
facts: Readable<InferFacts<M>>;
|
|
124
134
|
derived: Readable<InferDerivations<M>>;
|
|
125
|
-
events:
|
|
126
|
-
_type: infer T_1;
|
|
127
|
-
} ? T_1 : T[K]; } : never : never : never) => void : () => void; } : Record<string, never>;
|
|
135
|
+
events: SingleModuleSystem<M>["events"];
|
|
128
136
|
dispatch: (event: InferEvents<M>) => void;
|
|
129
|
-
statusPlugin:
|
|
130
|
-
plugin: Plugin<never>;
|
|
131
|
-
getStatus: (type: string) => RequirementTypeStatus;
|
|
132
|
-
getAllStatus: () => Map<string, RequirementTypeStatus>;
|
|
133
|
-
subscribe: (listener: () => void) => () => void;
|
|
134
|
-
reset: () => void;
|
|
135
|
-
} | undefined;
|
|
137
|
+
statusPlugin: StatusPlugin | undefined;
|
|
136
138
|
};
|
|
137
139
|
declare function createTypedHooks<M extends ModuleSchema>(): {
|
|
138
140
|
useFact: <K extends keyof InferFacts<M> & string>(system: SingleModuleSystem<M>, factKey: K) => Readable<InferFacts<M>[K] | undefined>;
|
|
@@ -155,5 +157,35 @@ declare function createTypedHooks<M extends ModuleSchema>(): {
|
|
|
155
157
|
* ```
|
|
156
158
|
*/
|
|
157
159
|
declare function useNamespacedSelector<Modules extends ModulesMap, R>(system: NamespacedSystem<Modules>, keys: string[], selector: (system: NamespacedSystem<Modules>) => R): Readable<R>;
|
|
160
|
+
/**
|
|
161
|
+
* Svelte composable to create and manage a query system with proper lifecycle.
|
|
162
|
+
*
|
|
163
|
+
* Accepts a factory function that creates the system.
|
|
164
|
+
* Handles cleanup on component destroy.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```svelte
|
|
168
|
+
* <script>
|
|
169
|
+
* import { useQuerySystem, useDerived } from "@directive-run/svelte";
|
|
170
|
+
* import { createQuerySystem } from "@directive-run/query";
|
|
171
|
+
*
|
|
172
|
+
* const app = useQuerySystem(() =>
|
|
173
|
+
* createQuerySystem({
|
|
174
|
+
* facts: { userId: "" },
|
|
175
|
+
* queries: { user: { key: ..., fetcher: ... } },
|
|
176
|
+
* autoStart: false,
|
|
177
|
+
* })
|
|
178
|
+
* );
|
|
179
|
+
*
|
|
180
|
+
* const user = useDerived(app, "user");
|
|
181
|
+
* </script>
|
|
182
|
+
* ```
|
|
183
|
+
*/
|
|
184
|
+
declare function useQuerySystem<T extends {
|
|
185
|
+
start: () => void;
|
|
186
|
+
destroy: () => void;
|
|
187
|
+
isRunning?: boolean;
|
|
188
|
+
[key: string]: any;
|
|
189
|
+
}>(factory: () => T): T;
|
|
158
190
|
|
|
159
|
-
export { type OptimisticUpdateResult, type StatusPlugin, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useHistory, useInspect, useNamespacedSelector, useOptimisticUpdate, useRequirementStatus, useSelector, useWatch };
|
|
191
|
+
export { type OptimisticUpdateResult, type StatusPlugin, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useHistory, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useWatch };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,20 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { createRequirementStatusPlugin, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, Plugin, TraceOption, ErrorBoundaryConfig, RequirementTypeStatus, HistoryState, ModulesMap, NamespacedSystem, InferSelectorState } from '@directive-run/core';
|
|
1
|
+
import { createRequirementStatusPlugin, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, Plugin, TraceOption, ErrorBoundaryConfig, HistoryState, ModulesMap, NamespacedSystem, RequirementTypeStatus, InferSelectorState } from '@directive-run/core';
|
|
3
2
|
export { RequirementTypeStatus } from '@directive-run/core';
|
|
4
3
|
import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
|
|
5
4
|
export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
|
|
6
5
|
import { Readable } from 'svelte/store';
|
|
7
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Svelte Adapter - Consolidated Svelte stores for Directive
|
|
9
|
+
*
|
|
10
|
+
* 15 active exports: useFact, useDerived, useDispatch, useSelector,
|
|
11
|
+
* useWatch, useInspect, useRequirementStatus, useEvents, useExplain,
|
|
12
|
+
* useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,
|
|
13
|
+
* createTypedHooks, shallowEqual
|
|
14
|
+
*
|
|
15
|
+
* Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore
|
|
16
|
+
*/
|
|
17
|
+
|
|
8
18
|
/** Type for the requirement status plugin return value */
|
|
9
19
|
type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;
|
|
10
20
|
/**
|
|
@@ -120,19 +130,11 @@ interface UseDirectiveConfig {
|
|
|
120
130
|
*/
|
|
121
131
|
declare function useDirective<M extends ModuleSchema>(moduleDef: ModuleDef<M>, config?: UseDirectiveConfig): {
|
|
122
132
|
system: SingleModuleSystem<M>;
|
|
123
|
-
facts: Readable<
|
|
133
|
+
facts: Readable<InferFacts<M>>;
|
|
124
134
|
derived: Readable<InferDerivations<M>>;
|
|
125
|
-
events:
|
|
126
|
-
_type: infer T_1;
|
|
127
|
-
} ? T_1 : T[K]; } : never : never : never) => void : () => void; } : Record<string, never>;
|
|
135
|
+
events: SingleModuleSystem<M>["events"];
|
|
128
136
|
dispatch: (event: InferEvents<M>) => void;
|
|
129
|
-
statusPlugin:
|
|
130
|
-
plugin: Plugin<never>;
|
|
131
|
-
getStatus: (type: string) => RequirementTypeStatus;
|
|
132
|
-
getAllStatus: () => Map<string, RequirementTypeStatus>;
|
|
133
|
-
subscribe: (listener: () => void) => () => void;
|
|
134
|
-
reset: () => void;
|
|
135
|
-
} | undefined;
|
|
137
|
+
statusPlugin: StatusPlugin | undefined;
|
|
136
138
|
};
|
|
137
139
|
declare function createTypedHooks<M extends ModuleSchema>(): {
|
|
138
140
|
useFact: <K extends keyof InferFacts<M> & string>(system: SingleModuleSystem<M>, factKey: K) => Readable<InferFacts<M>[K] | undefined>;
|
|
@@ -155,5 +157,35 @@ declare function createTypedHooks<M extends ModuleSchema>(): {
|
|
|
155
157
|
* ```
|
|
156
158
|
*/
|
|
157
159
|
declare function useNamespacedSelector<Modules extends ModulesMap, R>(system: NamespacedSystem<Modules>, keys: string[], selector: (system: NamespacedSystem<Modules>) => R): Readable<R>;
|
|
160
|
+
/**
|
|
161
|
+
* Svelte composable to create and manage a query system with proper lifecycle.
|
|
162
|
+
*
|
|
163
|
+
* Accepts a factory function that creates the system.
|
|
164
|
+
* Handles cleanup on component destroy.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```svelte
|
|
168
|
+
* <script>
|
|
169
|
+
* import { useQuerySystem, useDerived } from "@directive-run/svelte";
|
|
170
|
+
* import { createQuerySystem } from "@directive-run/query";
|
|
171
|
+
*
|
|
172
|
+
* const app = useQuerySystem(() =>
|
|
173
|
+
* createQuerySystem({
|
|
174
|
+
* facts: { userId: "" },
|
|
175
|
+
* queries: { user: { key: ..., fetcher: ... } },
|
|
176
|
+
* autoStart: false,
|
|
177
|
+
* })
|
|
178
|
+
* );
|
|
179
|
+
*
|
|
180
|
+
* const user = useDerived(app, "user");
|
|
181
|
+
* </script>
|
|
182
|
+
* ```
|
|
183
|
+
*/
|
|
184
|
+
declare function useQuerySystem<T extends {
|
|
185
|
+
start: () => void;
|
|
186
|
+
destroy: () => void;
|
|
187
|
+
isRunning?: boolean;
|
|
188
|
+
[key: string]: any;
|
|
189
|
+
}>(factory: () => T): T;
|
|
158
190
|
|
|
159
|
-
export { type OptimisticUpdateResult, type StatusPlugin, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useHistory, useInspect, useNamespacedSelector, useOptimisticUpdate, useRequirementStatus, useSelector, useWatch };
|
|
191
|
+
export { type OptimisticUpdateResult, type StatusPlugin, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useHistory, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useWatch };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {createRequirementStatusPlugin,createSystem}from'@directive-run/core';import {defaultEquality,assertSystem,computeInspectState,createThrottle,buildHistoryState,pickFacts,runTrackedSelector,depsChanged}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {onDestroy}from'svelte';import {readable}from'svelte/store';function
|
|
1
|
+
import {createRequirementStatusPlugin,createSystem}from'@directive-run/core';import {defaultEquality,assertSystem,computeInspectState,createThrottle,buildHistoryState,pickFacts,runTrackedSelector,depsChanged}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {onDestroy}from'svelte';import {readable}from'svelte/store';function E(e,t){return process.env.NODE_ENV!=="production"&&e.read(t)===void 0&&console.warn(`[Directive] createDerivedStore("${t}") returned undefined. Check that "${t}" is defined in your module's derive property.`),readable(e.read(t),n=>e.subscribe([t],()=>{n(e.read(t));}))}function C(e,t){let n=()=>{let s={};for(let r of t)s[r]=e.read(r);return s};return readable(n(),s=>e.subscribe(t,()=>{s(n());}))}function T(e,t){return process.env.NODE_ENV!=="production"&&(e.facts.$store.has(t)||console.warn(`[Directive] createFactStore("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`)),readable(e.facts.$store.get(t),n=>e.facts.$store.subscribe([t],()=>{n(e.facts.$store.get(t));}))}function _(e){return readable(e.inspect(),t=>{let n=()=>t(e.inspect()),s=e.facts.$store.subscribeAll(n),r=e.onSettledChange(n);return ()=>{s(),r();}})}function V(e,t){return assertSystem("useFact",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useFact() received a function. Did you mean useSelector()? useFact() takes a string key or array of keys, not a selector function."),Array.isArray(t)?$(e,t):T(e,t)}function $(e,t){let n=()=>{let s={};for(let r of t)s[r]=e.facts.$store.get(r);return s};return readable(n(),s=>e.facts.$store.subscribe(t,()=>{s(n());}))}function P(e,t){return assertSystem("useDerived",e),process.env.NODE_ENV!=="production"&&typeof t=="function"&&console.error("[Directive] useDerived() received a function. Did you mean useSelector()? useDerived() takes a string key or array of keys, not a selector function."),Array.isArray(t)?C(e,t):E(e,t)}function B(e,t,n=defaultEquality){assertSystem("useSelector",e);let s=new Set(Object.keys(e.derive??{})),r=()=>runTrackedSelector(e,s,t),o=r();return readable(o.value,l=>{let g=o.value,p=o.factKeys,S=o.deriveKeys,d=[],y=()=>{for(let c of d)c();d.length=0;let f=()=>{let c=r();n(g,c.value)||(g=c.value,l(c.value)),depsChanged(p,c.factKeys,S,c.deriveKeys)&&(p=c.factKeys,S=c.deriveKeys,y());};p.length>0?d.push(e.facts.$store.subscribe(p,f)):S.length===0&&d.push(e.facts.$store.subscribeAll(f)),S.length>0&&d.push(e.subscribe(S,f));};return y(),()=>{for(let f of d)f();}})}function j(e){return assertSystem("useDispatch",e),t=>{e.dispatch(t);}}function q(e){return assertSystem("useEvents",e),e.events}function A(e,t,n){assertSystem("useWatch",e);let s=e.watch(t,n);onDestroy(s);}function z(e,t){return assertSystem("useInspect",e),t?.throttleMs&&t.throttleMs>0?readable(computeInspectState(e),n=>{let{throttled:s,cleanup:r}=createThrottle(()=>{n(computeInspectState(e));},t.throttleMs),o=e.facts.$store.subscribeAll(s),l=e.onSettledChange(s);return ()=>{r(),o(),l();}}):readable(computeInspectState(e),n=>{let s=()=>n(computeInspectState(e)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function L(e,t){if(Array.isArray(t)){let n=()=>{let s={};for(let r of t)s[r]=e.getStatus(r);return s};return readable(n(),s=>e.subscribe(()=>{s(n());}))}return readable(e.getStatus(t),n=>e.subscribe(()=>{n(e.getStatus(t));}))}function Q(e,t){return assertSystem("useExplain",e),readable(e.explain(t),n=>{let s=()=>n(e.explain(t)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function G(e,t){return assertSystem("useConstraintStatus",e),readable(x(e,t),n=>{let s=()=>n(x(e,t)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function x(e,t){let n=e.inspect();return t?n.constraints.find(s=>s.id===t)??null:n.constraints}function J(e,t,n){assertSystem("useOptimisticUpdate",e);let s=false,r=null,o=null,l=null,g=new Set,p=new Set,S={subscribe(u){return u(s),g.add(u),()=>g.delete(u)}},d={subscribe(u){return u(r),p.add(u),()=>p.delete(u)}},y=u=>{s=u;for(let M of g)M(u);},f=u=>{r=u;for(let M of p)M(u);},c=()=>{o&&(e.restore(o),o=null),y(false),f(null),l?.(),l=null;},a=u=>{o=e.getSnapshot(),y(true),f(null),e.batch(u),t&&n&&(l?.(),l=t.subscribe(()=>{let M=t.getStatus(n);!M.isLoading&&!M.hasError?(o=null,y(false),l?.(),l=null):M.hasError&&(f(M.lastError),c());}));};return onDestroy(()=>{l?.();}),{mutate:a,isPending:S,error:d,rollback:c}}function X(e){return assertSystem("useHistory",e),readable(buildHistoryState(e),t=>e.onHistoryChange(()=>t(buildHistoryState(e))))}function Y(e,t){let n=[...t?.plugins??[]],s;if(t?.status){let a=createRequirementStatusPlugin();s=a,n.push(a.plugin);}let r=createSystem({module:e,plugins:n.length>0?n:void 0,trace:t?.trace,errorBoundary:t?.errorBoundary,tickMs:t?.tickMs,zeroConfig:t?.zeroConfig,initialFacts:t?.initialFacts});typeof window<"u"?r.start():r.initialize(),onDestroy(()=>{r.destroy();});let o=t?.facts,l=t?.derived,g=!o&&!l,p=g?readable(r.facts.$store.toObject(),a=>r.facts.$store.subscribeAll(()=>{a(r.facts.$store.toObject());})):readable(pickFacts(r,o??[]),a=>!o||o.length===0?()=>{}:r.facts.$store.subscribe(o,()=>{a(pickFacts(r,o));})),S=g?Object.keys(r.derive??{}):l??[],d=()=>{let a={};for(let u of S)a[u]=r.read(u);return a},y=S.length>0?readable(d(),a=>r.subscribe(S,()=>{a(d());})):readable(d(),()=>()=>{}),f=r.events;return {system:r,facts:p,derived:y,events:f,dispatch:a=>r.dispatch(a),statusPlugin:s}}function Z(){return {useFact:(e,t)=>V(e,t),useDerived:(e,t)=>P(e,t),useDispatch:e=>t=>{e.dispatch(t);},useEvents:e=>q(e),useWatch:(e,t,n)=>A(e,t,n)}}function ee(e,t,n){return readable(n(e),s=>e.subscribe(t,()=>{s(n(e));}))}function te(e){let t=e();return typeof window<"u"&&!t.isRunning&&t.start(),onDestroy(()=>{t.destroy();}),t}export{E as createDerivedStore,C as createDerivedsStore,T as createFactStore,_ as createInspectStore,Z as createTypedHooks,G as useConstraintStatus,P as useDerived,Y as useDirective,j as useDispatch,q as useEvents,Q as useExplain,V as useFact,X as useHistory,z as useInspect,ee as useNamespacedSelector,J as useOptimisticUpdate,te as useQuerySystem,L as useRequirementStatus,B as useSelector,A as useWatch};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["createDerivedStore","system","derivationId","readable","set","createDerivedsStore","derivationIds","getValues","result","id","createFactStore","factKey","createInspectStore","update","unsubFacts","unsubSettled","useFact","keyOrKeys","assertSystem","_useFactMulti","factKeys","key","useDerived","idOrIds","useSelector","selector","equalityFn","defaultEquality","deriveKeySet","runWithTracking","runTrackedSelector","initial","currentSelected","trackedFactKeys","trackedDeriveKeys","unsubs","resubscribe","unsub","onUpdate","depsChanged","useDispatch","event","useEvents","useWatch","callback","unsubscribe","onDestroy","useInspect","options","computeInspectState","throttled","cleanup","createThrottle","useRequirementStatus","statusPlugin","typeOrTypes","type","useExplain","requirementId","useConstraintStatus","constraintId","_getConstraintValue","inspection","c","useOptimisticUpdate","requirementType","isPendingValue","errorValue","snapshot","statusUnsub","pendingSubscribers","errorSubscribers","isPending","fn","error","setPending","v","setError","rollback","mutate","updateFn","status","useHistory","buildHistoryState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks","useNamespacedSelector","keys"],"mappings":"uXA+DO,SAASA,CAAAA,CAEdC,CAAAA,CACAC,EACa,CACb,OAAI,OAAA,CAAQ,GAAA,CAAI,WAAa,YAAA,EACND,CAAAA,CAAO,IAAA,CAAKC,CAAY,IACxB,MAAA,EACnB,OAAA,CAAQ,IAAA,CACN,CAAA,gCAAA,EAAmCA,CAAY,CAAA,mCAAA,EAC9BA,CAAY,gDAC/B,CAAA,CAIGC,QAAAA,CAAYF,EAAO,IAAA,CAAKC,CAAY,CAAA,CAASE,CAAAA,EAC9BH,EAAO,SAAA,CAAU,CAACC,CAAY,CAAA,CAAG,IAAM,CACzDE,CAAAA,CAAIH,CAAAA,CAAO,IAAA,CAAKC,CAAY,CAAM,EACpC,CAAC,CAEF,CACH,CAKO,SAASG,CAAAA,CAEdJ,CAAAA,CACAK,CAAAA,CACa,CACb,IAAMC,CAAAA,CAAY,IAAS,CACzB,IAAMC,CAAAA,CAAkC,EAAC,CACzC,IAAA,IAAWC,KAAMH,CAAAA,CACfE,CAAAA,CAAOC,CAAE,CAAA,CAAIR,CAAAA,CAAO,KAAKQ,CAAE,CAAA,CAE7B,OAAOD,CACT,EAEA,OAAOL,QAAAA,CAAYI,CAAAA,EAAU,CAAIH,GACXH,CAAAA,CAAO,SAAA,CAAUK,CAAAA,CAAe,IAAM,CACxDF,CAAAA,CAAIG,CAAAA,EAAW,EACjB,CAAC,CAEF,CACH,CAKO,SAASG,CAAAA,CAEdT,EACAU,CAAAA,CACyB,CACzB,OAAI,OAAA,CAAQ,IAAI,QAAA,GAAa,YAAA,GACtBV,CAAAA,CAAO,KAAA,CAAM,OAAO,GAAA,CAAIU,CAAO,GAClC,OAAA,CAAQ,IAAA,CACN,gCAAgCA,CAAO,CAAA,+CAAA,EACtBA,CAAO,CAAA,qCAAA,CAC1B,GAIGR,QAAAA,CACLF,CAAAA,CAAO,KAAA,CAAM,MAAA,CA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,CAAO,EAGpD,UAAA,CAAY,CACVV,CAAAA,CACAC,CAAAA,GAGAoB,EAAWrB,CAAAA,CAAmCC,CAAY,CAAA,CAG5D,WAAA,CAAcD,GACJwC,CAAAA,EAA0B,CAChCxC,EAAO,QAAA,CAASwC,CAAK,EACvB,CAAA,CAEF,SAAA,CAAYxC,CAAAA,EAAkCyC,CAAAA,CAAazC,CAAM,CAAA,CACjE,QAAA,CAAU,CACRA,CAAAA,CACAoB,EACAuB,CAAAA,GAGAD,CAAAA,CAAS1C,CAAAA,CAAmCoB,CAAAA,CAAKuB,CAAQ,CAC7D,CACF,CAmBO,SAASwD,EAAAA,CACdnG,EACAoG,CAAAA,CACA5E,CAAAA,CACa,CACb,OAAOtB,SAAYsB,CAAAA,CAASxB,CAAM,CAAA,CAAIG,CAAAA,EAChBH,EAAO,SAAA,CAAUoG,CAAAA,CAAM,IAAM,CAC/CjG,EAAIqB,CAAAA,CAASxB,CAAM,CAAC,EACtB,CAAC,CAGF,CACH","file":"index.js","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n TraceOption,\n ErrorBoundaryConfig,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemInspection,\n SystemSnapshot,\n HistoryState,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { onDestroy } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationId: string,\n): Readable<T> {\n if (process.env.NODE_ENV !== \"production\") {\n const initialValue = system.read(derivationId);\n if (initialValue === undefined) {\n console.warn(\n `[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n return readable<T>(system.read(derivationId) as T, (set) => {\n const unsubscribe = system.subscribe([derivationId], () => {\n set(system.read(derivationId) as T);\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Readable<T> {\n const getValues = (): T => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n return result as T;\n };\n\n return readable<T>(getValues(), (set) => {\n const unsubscribe = system.subscribe(derivationIds, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n factKey: string,\n): Readable<T | undefined> {\n if (process.env.NODE_ENV !== \"production\") {\n if (!system.facts.$store.has(factKey)) {\n console.warn(\n `[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n return readable<T | undefined>(\n system.facts.$store.get(factKey) as T | undefined,\n (set) => {\n const unsubscribe = system.facts.$store.subscribe([factKey], () => {\n set(system.facts.$store.get(factKey) as T | undefined);\n });\n return unsubscribe;\n },\n );\n}\n\n/**\n * Create a Svelte store for system inspection data.\n * NOTE: This updates on every fact change. Use sparingly in production.\n */\nexport function createInspectStore(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n return readable<SystemInspection>(system.inspect(), (set) => {\n const update = () => set(system.inspect());\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\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>(\n system: SingleModuleSystem<S>,\n factKey: K,\n): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKeys: K[],\n): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): Readable<unknown> {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFactMulti(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Readable<Record<string, unknown>> {\n const getValues = (): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n set(getValues());\n });\n return unsubscribe;\n });\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>(\n system: SingleModuleSystem<S>,\n derivationId: K,\n): Readable<InferDerivations<S>[K]>;\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): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n idOrIds: string | string[],\n): Readable<unknown> {\n assertSystem(\"useDerived\", system);\n if (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"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(idOrIds)) {\n return createDerivedsStore(system, idOrIds);\n }\n\n // Single key path\n return createDerivedStore(system, idOrIds);\n}\n\n// ============================================================================\n// useSelector — auto-tracking selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations.\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys.\n */\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n equalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n assertSystem(\"useSelector\", system);\n const deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const runWithTracking = () =>\n runTrackedSelector(system, deriveKeySet, selector);\n\n const initial = runWithTracking();\n\n return readable(initial.value, (set) => {\n let currentSelected = initial.value;\n let trackedFactKeys = initial.factKeys;\n let trackedDeriveKeys = initial.deriveKeys;\n const unsubs: Array<() => void> = [];\n\n const resubscribe = () => {\n for (const unsub of unsubs) unsub();\n unsubs.length = 0;\n\n const onUpdate = () => {\n const result = runWithTracking();\n if (!equalityFn(currentSelected, result.value)) {\n currentSelected = result.value;\n set(result.value);\n }\n // Re-track: check if deps changed\n if (\n depsChanged(\n trackedFactKeys,\n result.factKeys,\n trackedDeriveKeys,\n result.deriveKeys,\n )\n ) {\n trackedFactKeys = result.factKeys;\n trackedDeriveKeys = result.deriveKeys;\n resubscribe();\n }\n };\n\n if (trackedFactKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n } else if (trackedDeriveKeys.length === 0) {\n unsubs.push(system.facts.$store.subscribeAll(onUpdate));\n }\n if (trackedDeriveKeys.length > 0) {\n unsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n });\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 (event: InferEvents<S>) => {\n system.dispatch(event);\n };\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher.\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return system.events;\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect\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 previousValue: 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 previousValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n callback: (newValue: unknown, prevValue: unknown) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const unsubscribe = system.watch(key, callback);\n onDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n throttleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): Readable<InspectState> {\n assertSystem(\"useInspect\", system);\n if (options?.throttleMs && options.throttleMs > 0) {\n return readable<InspectState>(computeInspectState(system), (set) => {\n const { throttled, cleanup } = createThrottle(() => {\n set(computeInspectState(system));\n }, options.throttleMs!);\n\n const unsubFacts = system.facts.$store.subscribeAll(throttled);\n const unsubSettled = system.onSettledChange(throttled);\n\n return () => {\n cleanup();\n unsubFacts();\n unsubSettled();\n };\n });\n }\n\n return readable<InspectState>(computeInspectState(system), (set) => {\n const update = () => set(computeInspectState(system));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n):\n | Readable<RequirementTypeStatus>\n | Readable<Record<string, RequirementTypeStatus>> {\n if (Array.isArray(typeOrTypes)) {\n const getValues = (): Record<string, RequirementTypeStatus> => {\n const result: Record<string, RequirementTypeStatus> = {};\n for (const type of typeOrTypes) {\n result[type] = statusPlugin.getStatus(type);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(getValues());\n });\n return unsubscribe;\n });\n }\n\n return readable<RequirementTypeStatus>(\n statusPlugin.getStatus(typeOrTypes),\n (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(statusPlugin.getStatus(typeOrTypes));\n });\n return unsubscribe;\n },\n );\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): Readable<string | null> {\n assertSystem(\"useExplain\", system);\n return readable<string | null>(system.explain(requirementId), (set) => {\n const update = () => set(system.explain(requirementId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): Readable<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): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n assertSystem(\"useConstraintStatus\", system);\n return readable<ConstraintInfo[] | ConstraintInfo | null>(\n _getConstraintValue(system, constraintId),\n (set) => {\n const update = () => set(_getConstraintValue(system, constraintId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n );\n}\n\nfunction _getConstraintValue(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return (\n inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ??\n null\n );\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n mutate: (updateFn: () => void) => void;\n isPending: Readable<boolean>;\n error: Readable<Error | null>;\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 */\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 let isPendingValue = false;\n let errorValue: Error | null = null;\n let snapshot: SystemSnapshot | null = null;\n let statusUnsub: (() => void) | null = null;\n\n // We track subscribers manually since we need imperative push\n const pendingSubscribers = new Set<(v: boolean) => void>();\n const errorSubscribers = new Set<(v: Error | null) => void>();\n\n const isPending: Readable<boolean> = {\n subscribe(fn) {\n fn(isPendingValue);\n pendingSubscribers.add(fn);\n return () => pendingSubscribers.delete(fn);\n },\n };\n\n const error: Readable<Error | null> = {\n subscribe(fn) {\n fn(errorValue);\n errorSubscribers.add(fn);\n return () => errorSubscribers.delete(fn);\n },\n };\n\n const setPending = (v: boolean) => {\n isPendingValue = v;\n for (const fn of pendingSubscribers) fn(v);\n };\n\n const setError = (v: Error | null) => {\n errorValue = v;\n for (const fn of errorSubscribers) fn(v);\n };\n\n const rollback = () => {\n if (snapshot) {\n system.restore(snapshot);\n snapshot = null;\n }\n setPending(false);\n setError(null);\n statusUnsub?.();\n statusUnsub = null;\n };\n\n const mutate = (updateFn: () => void) => {\n snapshot = system.getSnapshot();\n setPending(true);\n setError(null);\n system.batch(updateFn);\n\n if (statusPlugin && requirementType) {\n statusUnsub?.();\n statusUnsub = statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n snapshot = null;\n setPending(false);\n statusUnsub?.();\n statusUnsub = null;\n } else if (status.hasError) {\n setError(status.lastError);\n rollback();\n }\n });\n }\n };\n\n onDestroy(() => {\n statusUnsub?.();\n });\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useHistory — reactive history store\n// ============================================================================\n\n/**\n * Reactive history Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const history = useHistory(system);\n * <button disabled={!$history?.canGoBack} on:click={() => $history?.goBack()}>Undo</button>\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): Readable<HistoryState | null> {\n assertSystem(\"useHistory\", system);\n return readable<HistoryState | null>(\n buildHistoryState(system),\n (set) => {\n return system.onHistoryChange(() => set(buildHistoryState(system)));\n },\n );\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\ninterface UseDirectiveConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\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 status?: boolean;\n /** Fact keys to subscribe to (omit for all) */\n facts?: string[];\n /** Derivation keys to subscribe to (omit for all) */\n derived?: string[];\n}\n\n/**\n * Create a scoped Directive system with automatic lifecycle management.\n * When no `facts` or `derived` keys are specified, subscribes to ALL\n * facts and derivations and returns Svelte readable stores.\n *\n * @example\n * ```svelte\n * // Subscribe to everything\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n *\n * // Selective keys\n * const { facts, derived } = useDirective(counterModule, { facts: [\"count\"], derived: [\"doubled\"] });\n * ```\n */\nexport function useDirective<M extends ModuleSchema>(\n moduleDef: ModuleDef<M>,\n config?: UseDirectiveConfig,\n) {\n const allPlugins = [...(config?.plugins ?? [])];\n let statusPlugin: StatusPlugin | undefined;\n\n if (config?.status) {\n const sp = createRequirementStatusPlugin();\n statusPlugin = sp;\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins.push(sp.plugin as Plugin<any>);\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: moduleDef,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n trace: config?.trace,\n errorBoundary: config?.errorBoundary,\n tickMs: config?.tickMs,\n zeroConfig: config?.zeroConfig,\n initialFacts: config?.initialFacts,\n } as any) as unknown as SingleModuleSystem<M>;\n\n system.start();\n\n onDestroy(() => {\n system.destroy();\n });\n\n const factKeys = config?.facts;\n const derivedKeys = config?.derived;\n const subscribeAll = !factKeys && !derivedKeys;\n\n // Subscribe to facts\n const factsStore: Readable<InferFacts<M>> = subscribeAll\n ? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n return system.facts.$store.subscribeAll(() => {\n set(system.facts.$store.toObject() as InferFacts<M>);\n });\n })\n : readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n if (!factKeys || factKeys.length === 0) return () => {};\n return system.facts.$store.subscribe(factKeys, () => {\n set(pickFacts(system, factKeys) as InferFacts<M>);\n });\n });\n\n // Subscribe to derivations\n const allDerivationKeys = subscribeAll\n ? Object.keys(system.derive ?? {})\n : (derivedKeys ?? []);\n const getDerived = (): InferDerivations<M> => {\n const result: Record<string, unknown> = {};\n for (const key of allDerivationKeys) {\n result[key] = system.read(key);\n }\n return result as InferDerivations<M>;\n };\n const derivedStore: Readable<InferDerivations<M>> =\n allDerivationKeys.length > 0\n ? readable(getDerived(), (set) => {\n return system.subscribe(allDerivationKeys, () => {\n set(getDerived());\n });\n })\n : readable(getDerived(), () => () => {});\n\n const events = system.events;\n const dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n return {\n system,\n facts: factsStore,\n derived: derivedStore,\n events,\n dispatch,\n statusPlugin,\n };\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => Readable<InferFacts<M>[K] | undefined>;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => Readable<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: Cast for overload compatibility\n useFact(system as SingleModuleSystem<any>, factKey) as Readable<\n InferFacts<M>[K] | undefined\n >,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useDerived(system as SingleModuleSystem<any>, derivationId) as Readable<\n InferDerivations<M>[K]\n >,\n useDispatch: (system: SingleModuleSystem<M>) => {\n return (event: InferEvents<M>) => {\n system.dispatch(event);\n };\n },\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: Cast for overload compatibility\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem\n// ============================================================================\n\n/**\n * Svelte readable store that selects from a NamespacedSystem.\n * Subscribes to specified keys and provides reactive updates.\n *\n * @param system - The namespaced system\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 * ```svelte\n * const token$ = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): Readable<R> {\n return readable<R>(selector(system), (set) => {\n const unsubscribe = system.subscribe(keys, () => {\n set(selector(system));\n });\n\n return unsubscribe;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["createDerivedStore","system","derivationId","readable","set","createDerivedsStore","derivationIds","getValues","result","id","createFactStore","factKey","createInspectStore","update","unsubFacts","unsubSettled","useFact","keyOrKeys","assertSystem","_useFactMulti","factKeys","key","useDerived","idOrIds","useSelector","selector","equalityFn","defaultEquality","deriveKeySet","runWithTracking","runTrackedSelector","initial","currentSelected","trackedFactKeys","trackedDeriveKeys","unsubs","resubscribe","unsub","onUpdate","depsChanged","useDispatch","event","useEvents","useWatch","callback","unsubscribe","onDestroy","useInspect","options","computeInspectState","throttled","cleanup","createThrottle","useRequirementStatus","statusPlugin","typeOrTypes","type","useExplain","requirementId","useConstraintStatus","constraintId","_getConstraintValue","inspection","c","useOptimisticUpdate","requirementType","isPendingValue","errorValue","snapshot","statusUnsub","pendingSubscribers","errorSubscribers","isPending","fn","error","setPending","v","setError","rollback","mutate","updateFn","status","useHistory","buildHistoryState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks","useNamespacedSelector","keys","useQuerySystem","factory"],"mappings":"uXA+DO,SAASA,EAEdC,CAAAA,CACAC,CAAAA,CACa,CACb,OAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,GAAa,cACND,CAAAA,CAAO,IAAA,CAAKC,CAAY,CAAA,GACxB,QACnB,OAAA,CAAQ,IAAA,CACN,CAAA,gCAAA,EAAmCA,CAAY,sCAC9BA,CAAY,CAAA,8CAAA,CAC/B,EAIGC,QAAAA,CAAYF,CAAAA,CAAO,KAAKC,CAAY,CAAA,CAASE,CAAAA,EAC9BH,CAAAA,CAAO,UAAU,CAACC,CAAY,EAAG,IAAM,CACzDE,EAAIH,CAAAA,CAAO,IAAA,CAAKC,CAAY,CAAM,EACpC,CAAC,CAEF,CACH,CAKO,SAASG,EAEdJ,CAAAA,CACAK,CAAAA,CACa,CACb,IAAMC,EAAY,IAAS,CACzB,IAAMC,CAAAA,CAAkC,EAAC,CACzC,IAAA,IAAWC,CAAAA,IAAMH,CAAAA,CACfE,EAAOC,CAAE,CAAA,CAAIR,EAAO,IAAA,CAAKQ,CAAE,EAE7B,OAAOD,CACT,CAAA,CAEA,OAAOL,SAAY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,IAAM,CACd7C,CAAAA,CAAO,UACT,CAAC,EAEMA,CACT","file":"index.js","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n TraceOption,\n ErrorBoundaryConfig,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemInspection,\n SystemSnapshot,\n HistoryState,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { onDestroy } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationId: string,\n): Readable<T> {\n if (process.env.NODE_ENV !== \"production\") {\n const initialValue = system.read(derivationId);\n if (initialValue === undefined) {\n console.warn(\n `[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n return readable<T>(system.read(derivationId) as T, (set) => {\n const unsubscribe = system.subscribe([derivationId], () => {\n set(system.read(derivationId) as T);\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Readable<T> {\n const getValues = (): T => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n return result as T;\n };\n\n return readable<T>(getValues(), (set) => {\n const unsubscribe = system.subscribe(derivationIds, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n factKey: string,\n): Readable<T | undefined> {\n if (process.env.NODE_ENV !== \"production\") {\n if (!system.facts.$store.has(factKey)) {\n console.warn(\n `[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n return readable<T | undefined>(\n system.facts.$store.get(factKey) as T | undefined,\n (set) => {\n const unsubscribe = system.facts.$store.subscribe([factKey], () => {\n set(system.facts.$store.get(factKey) as T | undefined);\n });\n return unsubscribe;\n },\n );\n}\n\n/**\n * Create a Svelte store for system inspection data.\n * NOTE: This updates on every fact change. Use sparingly in production.\n */\nexport function createInspectStore(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n return readable<SystemInspection>(system.inspect(), (set) => {\n const update = () => set(system.inspect());\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\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>(\n system: SingleModuleSystem<S>,\n factKey: K,\n): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKeys: K[],\n): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): Readable<unknown> {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFactMulti(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Readable<Record<string, unknown>> {\n const getValues = (): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n set(getValues());\n });\n return unsubscribe;\n });\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>(\n system: SingleModuleSystem<S>,\n derivationId: K,\n): Readable<InferDerivations<S>[K]>;\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): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n idOrIds: string | string[],\n): Readable<unknown> {\n assertSystem(\"useDerived\", system);\n if (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"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(idOrIds)) {\n return createDerivedsStore(system, idOrIds);\n }\n\n // Single key path\n return createDerivedStore(system, idOrIds);\n}\n\n// ============================================================================\n// useSelector — auto-tracking selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations.\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys.\n */\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n equalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n assertSystem(\"useSelector\", system);\n const deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const runWithTracking = () =>\n runTrackedSelector(system, deriveKeySet, selector);\n\n const initial = runWithTracking();\n\n return readable(initial.value, (set) => {\n let currentSelected = initial.value;\n let trackedFactKeys = initial.factKeys;\n let trackedDeriveKeys = initial.deriveKeys;\n const unsubs: Array<() => void> = [];\n\n const resubscribe = () => {\n for (const unsub of unsubs) unsub();\n unsubs.length = 0;\n\n const onUpdate = () => {\n const result = runWithTracking();\n if (!equalityFn(currentSelected, result.value)) {\n currentSelected = result.value;\n set(result.value);\n }\n // Re-track: check if deps changed\n if (\n depsChanged(\n trackedFactKeys,\n result.factKeys,\n trackedDeriveKeys,\n result.deriveKeys,\n )\n ) {\n trackedFactKeys = result.factKeys;\n trackedDeriveKeys = result.deriveKeys;\n resubscribe();\n }\n };\n\n if (trackedFactKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n } else if (trackedDeriveKeys.length === 0) {\n unsubs.push(system.facts.$store.subscribeAll(onUpdate));\n }\n if (trackedDeriveKeys.length > 0) {\n unsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n });\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 (event: InferEvents<S>) => {\n system.dispatch(event);\n };\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher.\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return system.events;\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect\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 previousValue: 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 previousValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n callback: (newValue: unknown, prevValue: unknown) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const unsubscribe = system.watch(key, callback);\n onDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n throttleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): Readable<InspectState> {\n assertSystem(\"useInspect\", system);\n if (options?.throttleMs && options.throttleMs > 0) {\n return readable<InspectState>(computeInspectState(system), (set) => {\n const { throttled, cleanup } = createThrottle(() => {\n set(computeInspectState(system));\n }, options.throttleMs!);\n\n const unsubFacts = system.facts.$store.subscribeAll(throttled);\n const unsubSettled = system.onSettledChange(throttled);\n\n return () => {\n cleanup();\n unsubFacts();\n unsubSettled();\n };\n });\n }\n\n return readable<InspectState>(computeInspectState(system), (set) => {\n const update = () => set(computeInspectState(system));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n):\n | Readable<RequirementTypeStatus>\n | Readable<Record<string, RequirementTypeStatus>> {\n if (Array.isArray(typeOrTypes)) {\n const getValues = (): Record<string, RequirementTypeStatus> => {\n const result: Record<string, RequirementTypeStatus> = {};\n for (const type of typeOrTypes) {\n result[type] = statusPlugin.getStatus(type);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(getValues());\n });\n return unsubscribe;\n });\n }\n\n return readable<RequirementTypeStatus>(\n statusPlugin.getStatus(typeOrTypes),\n (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(statusPlugin.getStatus(typeOrTypes));\n });\n return unsubscribe;\n },\n );\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): Readable<string | null> {\n assertSystem(\"useExplain\", system);\n return readable<string | null>(system.explain(requirementId), (set) => {\n const update = () => set(system.explain(requirementId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): Readable<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): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n assertSystem(\"useConstraintStatus\", system);\n return readable<ConstraintInfo[] | ConstraintInfo | null>(\n _getConstraintValue(system, constraintId),\n (set) => {\n const update = () => set(_getConstraintValue(system, constraintId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n );\n}\n\nfunction _getConstraintValue(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return (\n inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ??\n null\n );\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n mutate: (updateFn: () => void) => void;\n isPending: Readable<boolean>;\n error: Readable<Error | null>;\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 */\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 let isPendingValue = false;\n let errorValue: Error | null = null;\n let snapshot: SystemSnapshot | null = null;\n let statusUnsub: (() => void) | null = null;\n\n // We track subscribers manually since we need imperative push\n const pendingSubscribers = new Set<(v: boolean) => void>();\n const errorSubscribers = new Set<(v: Error | null) => void>();\n\n const isPending: Readable<boolean> = {\n subscribe(fn) {\n fn(isPendingValue);\n pendingSubscribers.add(fn);\n return () => pendingSubscribers.delete(fn);\n },\n };\n\n const error: Readable<Error | null> = {\n subscribe(fn) {\n fn(errorValue);\n errorSubscribers.add(fn);\n return () => errorSubscribers.delete(fn);\n },\n };\n\n const setPending = (v: boolean) => {\n isPendingValue = v;\n for (const fn of pendingSubscribers) fn(v);\n };\n\n const setError = (v: Error | null) => {\n errorValue = v;\n for (const fn of errorSubscribers) fn(v);\n };\n\n const rollback = () => {\n if (snapshot) {\n system.restore(snapshot);\n snapshot = null;\n }\n setPending(false);\n setError(null);\n statusUnsub?.();\n statusUnsub = null;\n };\n\n const mutate = (updateFn: () => void) => {\n snapshot = system.getSnapshot();\n setPending(true);\n setError(null);\n system.batch(updateFn);\n\n if (statusPlugin && requirementType) {\n statusUnsub?.();\n statusUnsub = statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n snapshot = null;\n setPending(false);\n statusUnsub?.();\n statusUnsub = null;\n } else if (status.hasError) {\n setError(status.lastError);\n rollback();\n }\n });\n }\n };\n\n onDestroy(() => {\n statusUnsub?.();\n });\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useHistory — reactive history store\n// ============================================================================\n\n/**\n * Reactive history Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const history = useHistory(system);\n * <button disabled={!$history?.canGoBack} on:click={() => $history?.goBack()}>Undo</button>\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): Readable<HistoryState | null> {\n assertSystem(\"useHistory\", system);\n return readable<HistoryState | null>(\n buildHistoryState(system),\n (set) => {\n return system.onHistoryChange(() => set(buildHistoryState(system)));\n },\n );\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\ninterface UseDirectiveConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\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 status?: boolean;\n /** Fact keys to subscribe to (omit for all) */\n facts?: string[];\n /** Derivation keys to subscribe to (omit for all) */\n derived?: string[];\n}\n\n/**\n * Create a scoped Directive system with automatic lifecycle management.\n * When no `facts` or `derived` keys are specified, subscribes to ALL\n * facts and derivations and returns Svelte readable stores.\n *\n * @example\n * ```svelte\n * // Subscribe to everything\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n *\n * // Selective keys\n * const { facts, derived } = useDirective(counterModule, { facts: [\"count\"], derived: [\"doubled\"] });\n * ```\n */\nexport function useDirective<M extends ModuleSchema>(\n moduleDef: ModuleDef<M>,\n config?: UseDirectiveConfig,\n): {\n system: SingleModuleSystem<M>;\n facts: Readable<InferFacts<M>>;\n derived: Readable<InferDerivations<M>>;\n events: SingleModuleSystem<M>[\"events\"];\n dispatch: (event: InferEvents<M>) => void;\n statusPlugin: StatusPlugin | undefined;\n} {\n const allPlugins = [...(config?.plugins ?? [])];\n let statusPlugin: StatusPlugin | undefined;\n\n if (config?.status) {\n const sp = createRequirementStatusPlugin();\n statusPlugin = sp;\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins.push(sp.plugin as Plugin<any>);\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: moduleDef,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n trace: config?.trace,\n errorBoundary: config?.errorBoundary,\n tickMs: config?.tickMs,\n zeroConfig: config?.zeroConfig,\n initialFacts: config?.initialFacts,\n } as any) as unknown as SingleModuleSystem<M>;\n\n // SSR guard: initialize facts for SSR rendering, start reconciliation only in the browser\n if (typeof window !== \"undefined\") {\n system.start();\n } else {\n system.initialize();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n const factKeys = config?.facts;\n const derivedKeys = config?.derived;\n const subscribeAll = !factKeys && !derivedKeys;\n\n // Subscribe to facts\n const factsStore: Readable<InferFacts<M>> = subscribeAll\n ? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n return system.facts.$store.subscribeAll(() => {\n set(system.facts.$store.toObject() as InferFacts<M>);\n });\n })\n : readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n if (!factKeys || factKeys.length === 0) return () => {};\n return system.facts.$store.subscribe(factKeys, () => {\n set(pickFacts(system, factKeys) as InferFacts<M>);\n });\n });\n\n // Subscribe to derivations\n const allDerivationKeys = subscribeAll\n ? Object.keys(system.derive ?? {})\n : (derivedKeys ?? []);\n const getDerived = (): InferDerivations<M> => {\n const result: Record<string, unknown> = {};\n for (const key of allDerivationKeys) {\n result[key] = system.read(key);\n }\n return result as InferDerivations<M>;\n };\n const derivedStore: Readable<InferDerivations<M>> =\n allDerivationKeys.length > 0\n ? readable(getDerived(), (set) => {\n return system.subscribe(allDerivationKeys, () => {\n set(getDerived());\n });\n })\n : readable(getDerived(), () => () => {});\n\n const events = system.events;\n const dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n return {\n system,\n facts: factsStore,\n derived: derivedStore,\n events,\n dispatch,\n statusPlugin,\n };\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => Readable<InferFacts<M>[K] | undefined>;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => Readable<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: Cast for overload compatibility\n useFact(system as SingleModuleSystem<any>, factKey) as Readable<\n InferFacts<M>[K] | undefined\n >,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useDerived(system as SingleModuleSystem<any>, derivationId) as Readable<\n InferDerivations<M>[K]\n >,\n useDispatch: (system: SingleModuleSystem<M>) => {\n return (event: InferEvents<M>) => {\n system.dispatch(event);\n };\n },\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: Cast for overload compatibility\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem\n// ============================================================================\n\n/**\n * Svelte readable store that selects from a NamespacedSystem.\n * Subscribes to specified keys and provides reactive updates.\n *\n * @param system - The namespaced system\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 * ```svelte\n * const token$ = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): Readable<R> {\n return readable<R>(selector(system), (set) => {\n const unsubscribe = system.subscribe(keys, () => {\n set(selector(system));\n });\n\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useQuerySystem — Stable query system with lifecycle management\n// ============================================================================\n\n/**\n * Svelte composable to create and manage a query system with proper lifecycle.\n *\n * Accepts a factory function that creates the system.\n * Handles cleanup on component destroy.\n *\n * @example\n * ```svelte\n * <script>\n * import { useQuerySystem, useDerived } from \"@directive-run/svelte\";\n * import { createQuerySystem } from \"@directive-run/query\";\n *\n * const app = useQuerySystem(() =>\n * createQuerySystem({\n * facts: { userId: \"\" },\n * queries: { user: { key: ..., fetcher: ... } },\n * autoStart: false,\n * })\n * );\n *\n * const user = useDerived(app, \"user\");\n * </script>\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nexport function useQuerySystem<T extends { start: () => void; destroy: () => void; isRunning?: boolean; [key: string]: any }>(\n factory: () => T,\n): T {\n const system = factory();\n\n if (typeof window !== \"undefined\" && !system.isRunning) {\n system.start();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n return system;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@directive-run/svelte",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.4",
|
|
4
4
|
"description": "Svelte stores adapter for Directive.",
|
|
5
|
-
"license": "MIT",
|
|
5
|
+
"license": "(MIT OR Apache-2.0)",
|
|
6
6
|
"author": "Jason Comes",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
@@ -44,15 +44,15 @@
|
|
|
44
44
|
"dist"
|
|
45
45
|
],
|
|
46
46
|
"peerDependencies": {
|
|
47
|
-
"@directive-run/core": "
|
|
48
|
-
"svelte": ">=4"
|
|
47
|
+
"@directive-run/core": "^0.8.0",
|
|
48
|
+
"svelte": ">=4 || >=5"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@types/node": "^25.2.0",
|
|
52
|
-
"svelte": "^
|
|
52
|
+
"svelte": "^5.54.0",
|
|
53
53
|
"tsup": "^8.3.5",
|
|
54
54
|
"typescript": "^5.7.2",
|
|
55
|
-
"@directive-run/core": "0.8.
|
|
55
|
+
"@directive-run/core": "0.8.4"
|
|
56
56
|
},
|
|
57
57
|
"scripts": {
|
|
58
58
|
"build": "tsup",
|