@directive-run/svelte 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jason Comes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # @directive-run/svelte
2
+
3
+ Svelte stores adapter for Directive. Provides `Readable` store-based hooks and store factories for reading facts, derivations, and dispatching events.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @directive-run/core @directive-run/svelte
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```svelte
14
+ <script>
15
+ import { useFact, useDerived, useEvents } from "@directive-run/svelte";
16
+
17
+ const count = useFact(system, "count");
18
+ const doubled = useDerived(system, "doubled");
19
+ const events = useEvents(system);
20
+ </script>
21
+
22
+ <p>Count: {$count} (doubled: {$doubled})</p>
23
+ <button on:click={() => events.increment()}>+</button>
24
+ ```
25
+
26
+ ## Exports
27
+
28
+ `useFact`, `useDerived`, `useSelector`, `useDispatch`, `useEvents`, `useWatch`, `useInspect`, `useRequirementStatus`, `useExplain`, `useConstraintStatus`, `useOptimisticUpdate`, `useTimeTravel`, `useDirective`, `createTypedHooks`, `createFactStore`, `createDerivedStore`, `createDerivedsStore`, `createInspectStore`, `shallowEqual`
29
+
30
+ ## Peer Dependencies
31
+
32
+ - `svelte >= 4`
33
+ - `@directive-run/core`
34
+
35
+ ## License
36
+
37
+ MIT
38
+
39
+ [Full documentation](https://directive.run/docs)
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use strict';var svelte=require('svelte'),store=require('svelte/store'),core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils');function w(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),s=>e.subscribe([t],()=>{s(e.read(t));}))}function C(e,t){let s=()=>{let r={};for(let n of t)r[n]=e.read(n);return r};return store.readable(s(),r=>e.subscribe(t,()=>{r(s());}))}function E(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),s=>e.facts.$store.subscribe([t],()=>{s(e.facts.$store.get(t));}))}function j(e){return store.readable(e.inspect(),t=>{let s=()=>t(e.inspect()),r=e.facts.$store.subscribeAll(s),n=e.onSettledChange(s);return ()=>{r(),n();}})}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):E(e,t)}function $(e,t){let s=()=>{let r={};for(let n of t)r[n]=e.facts.$store.get(n);return r};return store.readable(s(),r=>e.facts.$store.subscribe(t,()=>{r(s());}))}function q(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):w(e,t)}function z(e,t,s=adapterUtils.defaultEquality){adapterUtils.assertSystem("useSelector",e);let r=new Set(Object.keys(e.derive??{})),n=()=>adapterUtils.runTrackedSelector(e,r,t),o=n();return store.readable(o.value,a=>{let S=o.value,p=o.factKeys,f=o.deriveKeys,d=[],y=()=>{for(let c of d)c();d.length=0;let b=()=>{let c=n();s(S,c.value)||(S=c.value,a(c.value)),adapterUtils.depsChanged(p,c.factKeys,f,c.deriveKeys)&&(p=c.factKeys,f=c.deriveKeys,y());};p.length>0?d.push(e.facts.$store.subscribe(p,b)):f.length===0&&d.push(e.facts.$store.subscribeAll(b)),f.length>0&&d.push(e.subscribe(f,b));};return y(),()=>{for(let b of d)b();}})}function O(e){return adapterUtils.assertSystem("useDispatch",e),t=>{e.dispatch(t);}}function A(e){return adapterUtils.assertSystem("useEvents",e),e.events}function P(e,t,s,r){adapterUtils.assertSystem("useWatch",e);let n=t==="fact"&&typeof s=="string"&&typeof r=="function",o=n?s:t,a=n?r:s,S=e.watch(o,a);svelte.onDestroy(S);}function H(e,t){return adapterUtils.assertSystem("useInspect",e),t?.throttleMs&&t.throttleMs>0?store.readable(adapterUtils.computeInspectState(e),s=>{let{throttled:r,cleanup:n}=adapterUtils.createThrottle(()=>{s(adapterUtils.computeInspectState(e));},t.throttleMs),o=e.facts.$store.subscribeAll(r),a=e.onSettledChange(r);return ()=>{n(),o(),a();}}):store.readable(adapterUtils.computeInspectState(e),s=>{let r=()=>s(adapterUtils.computeInspectState(e)),n=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{n(),o();}})}function L(e,t){if(Array.isArray(t)){let s=()=>{let r={};for(let n of t)r[n]=e.getStatus(n);return r};return store.readable(s(),r=>e.subscribe(()=>{r(s());}))}return store.readable(e.getStatus(t),s=>e.subscribe(()=>{s(e.getStatus(t));}))}function G(e,t){return adapterUtils.assertSystem("useExplain",e),store.readable(e.explain(t),s=>{let r=()=>s(e.explain(t)),n=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{n(),o();}})}function J(e,t){return adapterUtils.assertSystem("useConstraintStatus",e),store.readable(x(e,t),s=>{let r=()=>s(x(e,t)),n=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{n(),o();}})}function x(e,t){let s=e.inspect();return t?s.constraints.find(r=>r.id===t)??null:s.constraints}function Q(e,t,s){adapterUtils.assertSystem("useOptimisticUpdate",e);let r=false,n=null,o=null,a=null,S=new Set,p=new Set,f={subscribe(u){return u(r),S.add(u),()=>S.delete(u)}},d={subscribe(u){return u(n),p.add(u),()=>p.delete(u)}},y=u=>{r=u;for(let v of S)v(u);},b=u=>{n=u;for(let v of p)v(u);},c=()=>{o&&(e.restore(o),o=null),y(false),b(null),a?.(),a=null;},l=u=>{o=e.getSnapshot(),y(true),b(null),e.batch(u),t&&s&&(a?.(),a=t.subscribe(()=>{let v=t.getStatus(s);!v.isLoading&&!v.hasError?(o=null,y(false),a?.(),a=null):v.hasError&&(b(v.lastError),c());}));};return svelte.onDestroy(()=>{a?.();}),{mutate:l,isPending:f,error:d,rollback:c}}function X(e){return adapterUtils.assertSystem("useTimeTravel",e),store.readable(adapterUtils.buildTimeTravelState(e),t=>e.onTimeTravelChange(()=>t(adapterUtils.buildTimeTravelState(e))))}function Y(e,t){let s=[...t?.plugins??[]],r;if(t?.status){let l=core.createRequirementStatusPlugin();r=l,s.push(l.plugin);}let n=core.createSystem({module:e,plugins:s.length>0?s:void 0,debug:t?.debug,errorBoundary:t?.errorBoundary,tickMs:t?.tickMs,zeroConfig:t?.zeroConfig,initialFacts:t?.initialFacts});n.start(),svelte.onDestroy(()=>{n.destroy();});let o=t?.facts,a=t?.derived,S=!o&&!a,p=S?store.readable(n.facts.$store.toObject(),l=>n.facts.$store.subscribeAll(()=>{l(n.facts.$store.toObject());})):store.readable(adapterUtils.pickFacts(n,o??[]),l=>!o||o.length===0?()=>{}:n.facts.$store.subscribe(o,()=>{l(adapterUtils.pickFacts(n,o));})),f=S?Object.keys(n.derive??{}):a??[],d=()=>{let l={};for(let u of f)l[u]=n.read(u);return l},y=f.length>0?store.readable(d(),l=>n.subscribe(f,()=>{l(d());})):store.readable(d(),()=>()=>{}),b=n.events;return {system:n,facts:p,derived:y,events:b,dispatch:l=>n.dispatch(l),statusPlugin:r}}function Z(){return {useFact:(e,t)=>V(e,t),useDerived:(e,t)=>q(e,t),useDispatch:e=>t=>{e.dispatch(t);},useEvents:e=>A(e),useWatch:(e,t,s)=>P(e,t,s)}}Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return adapterUtils.shallowEqual}});exports.createDerivedStore=w;exports.createDerivedsStore=C;exports.createFactStore=E;exports.createInspectStore=j;exports.createTypedHooks=Z;exports.useConstraintStatus=J;exports.useDerived=q;exports.useDirective=Y;exports.useDispatch=O;exports.useEvents=A;exports.useExplain=G;exports.useFact=V;exports.useInspect=H;exports.useOptimisticUpdate=Q;exports.useRequirementStatus=L;exports.useSelector=z;exports.useTimeTravel=X;exports.useWatch=P;//# sourceMappingURL=index.cjs.map
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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","derivationIdOrKind","callbackOrFactKey","maybeCallback","isFact","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","useTimeTravel","buildTimeTravelState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks"],"mappings":"sKA6DO,SAASA,CAAAA,CAEfC,CAAAA,CACAC,EACc,CACd,OAAI,OAAA,CAAQ,GAAA,CAAI,WAAa,YAAA,EACPD,CAAAA,CAAO,IAAA,CAAKC,CAAY,IACxB,MAAA,EACpB,OAAA,CAAQ,IAAA,CACP,CAAA,gCAAA,EAAmCA,CAAY,CAAA,mCAAA,EAChCA,CAAY,gDAC5B,CAAA,CAIKC,cAAAA,CAAYF,EAAO,IAAA,CAAKC,CAAY,CAAA,CAASE,CAAAA,EAC/BH,EAAO,SAAA,CAAU,CAACC,CAAY,CAAA,CAAG,IAAM,CAC1DE,CAAAA,CAAIH,CAAAA,CAAO,IAAA,CAAKC,CAAY,CAAM,EACnC,CAAC,CAED,CACF,CAKO,SAASG,CAAAA,CAEfJ,CAAAA,CACAK,CAAAA,CACc,CACd,IAAMC,CAAAA,CAAY,IAAS,CAC1B,IAAMC,CAAAA,CAAkC,EAAC,CACzC,IAAA,IAAWC,KAAMH,CAAAA,CAChBE,CAAAA,CAAOC,CAAE,CAAA,CAAIR,EAAO,IAAA,CAAKQ,CAAE,CAAA,CAE5B,OAAOD,CACR,CAAA,CAEA,OAAOL,cAAAA,CAAYI,CAAAA,GAAcH,CAAAA,EACZH,CAAAA,CAAO,SAAA,CAAUK,CAAAA,CAAe,IAAM,CACzDF,CAAAA,CAAIG,GAAW,EAChB,C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AA8CF,CAAAA,CAAkB,MAAA,CAAS,CAAA,CAC5EhG,cAAAA,CAASiG,GAAW,CAAIhG,CAAAA,EAClBH,EAAO,SAAA,CAAUkG,CAAAA,CAAmB,IAAM,CAChD/F,CAAAA,CAAIgG,CAAAA,EAAY,EACjB,CAAC,CACD,CAAA,CACCjG,cAAAA,CAASiG,GAAW,CAAG,IAAM,IAAM,CAAC,CAAC,CAAA,CAElCE,CAAAA,CAASrG,EAAO,MAAA,CAGtB,OAAO,CACN,MAAA,CAAAA,CAAAA,CACA,KAAA,CAAOgG,CAAAA,CACP,QAASI,CAAAA,CACT,MAAA,CAAAC,CAAAA,CACA,QAAA,CAPiB7D,GAA0BxC,CAAAA,CAAO,QAAA,CAASwC,CAAK,CAAA,CAQhE,aAAAiB,CACD,CACD,CAMO,SAAS6C,CAAAA,EAgBd,CACD,OAAO,CACN,OAAA,CAAS,CAAyCtG,EAA+BU,CAAAA,GAEhFK,CAAAA,CAAQf,CAAAA,CAAmCU,CAAO,EACnD,UAAA,CAAY,CAA+CV,CAAAA,CAA+BC,CAAAA,GAEzFoB,EAAWrB,CAAAA,CAAmCC,CAAY,EAC3D,WAAA,CAAcD,CAAAA,EACLwC,GAA0B,CACjCxC,CAAAA,CAAO,QAAA,CAASwC,CAAK,EACtB,CAAA,CAED,SAAA,CAAYxC,CAAAA,EAAkCyC,CAAAA,CAAazC,CAAM,CAAA,CACjE,QAAA,CAAU,CACTA,CAAAA,CACAoB,EACA2B,CAAAA,GAGAL,CAAAA,CAAS1C,EAAmCoB,CAAAA,CAAK2B,CAAQ,CAC3D,CACD","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, useTimeTravel,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport { onDestroy } from \"svelte\";\nimport { readable, type Readable } from \"svelte/store\";\nimport type {\n\tModuleSchema,\n\tModuleDef,\n\tPlugin,\n\tDebugConfig,\n\tErrorBoundaryConfig,\n\tInferFacts,\n\tInferDerivations,\n\tInferSelectorState,\n\tInferEvents,\n\tSingleModuleSystem,\n\tSystemInspection,\n\tSystemSnapshot,\n\tTimeTravelState,\n} from \"@directive-run/core\";\nimport {\n\tcreateSystem,\n\tcreateRequirementStatusPlugin,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n\ttype InspectState,\n\ttype ConstraintInfo,\n\tcomputeInspectState,\n\tcreateThrottle,\n\tassertSystem,\n\tdefaultEquality,\n\tbuildTimeTravelState,\n\tpickFacts,\n\trunTrackedSelector,\n\tdepsChanged,\n\tshallowEqual,\n} from \"@directive-run/core/adapter-utils\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\tsystem: SingleModuleSystem<any>,\n\tderivationId: string,\n): Readable<T> {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst initialValue = system.read(derivationId);\n\t\tif (initialValue === undefined) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n\t\t\t\t`Check that \"${derivationId}\" is defined in your module's derive property.`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn readable<T>(system.read(derivationId) as T, (set) => {\n\t\tconst unsubscribe = system.subscribe([derivationId], () => {\n\t\t\tset(system.read(derivationId) as T);\n\t\t});\n\t\treturn unsubscribe;\n\t});\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\tsystem: SingleModuleSystem<any>,\n\tderivationIds: string[],\n): Readable<T> {\n\tconst getValues = (): T => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const id of derivationIds) {\n\t\t\tresult[id] = system.read(id);\n\t\t}\n\t\treturn result as T;\n\t};\n\n\treturn readable<T>(getValues(), (set) => {\n\t\tconst unsubscribe = system.subscribe(derivationIds, () => {\n\t\t\tset(getValues());\n\t\t});\n\t\treturn unsubscribe;\n\t});\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\tsystem: SingleModuleSystem<any>,\n\tfactKey: string,\n): Readable<T | undefined> {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!system.facts.$store.has(factKey)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n\t\t\t\t`Check that \"${factKey}\" is defined in your module's schema.`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn readable<T | undefined>(\n\t\tsystem.facts.$store.get(factKey) as T | undefined,\n\t\t(set) => {\n\t\t\tconst unsubscribe = system.facts.$store.subscribe([factKey], () => {\n\t\t\t\tset(system.facts.$store.get(factKey) as T | undefined);\n\t\t\t});\n\t\t\treturn unsubscribe;\n\t\t},\n\t);\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\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\tsystem: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n\treturn readable<SystemInspection>(system.inspect(), (set) => {\n\t\tconst update = () => set(system.inspect());\n\t\tconst unsubFacts = system.facts.$store.subscribeAll(update);\n\t\tconst unsubSettled = system.onSettledChange(update);\n\t\treturn () => {\n\t\t\tunsubFacts();\n\t\t\tunsubSettled();\n\t\t};\n\t});\n}\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKeys: K[]): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tkeyOrKeys: string | string[],\n): Readable<unknown> {\n\tassertSystem(\"useFact\", system);\n\tif (process.env.NODE_ENV !== \"production\" && typeof keyOrKeys === \"function\") {\n\t\tconsole.error(\n\t\t\t\"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n\t\t\t\t\"useFact() takes a string key or array of keys, not a selector function.\",\n\t\t);\n\t}\n\n\t// Multi-key path: useFact(system, [keys])\n\tif (Array.isArray(keyOrKeys)) {\n\t\treturn _useFactMulti(system, keyOrKeys);\n\t}\n\n\t// Single key path: useFact(system, key)\n\treturn createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(system: SingleModuleSystem<any>, factKeys: string[]): Readable<Record<string, unknown>> {\n\tconst getValues = (): Record<string, unknown> => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of factKeys) {\n\t\t\tresult[key] = system.facts.$store.get(key);\n\t\t}\n\t\treturn result;\n\t};\n\n\treturn readable(getValues(), (set) => {\n\t\tconst unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n\t\t\tset(getValues());\n\t\t});\n\t\treturn unsubscribe;\n\t});\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationId: K): Readable<InferDerivations<S>[K]>;\n/** Multi-key overload */\nexport function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationIds: K[]): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tidOrIds: string | string[],\n): Readable<unknown> {\n\tassertSystem(\"useDerived\", system);\n\tif (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"function\") {\n\t\tconsole.error(\n\t\t\t\"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n\t\t\t\t\"useDerived() takes a string key or array of keys, not a selector function.\",\n\t\t);\n\t}\n\n\t// Multi-key path\n\tif (Array.isArray(idOrIds)) {\n\t\treturn createDerivedsStore(system, idOrIds);\n\t}\n\n\t// Single key path\n\treturn 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>(system: SingleModuleSystem<S>, selector: (state: InferSelectorState<S>) => R, equalityFn?: (a: R, b: R) => boolean): Readable<R>;\nexport function useSelector<R>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any>,\n\t// biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n\tselector: (state: Record<string, any>) => R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tselector: (state: any) => unknown,\n\tequalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n\tassertSystem(\"useSelector\", system);\n\tconst deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n\t// Build a tracking-aware state proxy that exposes both facts and derivations\n\tconst runWithTracking = () => runTrackedSelector(system, deriveKeySet, selector);\n\n\tconst initial = runWithTracking();\n\n\treturn readable(initial.value, (set) => {\n\t\tlet currentSelected = initial.value;\n\t\tlet trackedFactKeys = initial.factKeys;\n\t\tlet trackedDeriveKeys = initial.deriveKeys;\n\t\tconst unsubs: Array<() => void> = [];\n\n\t\tconst resubscribe = () => {\n\t\t\tfor (const unsub of unsubs) unsub();\n\t\t\tunsubs.length = 0;\n\n\t\t\tconst onUpdate = () => {\n\t\t\t\tconst result = runWithTracking();\n\t\t\t\tif (!equalityFn(currentSelected, result.value)) {\n\t\t\t\t\tcurrentSelected = result.value;\n\t\t\t\t\tset(result.value);\n\t\t\t\t}\n\t\t\t\t// Re-track: check if deps changed\n\t\t\t\tif (depsChanged(trackedFactKeys, result.factKeys, trackedDeriveKeys, result.deriveKeys)) {\n\t\t\t\t\ttrackedFactKeys = result.factKeys;\n\t\t\t\t\ttrackedDeriveKeys = result.deriveKeys;\n\t\t\t\t\tresubscribe();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tif (trackedFactKeys.length > 0) {\n\t\t\t\tunsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n\t\t\t} else if (trackedDeriveKeys.length === 0) {\n\t\t\t\tunsubs.push(system.facts.$store.subscribeAll(onUpdate));\n\t\t\t}\n\t\t\tif (trackedDeriveKeys.length > 0) {\n\t\t\t\tunsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n\t\t\t}\n\t\t};\n\n\t\tresubscribe();\n\n\t\treturn () => {\n\t\t\tfor (const unsub of unsubs) unsub();\n\t\t};\n\t});\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n\tsystem: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n\tassertSystem(\"useDispatch\", system);\n\treturn (event: InferEvents<S>) => {\n\t\tsystem.dispatch(event);\n\t};\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\tsystem: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n\tassertSystem(\"useEvents\", system);\n\treturn 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<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tkey: K,\n\tcallback: (newValue: InferDerivations<S>[K], previousValue: InferDerivations<S>[K] | undefined) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tkey: K,\n\tcallback: (newValue: InferFacts<S>[K] | undefined, previousValue: InferFacts<S>[K] | undefined) => void,\n): void;\n/**\n * Watch a fact by explicit \"fact\" discriminator.\n * @deprecated Use `useWatch(system, key, callback)` instead — facts are now auto-detected.\n */\nexport function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tkind: \"fact\",\n\tfactKey: K,\n\tcallback: (newValue: InferFacts<S>[K] | undefined, previousValue: InferFacts<S>[K] | undefined) => void,\n): void;\n/** Watch a fact or derivation (generic fallback) */\nexport function useWatch<T>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any>,\n\tkey: string,\n\tcallback: (newValue: T, previousValue: T | undefined) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tderivationIdOrKind: string,\n\tcallbackOrFactKey: string | ((newValue: unknown, prevValue: unknown) => void),\n\tmaybeCallback?: (newValue: unknown, prevValue: unknown) => void,\n): void {\n\tassertSystem(\"useWatch\", system);\n\t// Backward compat: useWatch(system, \"fact\", factKey, callback)\n\tconst isFact =\n\t\tderivationIdOrKind === \"fact\" &&\n\t\ttypeof callbackOrFactKey === \"string\" &&\n\t\ttypeof maybeCallback === \"function\";\n\n\tconst key = isFact ? (callbackOrFactKey as string) : derivationIdOrKind;\n\tconst callback = isFact\n\t\t? maybeCallback!\n\t\t: (callbackOrFactKey as (newValue: unknown, prevValue: unknown) => void);\n\n\tconst unsubscribe = system.watch(key, callback);\n\tonDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n\tthrottleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\toptions?: UseInspectOptions,\n): Readable<InspectState> {\n\tassertSystem(\"useInspect\", system);\n\tif (options?.throttleMs && options.throttleMs > 0) {\n\t\treturn readable<InspectState>(computeInspectState(system), (set) => {\n\t\t\tconst { throttled, cleanup } = createThrottle(() => {\n\t\t\t\tset(computeInspectState(system));\n\t\t\t}, options.throttleMs!);\n\n\t\t\tconst unsubFacts = system.facts.$store.subscribeAll(throttled);\n\t\t\tconst unsubSettled = system.onSettledChange(throttled);\n\n\t\t\treturn () => {\n\t\t\t\tcleanup();\n\t\t\t\tunsubFacts();\n\t\t\t\tunsubSettled();\n\t\t\t};\n\t\t});\n\t}\n\n\treturn readable<InspectState>(computeInspectState(system), (set) => {\n\t\tconst update = () => set(computeInspectState(system));\n\t\tconst unsubFacts = system.facts.$store.subscribeAll(update);\n\t\tconst unsubSettled = system.onSettledChange(update);\n\n\t\treturn () => {\n\t\t\tunsubFacts();\n\t\t\tunsubSettled();\n\t\t};\n\t});\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(statusPlugin: StatusPlugin, type: string): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(statusPlugin: StatusPlugin, types: string[]): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n\tstatusPlugin: StatusPlugin,\n\ttypeOrTypes: string | string[],\n): Readable<RequirementTypeStatus> | Readable<Record<string, RequirementTypeStatus>> {\n\tif (Array.isArray(typeOrTypes)) {\n\t\tconst getValues = (): Record<string, RequirementTypeStatus> => {\n\t\t\tconst result: Record<string, RequirementTypeStatus> = {};\n\t\t\tfor (const type of typeOrTypes) {\n\t\t\t\tresult[type] = statusPlugin.getStatus(type);\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\n\t\treturn readable(getValues(), (set) => {\n\t\t\tconst unsubscribe = statusPlugin.subscribe(() => {\n\t\t\t\tset(getValues());\n\t\t\t});\n\t\t\treturn unsubscribe;\n\t\t});\n\t}\n\n\treturn readable<RequirementTypeStatus>(statusPlugin.getStatus(typeOrTypes), (set) => {\n\t\tconst unsubscribe = statusPlugin.subscribe(() => {\n\t\t\tset(statusPlugin.getStatus(typeOrTypes));\n\t\t});\n\t\treturn unsubscribe;\n\t});\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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\trequirementId: string,\n): Readable<string | null> {\n\tassertSystem(\"useExplain\", system);\n\treturn readable<string | null>(system.explain(requirementId), (set) => {\n\t\tconst update = () => set(system.explain(requirementId));\n\t\tconst unsubFacts = system.facts.$store.subscribeAll(update);\n\t\tconst unsubSettled = system.onSettledChange(update);\n\n\t\treturn () => {\n\t\t\tunsubFacts();\n\t\t\tunsubSettled();\n\t\t};\n\t});\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n\tsystem: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId: string,\n): Readable<ConstraintInfo | null>;\n/** Implementation */\nexport function useConstraintStatus(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId?: string,\n): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n\tassertSystem(\"useConstraintStatus\", system);\n\treturn readable<ConstraintInfo[] | ConstraintInfo | null>(\n\t\t_getConstraintValue(system, constraintId),\n\t\t(set) => {\n\t\t\tconst update = () => set(_getConstraintValue(system, constraintId));\n\t\t\tconst unsubFacts = system.facts.$store.subscribeAll(update);\n\t\t\tconst unsubSettled = system.onSettledChange(update);\n\n\t\t\treturn () => {\n\t\t\t\tunsubFacts();\n\t\t\t\tunsubSettled();\n\t\t\t};\n\t\t},\n\t);\n}\n\nfunction _getConstraintValue(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n\tconst inspection = system.inspect();\n\tif (!constraintId) return inspection.constraints;\n\treturn inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ?? null;\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n\tmutate: (updateFn: () => void) => void;\n\tisPending: Readable<boolean>;\n\terror: Readable<Error | null>;\n\trollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n */\nexport function useOptimisticUpdate(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\tstatusPlugin?: StatusPlugin,\n\trequirementType?: string,\n): OptimisticUpdateResult {\n\tassertSystem(\"useOptimisticUpdate\", system);\n\tlet isPendingValue = false;\n\tlet errorValue: Error | null = null;\n\tlet snapshot: SystemSnapshot | null = null;\n\tlet statusUnsub: (() => void) | null = null;\n\n\t// We track subscribers manually since we need imperative push\n\tconst pendingSubscribers = new Set<(v: boolean) => void>();\n\tconst errorSubscribers = new Set<(v: Error | null) => void>();\n\n\tconst isPending: Readable<boolean> = {\n\t\tsubscribe(fn) {\n\t\t\tfn(isPendingValue);\n\t\t\tpendingSubscribers.add(fn);\n\t\t\treturn () => pendingSubscribers.delete(fn);\n\t\t},\n\t};\n\n\tconst error: Readable<Error | null> = {\n\t\tsubscribe(fn) {\n\t\t\tfn(errorValue);\n\t\t\terrorSubscribers.add(fn);\n\t\t\treturn () => errorSubscribers.delete(fn);\n\t\t},\n\t};\n\n\tconst setPending = (v: boolean) => {\n\t\tisPendingValue = v;\n\t\tfor (const fn of pendingSubscribers) fn(v);\n\t};\n\n\tconst setError = (v: Error | null) => {\n\t\terrorValue = v;\n\t\tfor (const fn of errorSubscribers) fn(v);\n\t};\n\n\tconst rollback = () => {\n\t\tif (snapshot) {\n\t\t\tsystem.restore(snapshot);\n\t\t\tsnapshot = null;\n\t\t}\n\t\tsetPending(false);\n\t\tsetError(null);\n\t\tstatusUnsub?.();\n\t\tstatusUnsub = null;\n\t};\n\n\tconst mutate = (updateFn: () => void) => {\n\t\tsnapshot = system.getSnapshot();\n\t\tsetPending(true);\n\t\tsetError(null);\n\t\tsystem.batch(updateFn);\n\n\t\tif (statusPlugin && requirementType) {\n\t\t\tstatusUnsub?.();\n\t\t\tstatusUnsub = statusPlugin.subscribe(() => {\n\t\t\t\tconst status = statusPlugin.getStatus(requirementType);\n\t\t\t\tif (!status.isLoading && !status.hasError) {\n\t\t\t\t\tsnapshot = null;\n\t\t\t\t\tsetPending(false);\n\t\t\t\t\tstatusUnsub?.();\n\t\t\t\t\tstatusUnsub = null;\n\t\t\t\t} else if (status.hasError) {\n\t\t\t\t\tsetError(status.lastError);\n\t\t\t\t\trollback();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n\n\tonDestroy(() => {\n\t\tstatusUnsub?.();\n\t});\n\n\treturn { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useTimeTravel — reactive time-travel store\n// ============================================================================\n\n/**\n * Reactive time-travel Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const tt = useTimeTravel(system);\n * <button disabled={!$tt?.canUndo} on:click={() => $tt?.undo()}>Undo</button>\n * ```\n */\nexport function useTimeTravel(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n): Readable<TimeTravelState | null> {\n\tassertSystem(\"useTimeTravel\", system);\n\treturn readable<TimeTravelState | null>(buildTimeTravelState(system), (set) => {\n\t\treturn system.onTimeTravelChange(() => set(buildTimeTravelState(system)));\n\t});\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\ninterface UseDirectiveConfig {\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n\tplugins?: Plugin<any>[];\n\tdebug?: DebugConfig;\n\terrorBoundary?: ErrorBoundaryConfig;\n\ttickMs?: number;\n\tzeroConfig?: boolean;\n\t// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n\tinitialFacts?: Record<string, any>;\n\tstatus?: boolean;\n\t/** Fact keys to subscribe to (omit for all) */\n\tfacts?: string[];\n\t/** Derivation keys to subscribe to (omit for all) */\n\tderived?: 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\tmoduleDef: ModuleDef<M>,\n\tconfig?: UseDirectiveConfig,\n) {\n\tconst allPlugins = [...(config?.plugins ?? [])];\n\tlet statusPlugin: StatusPlugin | undefined;\n\n\tif (config?.status) {\n\t\tconst sp = createRequirementStatusPlugin();\n\t\tstatusPlugin = sp;\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n\t\tallPlugins.push(sp.plugin as Plugin<any>);\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\tconst system = createSystem({\n\t\tmodule: moduleDef,\n\t\tplugins: allPlugins.length > 0 ? allPlugins : undefined,\n\t\tdebug: config?.debug,\n\t\terrorBoundary: config?.errorBoundary,\n\t\ttickMs: config?.tickMs,\n\t\tzeroConfig: config?.zeroConfig,\n\t\tinitialFacts: config?.initialFacts,\n\t} as any) as unknown as SingleModuleSystem<M>;\n\n\tsystem.start();\n\n\tonDestroy(() => {\n\t\tsystem.destroy();\n\t});\n\n\tconst factKeys = config?.facts;\n\tconst derivedKeys = config?.derived;\n\tconst subscribeAll = !factKeys && !derivedKeys;\n\n\t// Subscribe to facts\n\tconst factsStore: Readable<InferFacts<M>> = subscribeAll\n\t\t? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n\t\t\treturn system.facts.$store.subscribeAll(() => {\n\t\t\t\tset(system.facts.$store.toObject() as InferFacts<M>);\n\t\t\t});\n\t\t})\n\t\t: readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n\t\t\tif (!factKeys || factKeys.length === 0) return () => {};\n\t\t\treturn system.facts.$store.subscribe(factKeys, () => {\n\t\t\t\tset(pickFacts(system, factKeys) as InferFacts<M>);\n\t\t\t});\n\t\t});\n\n\t// Subscribe to derivations\n\tconst allDerivationKeys = subscribeAll ? Object.keys(system.derive ?? {}) : (derivedKeys ?? []);\n\tconst getDerived = (): InferDerivations<M> => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of allDerivationKeys) {\n\t\t\tresult[key] = system.read(key);\n\t\t}\n\t\treturn result as InferDerivations<M>;\n\t};\n\tconst derivedStore: Readable<InferDerivations<M>> = allDerivationKeys.length > 0\n\t\t? readable(getDerived(), (set) => {\n\t\t\treturn system.subscribe(allDerivationKeys, () => {\n\t\t\t\tset(getDerived());\n\t\t\t});\n\t\t})\n\t\t: readable(getDerived(), () => () => {});\n\n\tconst events = system.events;\n\tconst dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n\treturn {\n\t\tsystem,\n\t\tfacts: factsStore,\n\t\tderived: derivedStore,\n\t\tevents,\n\t\tdispatch,\n\t\tstatusPlugin,\n\t};\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n\tuseFact: <K extends keyof InferFacts<M> & string>(\n\t\tsystem: SingleModuleSystem<M>,\n\t\tfactKey: K,\n\t) => Readable<InferFacts<M>[K] | undefined>;\n\tuseDerived: <K extends keyof InferDerivations<M> & string>(\n\t\tsystem: SingleModuleSystem<M>,\n\t\tderivationId: K,\n\t) => Readable<InferDerivations<M>[K]>;\n\tuseDispatch: (system: SingleModuleSystem<M>) => (event: InferEvents<M>) => void;\n\tuseEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>[\"events\"];\n\tuseWatch: <K extends string>(\n\t\tsystem: SingleModuleSystem<M>,\n\t\tkey: K,\n\t\tcallback: (newValue: unknown, previousValue: unknown) => void,\n\t) => void;\n} {\n\treturn {\n\t\tuseFact: <K extends keyof InferFacts<M> & string>(system: SingleModuleSystem<M>, factKey: K) =>\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n\t\t\tuseFact(system as SingleModuleSystem<any>, factKey) as Readable<InferFacts<M>[K] | undefined>,\n\t\tuseDerived: <K extends keyof InferDerivations<M> & string>(system: SingleModuleSystem<M>, derivationId: K) =>\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n\t\t\tuseDerived(system as SingleModuleSystem<any>, derivationId) as Readable<InferDerivations<M>[K]>,\n\t\tuseDispatch: (system: SingleModuleSystem<M>) => {\n\t\t\treturn (event: InferEvents<M>) => {\n\t\t\t\tsystem.dispatch(event);\n\t\t\t};\n\t\t},\n\t\tuseEvents: (system: SingleModuleSystem<M>) => useEvents<M>(system),\n\t\tuseWatch: <K extends string>(\n\t\t\tsystem: SingleModuleSystem<M>,\n\t\t\tkey: K,\n\t\t\tcallback: (newValue: unknown, previousValue: unknown) => void,\n\t\t) =>\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n\t\t\tuseWatch(system as SingleModuleSystem<any>, key, callback),\n\t};\n}\n"]}
@@ -0,0 +1,153 @@
1
+ import * as _directive_run_core from '@directive-run/core';
2
+ import { createRequirementStatusPlugin, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, Plugin, DebugConfig, ErrorBoundaryConfig, RequirementTypeStatus, InferSelectorState, TimeTravelState } from '@directive-run/core';
3
+ export { RequirementTypeStatus } from '@directive-run/core';
4
+ import { Readable } from 'svelte/store';
5
+ import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
6
+ export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
7
+
8
+ /** Type for the requirement status plugin return value */
9
+ type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;
10
+ /**
11
+ * Create a Svelte store for a derived value.
12
+ */
13
+ declare function createDerivedStore<T>(system: SingleModuleSystem<any>, derivationId: string): Readable<T>;
14
+ /**
15
+ * Create a Svelte store for multiple derived values.
16
+ */
17
+ declare function createDerivedsStore<T extends Record<string, unknown>>(system: SingleModuleSystem<any>, derivationIds: string[]): Readable<T>;
18
+ /**
19
+ * Create a Svelte store for a single fact value.
20
+ */
21
+ declare function createFactStore<T>(system: SingleModuleSystem<any>, factKey: string): Readable<T | undefined>;
22
+ /**
23
+ * Create a Svelte store for system inspection data.
24
+ * NOTE: This updates on every fact change. Use sparingly in production.
25
+ */
26
+ declare function createInspectStore(system: SingleModuleSystem<any>): Readable<SystemInspection>;
27
+ /** Single key overload */
28
+ declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K): Readable<InferFacts<S>[K] | undefined>;
29
+ /** Multi-key overload */
30
+ declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKeys: K[]): Readable<Pick<InferFacts<S>, K>>;
31
+ /** Single key overload */
32
+ declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationId: K): Readable<InferDerivations<S>[K]>;
33
+ /** Multi-key overload */
34
+ declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationIds: K[]): Readable<Pick<InferDerivations<S>, K>>;
35
+ /**
36
+ * Auto-tracking selector over facts and derivations.
37
+ * Uses `withTracking()` to detect which facts the selector accesses,
38
+ * then subscribes only to those keys.
39
+ */
40
+ declare function useSelector<S extends ModuleSchema, R>(system: SingleModuleSystem<S>, selector: (state: InferSelectorState<S>) => R, equalityFn?: (a: R, b: R) => boolean): Readable<R>;
41
+ declare function useSelector<R>(system: SingleModuleSystem<any>, selector: (state: Record<string, any>) => R, equalityFn?: (a: R, b: R) => boolean): Readable<R>;
42
+ declare function useDispatch<S extends ModuleSchema>(system: SingleModuleSystem<S>): (event: InferEvents<S>) => void;
43
+ /**
44
+ * Returns the system's events dispatcher.
45
+ */
46
+ declare function useEvents<S extends ModuleSchema>(system: SingleModuleSystem<S>): SingleModuleSystem<S>["events"];
47
+ /** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */
48
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, key: K, callback: (newValue: InferDerivations<S>[K], previousValue: InferDerivations<S>[K] | undefined) => void): void;
49
+ /** Watch a fact key with auto-detection. */
50
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, key: K, callback: (newValue: InferFacts<S>[K] | undefined, previousValue: InferFacts<S>[K] | undefined) => void): void;
51
+ /**
52
+ * Watch a fact by explicit "fact" discriminator.
53
+ * @deprecated Use `useWatch(system, key, callback)` instead — facts are now auto-detected.
54
+ */
55
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, kind: "fact", factKey: K, callback: (newValue: InferFacts<S>[K] | undefined, previousValue: InferFacts<S>[K] | undefined) => void): void;
56
+ /** Watch a fact or derivation (generic fallback) */
57
+ declare function useWatch<T>(system: SingleModuleSystem<any>, key: string, callback: (newValue: T, previousValue: T | undefined) => void): void;
58
+ /** Options for useInspect */
59
+ interface UseInspectOptions {
60
+ throttleMs?: number;
61
+ }
62
+ /**
63
+ * Consolidated system inspection hook.
64
+ * Returns Readable<InspectState> with optional throttling.
65
+ */
66
+ declare function useInspect(system: SingleModuleSystem<any>, options?: UseInspectOptions): Readable<InspectState>;
67
+ /** Single type overload */
68
+ declare function useRequirementStatus(statusPlugin: StatusPlugin, type: string): Readable<RequirementTypeStatus>;
69
+ /** Multi-type overload */
70
+ declare function useRequirementStatus(statusPlugin: StatusPlugin, types: string[]): Readable<Record<string, RequirementTypeStatus>>;
71
+ /**
72
+ * Reactively returns the explanation string for a requirement.
73
+ */
74
+ declare function useExplain(system: SingleModuleSystem<any>, requirementId: string): Readable<string | null>;
75
+ /** Get all constraints */
76
+ declare function useConstraintStatus(system: SingleModuleSystem<any>): Readable<ConstraintInfo[]>;
77
+ /** Get a single constraint by ID */
78
+ declare function useConstraintStatus(system: SingleModuleSystem<any>, constraintId: string): Readable<ConstraintInfo | null>;
79
+ interface OptimisticUpdateResult {
80
+ mutate: (updateFn: () => void) => void;
81
+ isPending: Readable<boolean>;
82
+ error: Readable<Error | null>;
83
+ rollback: () => void;
84
+ }
85
+ /**
86
+ * Optimistic update hook. Saves a snapshot before mutating, monitors
87
+ * a requirement type via statusPlugin, and rolls back on failure.
88
+ */
89
+ declare function useOptimisticUpdate(system: SingleModuleSystem<any>, statusPlugin?: StatusPlugin, requirementType?: string): OptimisticUpdateResult;
90
+ /**
91
+ * Reactive time-travel Svelte store. Returns a Readable that updates
92
+ * when snapshots are taken or navigation occurs.
93
+ *
94
+ * @example
95
+ * ```svelte
96
+ * const tt = useTimeTravel(system);
97
+ * <button disabled={!$tt?.canUndo} on:click={() => $tt?.undo()}>Undo</button>
98
+ * ```
99
+ */
100
+ declare function useTimeTravel(system: SingleModuleSystem<any>): Readable<TimeTravelState | null>;
101
+ /** Configuration for useDirective */
102
+ interface UseDirectiveConfig {
103
+ plugins?: Plugin<any>[];
104
+ debug?: DebugConfig;
105
+ errorBoundary?: ErrorBoundaryConfig;
106
+ tickMs?: number;
107
+ zeroConfig?: boolean;
108
+ initialFacts?: Record<string, any>;
109
+ status?: boolean;
110
+ /** Fact keys to subscribe to (omit for all) */
111
+ facts?: string[];
112
+ /** Derivation keys to subscribe to (omit for all) */
113
+ derived?: string[];
114
+ }
115
+ /**
116
+ * Create a scoped Directive system with automatic lifecycle management.
117
+ * When no `facts` or `derived` keys are specified, subscribes to ALL
118
+ * facts and derivations and returns Svelte readable stores.
119
+ *
120
+ * @example
121
+ * ```svelte
122
+ * // Subscribe to everything
123
+ * const { facts, derived, events, dispatch } = useDirective(counterModule);
124
+ *
125
+ * // Selective keys
126
+ * const { facts, derived } = useDirective(counterModule, { facts: ["count"], derived: ["doubled"] });
127
+ * ```
128
+ */
129
+ declare function useDirective<M extends ModuleSchema>(moduleDef: ModuleDef<M>, config?: UseDirectiveConfig): {
130
+ system: SingleModuleSystem<M>;
131
+ facts: Readable<_directive_run_core.InferSchema<M["facts"]>>;
132
+ derived: Readable<InferDerivations<M>>;
133
+ events: M["events"] extends Record<string, unknown> ? { [E in keyof M["events"]]: M["events"][E] extends Record<string, unknown> ? keyof M["events"][E] extends never ? () => void : (payload: M["events"][E] extends infer T ? T extends M["events"][E] ? T extends Record<string, unknown> ? { [K in keyof T]: T[K] extends {
134
+ _type: infer T_1;
135
+ } ? T_1 : T[K]; } : never : never : never) => void : () => void; } : Record<string, never>;
136
+ dispatch: (event: InferEvents<M>) => void;
137
+ statusPlugin: {
138
+ plugin: Plugin<never>;
139
+ getStatus: (type: string) => RequirementTypeStatus;
140
+ getAllStatus: () => Map<string, RequirementTypeStatus>;
141
+ subscribe: (listener: () => void) => () => void;
142
+ reset: () => void;
143
+ } | undefined;
144
+ };
145
+ declare function createTypedHooks<M extends ModuleSchema>(): {
146
+ useFact: <K extends keyof InferFacts<M> & string>(system: SingleModuleSystem<M>, factKey: K) => Readable<InferFacts<M>[K] | undefined>;
147
+ useDerived: <K extends keyof InferDerivations<M> & string>(system: SingleModuleSystem<M>, derivationId: K) => Readable<InferDerivations<M>[K]>;
148
+ useDispatch: (system: SingleModuleSystem<M>) => (event: InferEvents<M>) => void;
149
+ useEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>["events"];
150
+ useWatch: <K extends string>(system: SingleModuleSystem<M>, key: K, callback: (newValue: unknown, previousValue: unknown) => void) => void;
151
+ };
152
+
153
+ export { type OptimisticUpdateResult, type StatusPlugin, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useInspect, useOptimisticUpdate, useRequirementStatus, useSelector, useTimeTravel, useWatch };
@@ -0,0 +1,153 @@
1
+ import * as _directive_run_core from '@directive-run/core';
2
+ import { createRequirementStatusPlugin, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, Plugin, DebugConfig, ErrorBoundaryConfig, RequirementTypeStatus, InferSelectorState, TimeTravelState } from '@directive-run/core';
3
+ export { RequirementTypeStatus } from '@directive-run/core';
4
+ import { Readable } from 'svelte/store';
5
+ import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
6
+ export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
7
+
8
+ /** Type for the requirement status plugin return value */
9
+ type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;
10
+ /**
11
+ * Create a Svelte store for a derived value.
12
+ */
13
+ declare function createDerivedStore<T>(system: SingleModuleSystem<any>, derivationId: string): Readable<T>;
14
+ /**
15
+ * Create a Svelte store for multiple derived values.
16
+ */
17
+ declare function createDerivedsStore<T extends Record<string, unknown>>(system: SingleModuleSystem<any>, derivationIds: string[]): Readable<T>;
18
+ /**
19
+ * Create a Svelte store for a single fact value.
20
+ */
21
+ declare function createFactStore<T>(system: SingleModuleSystem<any>, factKey: string): Readable<T | undefined>;
22
+ /**
23
+ * Create a Svelte store for system inspection data.
24
+ * NOTE: This updates on every fact change. Use sparingly in production.
25
+ */
26
+ declare function createInspectStore(system: SingleModuleSystem<any>): Readable<SystemInspection>;
27
+ /** Single key overload */
28
+ declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K): Readable<InferFacts<S>[K] | undefined>;
29
+ /** Multi-key overload */
30
+ declare function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKeys: K[]): Readable<Pick<InferFacts<S>, K>>;
31
+ /** Single key overload */
32
+ declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationId: K): Readable<InferDerivations<S>[K]>;
33
+ /** Multi-key overload */
34
+ declare function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationIds: K[]): Readable<Pick<InferDerivations<S>, K>>;
35
+ /**
36
+ * Auto-tracking selector over facts and derivations.
37
+ * Uses `withTracking()` to detect which facts the selector accesses,
38
+ * then subscribes only to those keys.
39
+ */
40
+ declare function useSelector<S extends ModuleSchema, R>(system: SingleModuleSystem<S>, selector: (state: InferSelectorState<S>) => R, equalityFn?: (a: R, b: R) => boolean): Readable<R>;
41
+ declare function useSelector<R>(system: SingleModuleSystem<any>, selector: (state: Record<string, any>) => R, equalityFn?: (a: R, b: R) => boolean): Readable<R>;
42
+ declare function useDispatch<S extends ModuleSchema>(system: SingleModuleSystem<S>): (event: InferEvents<S>) => void;
43
+ /**
44
+ * Returns the system's events dispatcher.
45
+ */
46
+ declare function useEvents<S extends ModuleSchema>(system: SingleModuleSystem<S>): SingleModuleSystem<S>["events"];
47
+ /** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */
48
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, key: K, callback: (newValue: InferDerivations<S>[K], previousValue: InferDerivations<S>[K] | undefined) => void): void;
49
+ /** Watch a fact key with auto-detection. */
50
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, key: K, callback: (newValue: InferFacts<S>[K] | undefined, previousValue: InferFacts<S>[K] | undefined) => void): void;
51
+ /**
52
+ * Watch a fact by explicit "fact" discriminator.
53
+ * @deprecated Use `useWatch(system, key, callback)` instead — facts are now auto-detected.
54
+ */
55
+ declare function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, kind: "fact", factKey: K, callback: (newValue: InferFacts<S>[K] | undefined, previousValue: InferFacts<S>[K] | undefined) => void): void;
56
+ /** Watch a fact or derivation (generic fallback) */
57
+ declare function useWatch<T>(system: SingleModuleSystem<any>, key: string, callback: (newValue: T, previousValue: T | undefined) => void): void;
58
+ /** Options for useInspect */
59
+ interface UseInspectOptions {
60
+ throttleMs?: number;
61
+ }
62
+ /**
63
+ * Consolidated system inspection hook.
64
+ * Returns Readable<InspectState> with optional throttling.
65
+ */
66
+ declare function useInspect(system: SingleModuleSystem<any>, options?: UseInspectOptions): Readable<InspectState>;
67
+ /** Single type overload */
68
+ declare function useRequirementStatus(statusPlugin: StatusPlugin, type: string): Readable<RequirementTypeStatus>;
69
+ /** Multi-type overload */
70
+ declare function useRequirementStatus(statusPlugin: StatusPlugin, types: string[]): Readable<Record<string, RequirementTypeStatus>>;
71
+ /**
72
+ * Reactively returns the explanation string for a requirement.
73
+ */
74
+ declare function useExplain(system: SingleModuleSystem<any>, requirementId: string): Readable<string | null>;
75
+ /** Get all constraints */
76
+ declare function useConstraintStatus(system: SingleModuleSystem<any>): Readable<ConstraintInfo[]>;
77
+ /** Get a single constraint by ID */
78
+ declare function useConstraintStatus(system: SingleModuleSystem<any>, constraintId: string): Readable<ConstraintInfo | null>;
79
+ interface OptimisticUpdateResult {
80
+ mutate: (updateFn: () => void) => void;
81
+ isPending: Readable<boolean>;
82
+ error: Readable<Error | null>;
83
+ rollback: () => void;
84
+ }
85
+ /**
86
+ * Optimistic update hook. Saves a snapshot before mutating, monitors
87
+ * a requirement type via statusPlugin, and rolls back on failure.
88
+ */
89
+ declare function useOptimisticUpdate(system: SingleModuleSystem<any>, statusPlugin?: StatusPlugin, requirementType?: string): OptimisticUpdateResult;
90
+ /**
91
+ * Reactive time-travel Svelte store. Returns a Readable that updates
92
+ * when snapshots are taken or navigation occurs.
93
+ *
94
+ * @example
95
+ * ```svelte
96
+ * const tt = useTimeTravel(system);
97
+ * <button disabled={!$tt?.canUndo} on:click={() => $tt?.undo()}>Undo</button>
98
+ * ```
99
+ */
100
+ declare function useTimeTravel(system: SingleModuleSystem<any>): Readable<TimeTravelState | null>;
101
+ /** Configuration for useDirective */
102
+ interface UseDirectiveConfig {
103
+ plugins?: Plugin<any>[];
104
+ debug?: DebugConfig;
105
+ errorBoundary?: ErrorBoundaryConfig;
106
+ tickMs?: number;
107
+ zeroConfig?: boolean;
108
+ initialFacts?: Record<string, any>;
109
+ status?: boolean;
110
+ /** Fact keys to subscribe to (omit for all) */
111
+ facts?: string[];
112
+ /** Derivation keys to subscribe to (omit for all) */
113
+ derived?: string[];
114
+ }
115
+ /**
116
+ * Create a scoped Directive system with automatic lifecycle management.
117
+ * When no `facts` or `derived` keys are specified, subscribes to ALL
118
+ * facts and derivations and returns Svelte readable stores.
119
+ *
120
+ * @example
121
+ * ```svelte
122
+ * // Subscribe to everything
123
+ * const { facts, derived, events, dispatch } = useDirective(counterModule);
124
+ *
125
+ * // Selective keys
126
+ * const { facts, derived } = useDirective(counterModule, { facts: ["count"], derived: ["doubled"] });
127
+ * ```
128
+ */
129
+ declare function useDirective<M extends ModuleSchema>(moduleDef: ModuleDef<M>, config?: UseDirectiveConfig): {
130
+ system: SingleModuleSystem<M>;
131
+ facts: Readable<_directive_run_core.InferSchema<M["facts"]>>;
132
+ derived: Readable<InferDerivations<M>>;
133
+ events: M["events"] extends Record<string, unknown> ? { [E in keyof M["events"]]: M["events"][E] extends Record<string, unknown> ? keyof M["events"][E] extends never ? () => void : (payload: M["events"][E] extends infer T ? T extends M["events"][E] ? T extends Record<string, unknown> ? { [K in keyof T]: T[K] extends {
134
+ _type: infer T_1;
135
+ } ? T_1 : T[K]; } : never : never : never) => void : () => void; } : Record<string, never>;
136
+ dispatch: (event: InferEvents<M>) => void;
137
+ statusPlugin: {
138
+ plugin: Plugin<never>;
139
+ getStatus: (type: string) => RequirementTypeStatus;
140
+ getAllStatus: () => Map<string, RequirementTypeStatus>;
141
+ subscribe: (listener: () => void) => () => void;
142
+ reset: () => void;
143
+ } | undefined;
144
+ };
145
+ declare function createTypedHooks<M extends ModuleSchema>(): {
146
+ useFact: <K extends keyof InferFacts<M> & string>(system: SingleModuleSystem<M>, factKey: K) => Readable<InferFacts<M>[K] | undefined>;
147
+ useDerived: <K extends keyof InferDerivations<M> & string>(system: SingleModuleSystem<M>, derivationId: K) => Readable<InferDerivations<M>[K]>;
148
+ useDispatch: (system: SingleModuleSystem<M>) => (event: InferEvents<M>) => void;
149
+ useEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>["events"];
150
+ useWatch: <K extends string>(system: SingleModuleSystem<M>, key: K, callback: (newValue: unknown, previousValue: unknown) => void) => void;
151
+ };
152
+
153
+ export { type OptimisticUpdateResult, type StatusPlugin, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useInspect, useOptimisticUpdate, useRequirementStatus, useSelector, useTimeTravel, useWatch };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import {onDestroy}from'svelte';import {readable}from'svelte/store';import {createRequirementStatusPlugin,createSystem}from'@directive-run/core';import {defaultEquality,assertSystem,computeInspectState,createThrottle,buildTimeTravelState,pickFacts,runTrackedSelector,depsChanged}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';function w(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),s=>e.subscribe([t],()=>{s(e.read(t));}))}function C(e,t){let s=()=>{let r={};for(let n of t)r[n]=e.read(n);return r};return readable(s(),r=>e.subscribe(t,()=>{r(s());}))}function E(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),s=>e.facts.$store.subscribe([t],()=>{s(e.facts.$store.get(t));}))}function j(e){return readable(e.inspect(),t=>{let s=()=>t(e.inspect()),r=e.facts.$store.subscribeAll(s),n=e.onSettledChange(s);return ()=>{r(),n();}})}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):E(e,t)}function $(e,t){let s=()=>{let r={};for(let n of t)r[n]=e.facts.$store.get(n);return r};return readable(s(),r=>e.facts.$store.subscribe(t,()=>{r(s());}))}function q(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):w(e,t)}function z(e,t,s=defaultEquality){assertSystem("useSelector",e);let r=new Set(Object.keys(e.derive??{})),n=()=>runTrackedSelector(e,r,t),o=n();return readable(o.value,a=>{let S=o.value,p=o.factKeys,f=o.deriveKeys,d=[],y=()=>{for(let c of d)c();d.length=0;let b=()=>{let c=n();s(S,c.value)||(S=c.value,a(c.value)),depsChanged(p,c.factKeys,f,c.deriveKeys)&&(p=c.factKeys,f=c.deriveKeys,y());};p.length>0?d.push(e.facts.$store.subscribe(p,b)):f.length===0&&d.push(e.facts.$store.subscribeAll(b)),f.length>0&&d.push(e.subscribe(f,b));};return y(),()=>{for(let b of d)b();}})}function O(e){return assertSystem("useDispatch",e),t=>{e.dispatch(t);}}function A(e){return assertSystem("useEvents",e),e.events}function P(e,t,s,r){assertSystem("useWatch",e);let n=t==="fact"&&typeof s=="string"&&typeof r=="function",o=n?s:t,a=n?r:s,S=e.watch(o,a);onDestroy(S);}function H(e,t){return assertSystem("useInspect",e),t?.throttleMs&&t.throttleMs>0?readable(computeInspectState(e),s=>{let{throttled:r,cleanup:n}=createThrottle(()=>{s(computeInspectState(e));},t.throttleMs),o=e.facts.$store.subscribeAll(r),a=e.onSettledChange(r);return ()=>{n(),o(),a();}}):readable(computeInspectState(e),s=>{let r=()=>s(computeInspectState(e)),n=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{n(),o();}})}function L(e,t){if(Array.isArray(t)){let s=()=>{let r={};for(let n of t)r[n]=e.getStatus(n);return r};return readable(s(),r=>e.subscribe(()=>{r(s());}))}return readable(e.getStatus(t),s=>e.subscribe(()=>{s(e.getStatus(t));}))}function G(e,t){return assertSystem("useExplain",e),readable(e.explain(t),s=>{let r=()=>s(e.explain(t)),n=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{n(),o();}})}function J(e,t){return assertSystem("useConstraintStatus",e),readable(x(e,t),s=>{let r=()=>s(x(e,t)),n=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{n(),o();}})}function x(e,t){let s=e.inspect();return t?s.constraints.find(r=>r.id===t)??null:s.constraints}function Q(e,t,s){assertSystem("useOptimisticUpdate",e);let r=false,n=null,o=null,a=null,S=new Set,p=new Set,f={subscribe(u){return u(r),S.add(u),()=>S.delete(u)}},d={subscribe(u){return u(n),p.add(u),()=>p.delete(u)}},y=u=>{r=u;for(let v of S)v(u);},b=u=>{n=u;for(let v of p)v(u);},c=()=>{o&&(e.restore(o),o=null),y(false),b(null),a?.(),a=null;},l=u=>{o=e.getSnapshot(),y(true),b(null),e.batch(u),t&&s&&(a?.(),a=t.subscribe(()=>{let v=t.getStatus(s);!v.isLoading&&!v.hasError?(o=null,y(false),a?.(),a=null):v.hasError&&(b(v.lastError),c());}));};return onDestroy(()=>{a?.();}),{mutate:l,isPending:f,error:d,rollback:c}}function X(e){return assertSystem("useTimeTravel",e),readable(buildTimeTravelState(e),t=>e.onTimeTravelChange(()=>t(buildTimeTravelState(e))))}function Y(e,t){let s=[...t?.plugins??[]],r;if(t?.status){let l=createRequirementStatusPlugin();r=l,s.push(l.plugin);}let n=createSystem({module:e,plugins:s.length>0?s:void 0,debug:t?.debug,errorBoundary:t?.errorBoundary,tickMs:t?.tickMs,zeroConfig:t?.zeroConfig,initialFacts:t?.initialFacts});n.start(),onDestroy(()=>{n.destroy();});let o=t?.facts,a=t?.derived,S=!o&&!a,p=S?readable(n.facts.$store.toObject(),l=>n.facts.$store.subscribeAll(()=>{l(n.facts.$store.toObject());})):readable(pickFacts(n,o??[]),l=>!o||o.length===0?()=>{}:n.facts.$store.subscribe(o,()=>{l(pickFacts(n,o));})),f=S?Object.keys(n.derive??{}):a??[],d=()=>{let l={};for(let u of f)l[u]=n.read(u);return l},y=f.length>0?readable(d(),l=>n.subscribe(f,()=>{l(d());})):readable(d(),()=>()=>{}),b=n.events;return {system:n,facts:p,derived:y,events:b,dispatch:l=>n.dispatch(l),statusPlugin:r}}function Z(){return {useFact:(e,t)=>V(e,t),useDerived:(e,t)=>q(e,t),useDispatch:e=>t=>{e.dispatch(t);},useEvents:e=>A(e),useWatch:(e,t,s)=>P(e,t,s)}}export{w as createDerivedStore,C as createDerivedsStore,E as createFactStore,j as createInspectStore,Z as createTypedHooks,J as useConstraintStatus,q as useDerived,Y as useDirective,O as useDispatch,A as useEvents,G as useExplain,V as useFact,H as useInspect,Q as useOptimisticUpdate,L as useRequirementStatus,z as useSelector,X as useTimeTravel,P as useWatch};//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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","derivationIdOrKind","callbackOrFactKey","maybeCallback","isFact","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","useTimeTravel","buildTimeTravelState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks"],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APiB7D,GAA0BxC,CAAAA,CAAO,QAAA,CAASwC,CAAK,CAAA,CAQhE,aAAAiB,CACD,CACD,CAMO,SAAS6C,CAAAA,EAgBd,CACD,OAAO,CACN,OAAA,CAAS,CAAyCtG,EAA+BU,CAAAA,GAEhFK,CAAAA,CAAQf,CAAAA,CAAmCU,CAAO,EACnD,UAAA,CAAY,CAA+CV,CAAAA,CAA+BC,CAAAA,GAEzFoB,EAAWrB,CAAAA,CAAmCC,CAAY,EAC3D,WAAA,CAAcD,CAAAA,EACLwC,GAA0B,CACjCxC,CAAAA,CAAO,QAAA,CAASwC,CAAK,EACtB,CAAA,CAED,SAAA,CAAYxC,CAAAA,EAAkCyC,CAAAA,CAAazC,CAAM,CAAA,CACjE,QAAA,CAAU,CACTA,CAAAA,CACAoB,EACA2B,CAAAA,GAGAL,CAAAA,CAAS1C,EAAmCoB,CAAAA,CAAK2B,CAAQ,CAC3D,CACD","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, useTimeTravel,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport { onDestroy } from \"svelte\";\nimport { readable, type Readable } from \"svelte/store\";\nimport type {\n\tModuleSchema,\n\tModuleDef,\n\tPlugin,\n\tDebugConfig,\n\tErrorBoundaryConfig,\n\tInferFacts,\n\tInferDerivations,\n\tInferSelectorState,\n\tInferEvents,\n\tSingleModuleSystem,\n\tSystemInspection,\n\tSystemSnapshot,\n\tTimeTravelState,\n} from \"@directive-run/core\";\nimport {\n\tcreateSystem,\n\tcreateRequirementStatusPlugin,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n\ttype InspectState,\n\ttype ConstraintInfo,\n\tcomputeInspectState,\n\tcreateThrottle,\n\tassertSystem,\n\tdefaultEquality,\n\tbuildTimeTravelState,\n\tpickFacts,\n\trunTrackedSelector,\n\tdepsChanged,\n\tshallowEqual,\n} from \"@directive-run/core/adapter-utils\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\tsystem: SingleModuleSystem<any>,\n\tderivationId: string,\n): Readable<T> {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst initialValue = system.read(derivationId);\n\t\tif (initialValue === undefined) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n\t\t\t\t`Check that \"${derivationId}\" is defined in your module's derive property.`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn readable<T>(system.read(derivationId) as T, (set) => {\n\t\tconst unsubscribe = system.subscribe([derivationId], () => {\n\t\t\tset(system.read(derivationId) as T);\n\t\t});\n\t\treturn unsubscribe;\n\t});\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\tsystem: SingleModuleSystem<any>,\n\tderivationIds: string[],\n): Readable<T> {\n\tconst getValues = (): T => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const id of derivationIds) {\n\t\t\tresult[id] = system.read(id);\n\t\t}\n\t\treturn result as T;\n\t};\n\n\treturn readable<T>(getValues(), (set) => {\n\t\tconst unsubscribe = system.subscribe(derivationIds, () => {\n\t\t\tset(getValues());\n\t\t});\n\t\treturn unsubscribe;\n\t});\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\tsystem: SingleModuleSystem<any>,\n\tfactKey: string,\n): Readable<T | undefined> {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!system.facts.$store.has(factKey)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n\t\t\t\t`Check that \"${factKey}\" is defined in your module's schema.`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn readable<T | undefined>(\n\t\tsystem.facts.$store.get(factKey) as T | undefined,\n\t\t(set) => {\n\t\t\tconst unsubscribe = system.facts.$store.subscribe([factKey], () => {\n\t\t\t\tset(system.facts.$store.get(factKey) as T | undefined);\n\t\t\t});\n\t\t\treturn unsubscribe;\n\t\t},\n\t);\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\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\tsystem: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n\treturn readable<SystemInspection>(system.inspect(), (set) => {\n\t\tconst update = () => set(system.inspect());\n\t\tconst unsubFacts = system.facts.$store.subscribeAll(update);\n\t\tconst unsubSettled = system.onSettledChange(update);\n\t\treturn () => {\n\t\t\tunsubFacts();\n\t\t\tunsubSettled();\n\t\t};\n\t});\n}\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKey: K): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(system: SingleModuleSystem<S>, factKeys: K[]): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tkeyOrKeys: string | string[],\n): Readable<unknown> {\n\tassertSystem(\"useFact\", system);\n\tif (process.env.NODE_ENV !== \"production\" && typeof keyOrKeys === \"function\") {\n\t\tconsole.error(\n\t\t\t\"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n\t\t\t\t\"useFact() takes a string key or array of keys, not a selector function.\",\n\t\t);\n\t}\n\n\t// Multi-key path: useFact(system, [keys])\n\tif (Array.isArray(keyOrKeys)) {\n\t\treturn _useFactMulti(system, keyOrKeys);\n\t}\n\n\t// Single key path: useFact(system, key)\n\treturn createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(system: SingleModuleSystem<any>, factKeys: string[]): Readable<Record<string, unknown>> {\n\tconst getValues = (): Record<string, unknown> => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of factKeys) {\n\t\t\tresult[key] = system.facts.$store.get(key);\n\t\t}\n\t\treturn result;\n\t};\n\n\treturn readable(getValues(), (set) => {\n\t\tconst unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n\t\t\tset(getValues());\n\t\t});\n\t\treturn unsubscribe;\n\t});\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationId: K): Readable<InferDerivations<S>[K]>;\n/** Multi-key overload */\nexport function useDerived<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(system: SingleModuleSystem<S>, derivationIds: K[]): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tidOrIds: string | string[],\n): Readable<unknown> {\n\tassertSystem(\"useDerived\", system);\n\tif (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"function\") {\n\t\tconsole.error(\n\t\t\t\"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n\t\t\t\t\"useDerived() takes a string key or array of keys, not a selector function.\",\n\t\t);\n\t}\n\n\t// Multi-key path\n\tif (Array.isArray(idOrIds)) {\n\t\treturn createDerivedsStore(system, idOrIds);\n\t}\n\n\t// Single key path\n\treturn 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>(system: SingleModuleSystem<S>, selector: (state: InferSelectorState<S>) => R, equalityFn?: (a: R, b: R) => boolean): Readable<R>;\nexport function useSelector<R>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any>,\n\t// biome-ignore lint/suspicious/noExplicitAny: Selector receives dynamic state\n\tselector: (state: Record<string, any>) => R,\n\tequalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tselector: (state: any) => unknown,\n\tequalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n\tassertSystem(\"useSelector\", system);\n\tconst deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n\t// Build a tracking-aware state proxy that exposes both facts and derivations\n\tconst runWithTracking = () => runTrackedSelector(system, deriveKeySet, selector);\n\n\tconst initial = runWithTracking();\n\n\treturn readable(initial.value, (set) => {\n\t\tlet currentSelected = initial.value;\n\t\tlet trackedFactKeys = initial.factKeys;\n\t\tlet trackedDeriveKeys = initial.deriveKeys;\n\t\tconst unsubs: Array<() => void> = [];\n\n\t\tconst resubscribe = () => {\n\t\t\tfor (const unsub of unsubs) unsub();\n\t\t\tunsubs.length = 0;\n\n\t\t\tconst onUpdate = () => {\n\t\t\t\tconst result = runWithTracking();\n\t\t\t\tif (!equalityFn(currentSelected, result.value)) {\n\t\t\t\t\tcurrentSelected = result.value;\n\t\t\t\t\tset(result.value);\n\t\t\t\t}\n\t\t\t\t// Re-track: check if deps changed\n\t\t\t\tif (depsChanged(trackedFactKeys, result.factKeys, trackedDeriveKeys, result.deriveKeys)) {\n\t\t\t\t\ttrackedFactKeys = result.factKeys;\n\t\t\t\t\ttrackedDeriveKeys = result.deriveKeys;\n\t\t\t\t\tresubscribe();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tif (trackedFactKeys.length > 0) {\n\t\t\t\tunsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n\t\t\t} else if (trackedDeriveKeys.length === 0) {\n\t\t\t\tunsubs.push(system.facts.$store.subscribeAll(onUpdate));\n\t\t\t}\n\t\t\tif (trackedDeriveKeys.length > 0) {\n\t\t\t\tunsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n\t\t\t}\n\t\t};\n\n\t\tresubscribe();\n\n\t\treturn () => {\n\t\t\tfor (const unsub of unsubs) unsub();\n\t\t};\n\t});\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n\tsystem: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n\tassertSystem(\"useDispatch\", system);\n\treturn (event: InferEvents<S>) => {\n\t\tsystem.dispatch(event);\n\t};\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\tsystem: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n\tassertSystem(\"useEvents\", system);\n\treturn 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<S extends ModuleSchema, K extends keyof InferDerivations<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tkey: K,\n\tcallback: (newValue: InferDerivations<S>[K], previousValue: InferDerivations<S>[K] | undefined) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tkey: K,\n\tcallback: (newValue: InferFacts<S>[K] | undefined, previousValue: InferFacts<S>[K] | undefined) => void,\n): void;\n/**\n * Watch a fact by explicit \"fact\" discriminator.\n * @deprecated Use `useWatch(system, key, callback)` instead — facts are now auto-detected.\n */\nexport function useWatch<S extends ModuleSchema, K extends keyof InferFacts<S> & string>(\n\tsystem: SingleModuleSystem<S>,\n\tkind: \"fact\",\n\tfactKey: K,\n\tcallback: (newValue: InferFacts<S>[K] | undefined, previousValue: InferFacts<S>[K] | undefined) => void,\n): void;\n/** Watch a fact or derivation (generic fallback) */\nexport function useWatch<T>(\n\t// biome-ignore lint/suspicious/noExplicitAny: Backward-compatible fallback\n\tsystem: SingleModuleSystem<any>,\n\tkey: string,\n\tcallback: (newValue: T, previousValue: T | undefined) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n\t// biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n\tsystem: SingleModuleSystem<any>,\n\tderivationIdOrKind: string,\n\tcallbackOrFactKey: string | ((newValue: unknown, prevValue: unknown) => void),\n\tmaybeCallback?: (newValue: unknown, prevValue: unknown) => void,\n): void {\n\tassertSystem(\"useWatch\", system);\n\t// Backward compat: useWatch(system, \"fact\", factKey, callback)\n\tconst isFact =\n\t\tderivationIdOrKind === \"fact\" &&\n\t\ttypeof callbackOrFactKey === \"string\" &&\n\t\ttypeof maybeCallback === \"function\";\n\n\tconst key = isFact ? (callbackOrFactKey as string) : derivationIdOrKind;\n\tconst callback = isFact\n\t\t? maybeCallback!\n\t\t: (callbackOrFactKey as (newValue: unknown, prevValue: unknown) => void);\n\n\tconst unsubscribe = system.watch(key, callback);\n\tonDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n\tthrottleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\toptions?: UseInspectOptions,\n): Readable<InspectState> {\n\tassertSystem(\"useInspect\", system);\n\tif (options?.throttleMs && options.throttleMs > 0) {\n\t\treturn readable<InspectState>(computeInspectState(system), (set) => {\n\t\t\tconst { throttled, cleanup } = createThrottle(() => {\n\t\t\t\tset(computeInspectState(system));\n\t\t\t}, options.throttleMs!);\n\n\t\t\tconst unsubFacts = system.facts.$store.subscribeAll(throttled);\n\t\t\tconst unsubSettled = system.onSettledChange(throttled);\n\n\t\t\treturn () => {\n\t\t\t\tcleanup();\n\t\t\t\tunsubFacts();\n\t\t\t\tunsubSettled();\n\t\t\t};\n\t\t});\n\t}\n\n\treturn readable<InspectState>(computeInspectState(system), (set) => {\n\t\tconst update = () => set(computeInspectState(system));\n\t\tconst unsubFacts = system.facts.$store.subscribeAll(update);\n\t\tconst unsubSettled = system.onSettledChange(update);\n\n\t\treturn () => {\n\t\t\tunsubFacts();\n\t\t\tunsubSettled();\n\t\t};\n\t});\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(statusPlugin: StatusPlugin, type: string): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(statusPlugin: StatusPlugin, types: string[]): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n\tstatusPlugin: StatusPlugin,\n\ttypeOrTypes: string | string[],\n): Readable<RequirementTypeStatus> | Readable<Record<string, RequirementTypeStatus>> {\n\tif (Array.isArray(typeOrTypes)) {\n\t\tconst getValues = (): Record<string, RequirementTypeStatus> => {\n\t\t\tconst result: Record<string, RequirementTypeStatus> = {};\n\t\t\tfor (const type of typeOrTypes) {\n\t\t\t\tresult[type] = statusPlugin.getStatus(type);\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\n\t\treturn readable(getValues(), (set) => {\n\t\t\tconst unsubscribe = statusPlugin.subscribe(() => {\n\t\t\t\tset(getValues());\n\t\t\t});\n\t\t\treturn unsubscribe;\n\t\t});\n\t}\n\n\treturn readable<RequirementTypeStatus>(statusPlugin.getStatus(typeOrTypes), (set) => {\n\t\tconst unsubscribe = statusPlugin.subscribe(() => {\n\t\t\tset(statusPlugin.getStatus(typeOrTypes));\n\t\t});\n\t\treturn unsubscribe;\n\t});\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\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\trequirementId: string,\n): Readable<string | null> {\n\tassertSystem(\"useExplain\", system);\n\treturn readable<string | null>(system.explain(requirementId), (set) => {\n\t\tconst update = () => set(system.explain(requirementId));\n\t\tconst unsubFacts = system.facts.$store.subscribeAll(update);\n\t\tconst unsubSettled = system.onSettledChange(update);\n\n\t\treturn () => {\n\t\t\tunsubFacts();\n\t\t\tunsubSettled();\n\t\t};\n\t});\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n\tsystem: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId: string,\n): Readable<ConstraintInfo | null>;\n/** Implementation */\nexport function useConstraintStatus(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId?: string,\n): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n\tassertSystem(\"useConstraintStatus\", system);\n\treturn readable<ConstraintInfo[] | ConstraintInfo | null>(\n\t\t_getConstraintValue(system, constraintId),\n\t\t(set) => {\n\t\t\tconst update = () => set(_getConstraintValue(system, constraintId));\n\t\t\tconst unsubFacts = system.facts.$store.subscribeAll(update);\n\t\t\tconst unsubSettled = system.onSettledChange(update);\n\n\t\t\treturn () => {\n\t\t\t\tunsubFacts();\n\t\t\t\tunsubSettled();\n\t\t\t};\n\t\t},\n\t);\n}\n\nfunction _getConstraintValue(\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal\n\tsystem: SingleModuleSystem<any>,\n\tconstraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n\tconst inspection = system.inspect();\n\tif (!constraintId) return inspection.constraints;\n\treturn inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ?? null;\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n\tmutate: (updateFn: () => void) => void;\n\tisPending: Readable<boolean>;\n\terror: Readable<Error | null>;\n\trollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n */\nexport function useOptimisticUpdate(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n\tstatusPlugin?: StatusPlugin,\n\trequirementType?: string,\n): OptimisticUpdateResult {\n\tassertSystem(\"useOptimisticUpdate\", system);\n\tlet isPendingValue = false;\n\tlet errorValue: Error | null = null;\n\tlet snapshot: SystemSnapshot | null = null;\n\tlet statusUnsub: (() => void) | null = null;\n\n\t// We track subscribers manually since we need imperative push\n\tconst pendingSubscribers = new Set<(v: boolean) => void>();\n\tconst errorSubscribers = new Set<(v: Error | null) => void>();\n\n\tconst isPending: Readable<boolean> = {\n\t\tsubscribe(fn) {\n\t\t\tfn(isPendingValue);\n\t\t\tpendingSubscribers.add(fn);\n\t\t\treturn () => pendingSubscribers.delete(fn);\n\t\t},\n\t};\n\n\tconst error: Readable<Error | null> = {\n\t\tsubscribe(fn) {\n\t\t\tfn(errorValue);\n\t\t\terrorSubscribers.add(fn);\n\t\t\treturn () => errorSubscribers.delete(fn);\n\t\t},\n\t};\n\n\tconst setPending = (v: boolean) => {\n\t\tisPendingValue = v;\n\t\tfor (const fn of pendingSubscribers) fn(v);\n\t};\n\n\tconst setError = (v: Error | null) => {\n\t\terrorValue = v;\n\t\tfor (const fn of errorSubscribers) fn(v);\n\t};\n\n\tconst rollback = () => {\n\t\tif (snapshot) {\n\t\t\tsystem.restore(snapshot);\n\t\t\tsnapshot = null;\n\t\t}\n\t\tsetPending(false);\n\t\tsetError(null);\n\t\tstatusUnsub?.();\n\t\tstatusUnsub = null;\n\t};\n\n\tconst mutate = (updateFn: () => void) => {\n\t\tsnapshot = system.getSnapshot();\n\t\tsetPending(true);\n\t\tsetError(null);\n\t\tsystem.batch(updateFn);\n\n\t\tif (statusPlugin && requirementType) {\n\t\t\tstatusUnsub?.();\n\t\t\tstatusUnsub = statusPlugin.subscribe(() => {\n\t\t\t\tconst status = statusPlugin.getStatus(requirementType);\n\t\t\t\tif (!status.isLoading && !status.hasError) {\n\t\t\t\t\tsnapshot = null;\n\t\t\t\t\tsetPending(false);\n\t\t\t\t\tstatusUnsub?.();\n\t\t\t\t\tstatusUnsub = null;\n\t\t\t\t} else if (status.hasError) {\n\t\t\t\t\tsetError(status.lastError);\n\t\t\t\t\trollback();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n\n\tonDestroy(() => {\n\t\tstatusUnsub?.();\n\t});\n\n\treturn { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useTimeTravel — reactive time-travel store\n// ============================================================================\n\n/**\n * Reactive time-travel Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const tt = useTimeTravel(system);\n * <button disabled={!$tt?.canUndo} on:click={() => $tt?.undo()}>Undo</button>\n * ```\n */\nexport function useTimeTravel(\n\t// biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n\tsystem: SingleModuleSystem<any>,\n): Readable<TimeTravelState | null> {\n\tassertSystem(\"useTimeTravel\", system);\n\treturn readable<TimeTravelState | null>(buildTimeTravelState(system), (set) => {\n\t\treturn system.onTimeTravelChange(() => set(buildTimeTravelState(system)));\n\t});\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\ninterface UseDirectiveConfig {\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n\tplugins?: Plugin<any>[];\n\tdebug?: DebugConfig;\n\terrorBoundary?: ErrorBoundaryConfig;\n\ttickMs?: number;\n\tzeroConfig?: boolean;\n\t// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n\tinitialFacts?: Record<string, any>;\n\tstatus?: boolean;\n\t/** Fact keys to subscribe to (omit for all) */\n\tfacts?: string[];\n\t/** Derivation keys to subscribe to (omit for all) */\n\tderived?: 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\tmoduleDef: ModuleDef<M>,\n\tconfig?: UseDirectiveConfig,\n) {\n\tconst allPlugins = [...(config?.plugins ?? [])];\n\tlet statusPlugin: StatusPlugin | undefined;\n\n\tif (config?.status) {\n\t\tconst sp = createRequirementStatusPlugin();\n\t\tstatusPlugin = sp;\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n\t\tallPlugins.push(sp.plugin as Plugin<any>);\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\tconst system = createSystem({\n\t\tmodule: moduleDef,\n\t\tplugins: allPlugins.length > 0 ? allPlugins : undefined,\n\t\tdebug: config?.debug,\n\t\terrorBoundary: config?.errorBoundary,\n\t\ttickMs: config?.tickMs,\n\t\tzeroConfig: config?.zeroConfig,\n\t\tinitialFacts: config?.initialFacts,\n\t} as any) as unknown as SingleModuleSystem<M>;\n\n\tsystem.start();\n\n\tonDestroy(() => {\n\t\tsystem.destroy();\n\t});\n\n\tconst factKeys = config?.facts;\n\tconst derivedKeys = config?.derived;\n\tconst subscribeAll = !factKeys && !derivedKeys;\n\n\t// Subscribe to facts\n\tconst factsStore: Readable<InferFacts<M>> = subscribeAll\n\t\t? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n\t\t\treturn system.facts.$store.subscribeAll(() => {\n\t\t\t\tset(system.facts.$store.toObject() as InferFacts<M>);\n\t\t\t});\n\t\t})\n\t\t: readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n\t\t\tif (!factKeys || factKeys.length === 0) return () => {};\n\t\t\treturn system.facts.$store.subscribe(factKeys, () => {\n\t\t\t\tset(pickFacts(system, factKeys) as InferFacts<M>);\n\t\t\t});\n\t\t});\n\n\t// Subscribe to derivations\n\tconst allDerivationKeys = subscribeAll ? Object.keys(system.derive ?? {}) : (derivedKeys ?? []);\n\tconst getDerived = (): InferDerivations<M> => {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of allDerivationKeys) {\n\t\t\tresult[key] = system.read(key);\n\t\t}\n\t\treturn result as InferDerivations<M>;\n\t};\n\tconst derivedStore: Readable<InferDerivations<M>> = allDerivationKeys.length > 0\n\t\t? readable(getDerived(), (set) => {\n\t\t\treturn system.subscribe(allDerivationKeys, () => {\n\t\t\t\tset(getDerived());\n\t\t\t});\n\t\t})\n\t\t: readable(getDerived(), () => () => {});\n\n\tconst events = system.events;\n\tconst dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n\treturn {\n\t\tsystem,\n\t\tfacts: factsStore,\n\t\tderived: derivedStore,\n\t\tevents,\n\t\tdispatch,\n\t\tstatusPlugin,\n\t};\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n\tuseFact: <K extends keyof InferFacts<M> & string>(\n\t\tsystem: SingleModuleSystem<M>,\n\t\tfactKey: K,\n\t) => Readable<InferFacts<M>[K] | undefined>;\n\tuseDerived: <K extends keyof InferDerivations<M> & string>(\n\t\tsystem: SingleModuleSystem<M>,\n\t\tderivationId: K,\n\t) => Readable<InferDerivations<M>[K]>;\n\tuseDispatch: (system: SingleModuleSystem<M>) => (event: InferEvents<M>) => void;\n\tuseEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>[\"events\"];\n\tuseWatch: <K extends string>(\n\t\tsystem: SingleModuleSystem<M>,\n\t\tkey: K,\n\t\tcallback: (newValue: unknown, previousValue: unknown) => void,\n\t) => void;\n} {\n\treturn {\n\t\tuseFact: <K extends keyof InferFacts<M> & string>(system: SingleModuleSystem<M>, factKey: K) =>\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n\t\t\tuseFact(system as SingleModuleSystem<any>, factKey) as Readable<InferFacts<M>[K] | undefined>,\n\t\tuseDerived: <K extends keyof InferDerivations<M> & string>(system: SingleModuleSystem<M>, derivationId: K) =>\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n\t\t\tuseDerived(system as SingleModuleSystem<any>, derivationId) as Readable<InferDerivations<M>[K]>,\n\t\tuseDispatch: (system: SingleModuleSystem<M>) => {\n\t\t\treturn (event: InferEvents<M>) => {\n\t\t\t\tsystem.dispatch(event);\n\t\t\t};\n\t\t},\n\t\tuseEvents: (system: SingleModuleSystem<M>) => useEvents<M>(system),\n\t\tuseWatch: <K extends string>(\n\t\t\tsystem: SingleModuleSystem<M>,\n\t\t\tkey: K,\n\t\t\tcallback: (newValue: unknown, previousValue: unknown) => void,\n\t\t) =>\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n\t\t\tuseWatch(system as SingleModuleSystem<any>, key, callback),\n\t};\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@directive-run/svelte",
3
+ "version": "0.1.1",
4
+ "description": "Svelte stores adapter for Directive.",
5
+ "license": "MIT",
6
+ "author": "Jason Comes",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/directive-run/directive",
10
+ "directory": "packages/svelte"
11
+ },
12
+ "homepage": "https://directive.run",
13
+ "bugs": {
14
+ "url": "https://github.com/directive-run/directive/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "registry": "https://registry.npmjs.org"
19
+ },
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "keywords": [
24
+ "directive",
25
+ "svelte",
26
+ "stores",
27
+ "state-management",
28
+ "reactive",
29
+ "constraint-driven"
30
+ ],
31
+ "sideEffects": false,
32
+ "type": "module",
33
+ "main": "./dist/index.cjs",
34
+ "module": "./dist/index.js",
35
+ "types": "./dist/index.d.ts",
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.ts",
39
+ "require": "./dist/index.cjs",
40
+ "import": "./dist/index.js"
41
+ }
42
+ },
43
+ "files": [
44
+ "dist"
45
+ ],
46
+ "peerDependencies": {
47
+ "svelte": ">=4",
48
+ "@directive-run/core": "0.1.1"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^25.2.0",
52
+ "svelte": "^4.2.0",
53
+ "tsup": "^8.3.5",
54
+ "typescript": "^5.7.2",
55
+ "@directive-run/core": "0.1.1"
56
+ },
57
+ "scripts": {
58
+ "build": "tsup",
59
+ "dev": "tsup --watch",
60
+ "test": "vitest run",
61
+ "typecheck": "tsc --noEmit",
62
+ "clean": "rm -rf dist"
63
+ }
64
+ }