@directive-run/svelte 0.8.6 → 0.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +31 -2
- package/dist/index.d.ts +31 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils'),svelte=require('svelte'),store=require('svelte/store');var
|
|
1
|
+
'use strict';var core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils'),svelte=require('svelte'),store=require('svelte/store');var D=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function P(e,t){return process.env.NODE_ENV!=="production"&&e.read(t)===void 0&&console.warn(`[Directive] createDerivedStore("${t}") returned undefined. Check that "${t}" is defined in your module's derive property.`),store.readable(e.read(t),n=>e.subscribe([t],()=>{n(e.read(t));}))}function A(e,t){let n=()=>{let s={};for(let r of t)s[r]=e.read(r);return s};return store.readable(n(),s=>e.subscribe(t,()=>{s(n());}))}function N(e,t){return process.env.NODE_ENV!=="production"&&(e.facts.$store.has(t)||console.warn(`[Directive] createFactStore("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`)),store.readable(e.facts.$store.get(t),n=>e.facts.$store.subscribe([t],()=>{n(e.facts.$store.get(t));}))}function X(e){return store.readable(e.inspect(),t=>{let n=()=>t(e.inspect()),s=e.facts.$store.subscribeAll(n),r=e.onSettledChange(n);return ()=>{s(),r();}})}function H(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)?U(e,t):N(e,t)}function U(e,t){let n=()=>{let s={};for(let r of t)s[r]=e.facts.$store.get(r);return s};return store.readable(n(),s=>e.facts.$store.subscribe(t,()=>{s(n());}))}function O(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)?A(e,t):P(e,t)}function Z(e,t,n=adapterUtils.defaultEquality){adapterUtils.assertSystem("useSelector",e);let s=new Set(Object.keys(e.derive??{})),r=()=>adapterUtils.runTrackedSelector(e,s,t),o=r();return store.readable(o.value,c=>{let p=o.value,g=o.factKeys,S=o.deriveKeys,d=[],y=()=>{for(let l of d)l();d.length=0;let f=()=>{let l=r();n(p,l.value)||(p=l.value,c(l.value)),adapterUtils.depsChanged(g,l.factKeys,S,l.deriveKeys)&&(g=l.factKeys,S=l.deriveKeys,y());};g.length>0?d.push(e.facts.$store.subscribe(g,f)):S.length===0&&d.push(e.facts.$store.subscribeAll(f)),S.length>0&&d.push(e.subscribe(S,f));};return y(),()=>{for(let f of d)f();}})}function ee(e){return adapterUtils.assertSystem("useDispatch",e),t=>{e.dispatch(t);}}function _(e){return adapterUtils.assertSystem("useEvents",e),e.events}function W(e,t,n){adapterUtils.assertSystem("useWatch",e);let s=e.watch(t,n);svelte.onDestroy(s);}function te(e,t){return adapterUtils.assertSystem("useInspect",e),t?.throttleMs&&t.throttleMs>0?store.readable(adapterUtils.computeInspectState(e),n=>{let{throttled:s,cleanup:r}=adapterUtils.createThrottle(()=>{n(adapterUtils.computeInspectState(e));},t.throttleMs),o=e.facts.$store.subscribeAll(s),c=e.onSettledChange(s);return ()=>{r(),o(),c();}}):store.readable(adapterUtils.computeInspectState(e),n=>{let s=()=>n(adapterUtils.computeInspectState(e)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function ne(e,t){if(Array.isArray(t)){let n=()=>{let s={};for(let r of t)s[r]=e.getStatus(r);return s};return store.readable(n(),s=>e.subscribe(()=>{s(n());}))}return store.readable(e.getStatus(t),n=>e.subscribe(()=>{n(e.getStatus(t));}))}function se(e,t){return adapterUtils.assertSystem("useExplain",e),store.readable(e.explain(t),n=>{let s=()=>n(e.explain(t)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function re(e,t){return adapterUtils.assertSystem("useConstraintStatus",e),store.readable(k(e,t),n=>{let s=()=>n(k(e,t)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function k(e,t){let n=e.inspect();return t?n.constraints.find(s=>s.id===t)??null:n.constraints}function oe(e,t,n){adapterUtils.assertSystem("useOptimisticUpdate",e);let s=false,r=null,o=null,c=null,p=new Set,g=new Set,S={subscribe(u){return u(s),p.add(u),()=>p.delete(u)}},d={subscribe(u){return u(r),g.add(u),()=>g.delete(u)}},y=u=>{s=u;for(let M of p)M(u);},f=u=>{r=u;for(let M of g)M(u);},l=()=>{o&&(e.restore(o),o=null),y(false),f(null),c?.(),c=null;},a=u=>{o=e.getSnapshot(),y(true),f(null),e.batch(u),t&&n&&(c?.(),c=t.subscribe(()=>{let M=t.getStatus(n);!M.isLoading&&!M.hasError?(o=null,y(false),c?.(),c=null):M.hasError&&(f(M.lastError),l());}));};return svelte.onDestroy(()=>{c?.();}),{mutate:a,isPending:S,error:d,rollback:l}}function ue(e){return adapterUtils.assertSystem("useHistory",e),store.readable(adapterUtils.buildHistoryState(e),t=>e.onHistoryChange(()=>t(adapterUtils.buildHistoryState(e))))}function Q(e,t){let n=[...t?.plugins??[]],s;if(t?.status){let a=core.createRequirementStatusPlugin();s=a,n.push(a.plugin);}let r=core.createSystem({module:e,plugins:n.length>0?n:void 0,trace:t?.trace,errorBoundary:t?.errorBoundary,tickMs:t?.tickMs,zeroConfig:t?.zeroConfig,initialFacts:t?.initialFacts});typeof window<"u"?r.start():r.initialize(),svelte.onDestroy(()=>{r.destroy();});let o=t?.facts,c=t?.derived,p=!o&&!c,g=p?store.readable(r.facts.$store.toObject(),a=>r.facts.$store.subscribeAll(()=>{a(r.facts.$store.toObject());})):store.readable(adapterUtils.pickFacts(r,o??[]),a=>!o||o.length===0?()=>{}:r.facts.$store.subscribe(o,()=>{a(adapterUtils.pickFacts(r,o));})),S=p?Object.keys(r.derive??{}):c??[],d=()=>{let a={};for(let u of S)a[u]=r.read(u);return a},y=S.length>0?store.readable(d(),a=>r.subscribe(S,()=>{a(d());})):store.readable(d(),()=>()=>{}),f=r.events;return {system:r,facts:g,derived:y,events:f,dispatch:a=>r.dispatch(a),statusPlugin:s}}function ie(){return {useFact:(e,t)=>H(e,t),useDerived:(e,t)=>O(e,t),useDispatch:e=>t=>{e.dispatch(t);},useEvents:e=>_(e),useWatch:(e,t,n)=>W(e,t,n)}}function ae(e,t,n){return store.readable(n(e),s=>e.subscribe(t,()=>{s(n(e));}))}var R=null;function B(){if(!R)try{R=D("@directive-run/query").createQuerySystem;}catch{throw new Error("[Directive] @directive-run/query is not installed. Install it with: pnpm add @directive-run/query")}return R}function ce(e){let n=B()(e);return typeof window<"u"&&!n.isRunning&&n.start(),svelte.onDestroy(()=>{n.destroy();}),n}var I=Symbol("directive-hydration");function le(e){svelte.setContext(I,e);}function de(e,t){let n=svelte.getContext(I),s=adapterUtils.mergeHydrationFacts(n,t?.initialFacts);return Q(e,{...t,initialFacts:s}).system}Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return adapterUtils.shallowEqual}});exports.createDerivedStore=P;exports.createDerivedsStore=A;exports.createFactStore=N;exports.createInspectStore=X;exports.createTypedHooks=ie;exports.setHydrationSnapshot=le;exports.useConstraintStatus=re;exports.useDerived=O;exports.useDirective=Q;exports.useDispatch=ee;exports.useEvents=_;exports.useExplain=se;exports.useFact=H;exports.useHistory=ue;exports.useHydratedSystem=de;exports.useInspect=te;exports.useNamespacedSelector=ae;exports.useOptimisticUpdate=oe;exports.useQuerySystem=ce;exports.useRequirementStatus=ne;exports.useSelector=Z;exports.useWatch=W;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["createDerivedStore","system","derivationId","readable","set","createDerivedsStore","derivationIds","getValues","result","id","createFactStore","factKey","createInspectStore","update","unsubFacts","unsubSettled","useFact","keyOrKeys","assertSystem","_useFactMulti","factKeys","key","useDerived","idOrIds","useSelector","selector","equalityFn","defaultEquality","deriveKeySet","runWithTracking","runTrackedSelector","initial","currentSelected","trackedFactKeys","trackedDeriveKeys","unsubs","resubscribe","unsub","onUpdate","depsChanged","useDispatch","event","useEvents","useWatch","callback","unsubscribe","onDestroy","useInspect","options","computeInspectState","throttled","cleanup","createThrottle","useRequirementStatus","statusPlugin","typeOrTypes","type","useExplain","requirementId","useConstraintStatus","constraintId","_getConstraintValue","inspection","c","useOptimisticUpdate","requirementType","isPendingValue","errorValue","snapshot","statusUnsub","pendingSubscribers","errorSubscribers","isPending","fn","error","setPending","v","setError","rollback","mutate","updateFn","status","useHistory","buildHistoryState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks","useNamespacedSelector","keys","_createQuerySystem","getCreateQuerySystem","useQuerySystem"],"mappings":"sKA4BA,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAA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AAA,CAAmCU,CAAO,CAAA,CAGpD,UAAA,CAAY,CACVV,CAAAA,CACAC,CAAAA,GAGAoB,EAAWrB,CAAAA,CAAmCC,CAAY,CAAA,CAG5D,WAAA,CAAcD,GACJwC,CAAAA,EAA0B,CAChCxC,EAAO,QAAA,CAASwC,CAAK,EACvB,CAAA,CAEF,SAAA,CAAYxC,CAAAA,EAAkCyC,CAAAA,CAAazC,CAAM,CAAA,CACjE,QAAA,CAAU,CACRA,CAAAA,CACAoB,CAAAA,CACAuB,IAGAD,CAAAA,CAAS1C,CAAAA,CAAmCoB,CAAAA,CAAKuB,CAAQ,CAC7D,CACF,CAmBO,SAASwD,EAAAA,CACdnG,CAAAA,CACAoG,EACA5E,CAAAA,CACa,CACb,OAAOtB,cAAAA,CAAYsB,EAASxB,CAAM,CAAA,CAAIG,GAChBH,CAAAA,CAAO,SAAA,CAAUoG,EAAM,IAAM,CAC/CjG,CAAAA,CAAIqB,CAAAA,CAASxB,CAAM,CAAC,EACtB,CAAC,CAGF,CACH,CAOA,IAAIqG,CAAAA,CACF,IAAA,CAEF,SAASC,GAAuB,CAC9B,GAAI,CAACD,CAAAA,CACH,GAAI,CAGFA,CAAAA,CADY,CAAA,CAAQ,sBAAsB,CAAA,CACjB,kBAC3B,CAAA,KAAQ,CACN,MAAM,IAAI,KAAA,CACR,mGAEF,CACF,CAGF,OAAOA,CACT,CAuBO,SAASE,EAAAA,CAOdlB,EAAoC,CAEpC,IAAMrF,EADoBsG,CAAAA,EAAqB,CACdjB,CAAM,CAAA,CAEvC,OAAI,OAAO,MAAA,CAAW,KAAe,CAACrF,CAAAA,CAAO,WAC3CA,CAAAA,CAAO,KAAA,EAAM,CAGf6C,gBAAAA,CAAU,IAAM,CACd7C,CAAAA,CAAO,UACT,CAAC,EAEMA,CACT","file":"index.cjs","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n ErrorBoundaryConfig,\n HistoryState,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemInspection,\n SystemSnapshot,\n TraceOption,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { onDestroy } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationId: string,\n): Readable<T> {\n if (process.env.NODE_ENV !== \"production\") {\n const initialValue = system.read(derivationId);\n if (initialValue === undefined) {\n console.warn(\n `[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n return readable<T>(system.read(derivationId) as T, (set) => {\n const unsubscribe = system.subscribe([derivationId], () => {\n set(system.read(derivationId) as T);\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Readable<T> {\n const getValues = (): T => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n return result as T;\n };\n\n return readable<T>(getValues(), (set) => {\n const unsubscribe = system.subscribe(derivationIds, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n factKey: string,\n): Readable<T | undefined> {\n if (process.env.NODE_ENV !== \"production\") {\n if (!system.facts.$store.has(factKey)) {\n console.warn(\n `[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n return readable<T | undefined>(\n system.facts.$store.get(factKey) as T | undefined,\n (set) => {\n const unsubscribe = system.facts.$store.subscribe([factKey], () => {\n set(system.facts.$store.get(factKey) as T | undefined);\n });\n return unsubscribe;\n },\n );\n}\n\n/**\n * Create a Svelte store for system inspection data.\n * NOTE: This updates on every fact change. Use sparingly in production.\n */\nexport function createInspectStore(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n return readable<SystemInspection>(system.inspect(), (set) => {\n const update = () => set(system.inspect());\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKey: K,\n): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKeys: K[],\n): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): Readable<unknown> {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFactMulti(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Readable<Record<string, unknown>> {\n const getValues = (): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationId: K,\n): Readable<InferDerivations<S>[K]>;\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n idOrIds: string | string[],\n): Readable<unknown> {\n assertSystem(\"useDerived\", system);\n if (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"function\") {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(idOrIds)) {\n return createDerivedsStore(system, idOrIds);\n }\n\n // Single key path\n return createDerivedStore(system, idOrIds);\n}\n\n// ============================================================================\n// useSelector — auto-tracking selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations.\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys.\n */\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n equalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n assertSystem(\"useSelector\", system);\n const deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const runWithTracking = () =>\n runTrackedSelector(system, deriveKeySet, selector);\n\n const initial = runWithTracking();\n\n return readable(initial.value, (set) => {\n let currentSelected = initial.value;\n let trackedFactKeys = initial.factKeys;\n let trackedDeriveKeys = initial.deriveKeys;\n const unsubs: Array<() => void> = [];\n\n const resubscribe = () => {\n for (const unsub of unsubs) unsub();\n unsubs.length = 0;\n\n const onUpdate = () => {\n const result = runWithTracking();\n if (!equalityFn(currentSelected, result.value)) {\n currentSelected = result.value;\n set(result.value);\n }\n // Re-track: check if deps changed\n if (\n depsChanged(\n trackedFactKeys,\n result.factKeys,\n trackedDeriveKeys,\n result.deriveKeys,\n )\n ) {\n trackedFactKeys = result.factKeys;\n trackedDeriveKeys = result.deriveKeys;\n resubscribe();\n }\n };\n\n if (trackedFactKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n } else if (trackedDeriveKeys.length === 0) {\n unsubs.push(system.facts.$store.subscribeAll(onUpdate));\n }\n if (trackedDeriveKeys.length > 0) {\n unsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n });\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return (event: InferEvents<S>) => {\n system.dispatch(event);\n };\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher.\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return system.events;\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n previousValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n previousValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n callback: (newValue: unknown, prevValue: unknown) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const unsubscribe = system.watch(key, callback);\n onDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n throttleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): Readable<InspectState> {\n assertSystem(\"useInspect\", system);\n if (options?.throttleMs && options.throttleMs > 0) {\n return readable<InspectState>(computeInspectState(system), (set) => {\n const { throttled, cleanup } = createThrottle(() => {\n set(computeInspectState(system));\n }, options.throttleMs!);\n\n const unsubFacts = system.facts.$store.subscribeAll(throttled);\n const unsubSettled = system.onSettledChange(throttled);\n\n return () => {\n cleanup();\n unsubFacts();\n unsubSettled();\n };\n });\n }\n\n return readable<InspectState>(computeInspectState(system), (set) => {\n const update = () => set(computeInspectState(system));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n):\n | Readable<RequirementTypeStatus>\n | Readable<Record<string, RequirementTypeStatus>> {\n if (Array.isArray(typeOrTypes)) {\n const getValues = (): Record<string, RequirementTypeStatus> => {\n const result: Record<string, RequirementTypeStatus> = {};\n for (const type of typeOrTypes) {\n result[type] = statusPlugin.getStatus(type);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(getValues());\n });\n return unsubscribe;\n });\n }\n\n return readable<RequirementTypeStatus>(\n statusPlugin.getStatus(typeOrTypes),\n (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(statusPlugin.getStatus(typeOrTypes));\n });\n return unsubscribe;\n },\n );\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): Readable<string | null> {\n assertSystem(\"useExplain\", system);\n return readable<string | null>(system.explain(requirementId), (set) => {\n const update = () => set(system.explain(requirementId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): Readable<ConstraintInfo | null>;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n assertSystem(\"useConstraintStatus\", system);\n return readable<ConstraintInfo[] | ConstraintInfo | null>(\n _getConstraintValue(system, constraintId),\n (set) => {\n const update = () => set(_getConstraintValue(system, constraintId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n );\n}\n\nfunction _getConstraintValue(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return (\n inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ??\n null\n );\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n mutate: (updateFn: () => void) => void;\n isPending: Readable<boolean>;\n error: Readable<Error | null>;\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n let isPendingValue = false;\n let errorValue: Error | null = null;\n let snapshot: SystemSnapshot | null = null;\n let statusUnsub: (() => void) | null = null;\n\n // We track subscribers manually since we need imperative push\n const pendingSubscribers = new Set<(v: boolean) => void>();\n const errorSubscribers = new Set<(v: Error | null) => void>();\n\n const isPending: Readable<boolean> = {\n subscribe(fn) {\n fn(isPendingValue);\n pendingSubscribers.add(fn);\n return () => pendingSubscribers.delete(fn);\n },\n };\n\n const error: Readable<Error | null> = {\n subscribe(fn) {\n fn(errorValue);\n errorSubscribers.add(fn);\n return () => errorSubscribers.delete(fn);\n },\n };\n\n const setPending = (v: boolean) => {\n isPendingValue = v;\n for (const fn of pendingSubscribers) fn(v);\n };\n\n const setError = (v: Error | null) => {\n errorValue = v;\n for (const fn of errorSubscribers) fn(v);\n };\n\n const rollback = () => {\n if (snapshot) {\n system.restore(snapshot);\n snapshot = null;\n }\n setPending(false);\n setError(null);\n statusUnsub?.();\n statusUnsub = null;\n };\n\n const mutate = (updateFn: () => void) => {\n snapshot = system.getSnapshot();\n setPending(true);\n setError(null);\n system.batch(updateFn);\n\n if (statusPlugin && requirementType) {\n statusUnsub?.();\n statusUnsub = statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n snapshot = null;\n setPending(false);\n statusUnsub?.();\n statusUnsub = null;\n } else if (status.hasError) {\n setError(status.lastError);\n rollback();\n }\n });\n }\n };\n\n onDestroy(() => {\n statusUnsub?.();\n });\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useHistory — reactive history store\n// ============================================================================\n\n/**\n * Reactive history Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const history = useHistory(system);\n * <button disabled={!$history?.canGoBack} on:click={() => $history?.goBack()}>Undo</button>\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): Readable<HistoryState | null> {\n assertSystem(\"useHistory\", system);\n return readable<HistoryState | null>(buildHistoryState(system), (set) => {\n return system.onHistoryChange(() => set(buildHistoryState(system)));\n });\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\ninterface UseDirectiveConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n status?: boolean;\n /** Fact keys to subscribe to (omit for all) */\n facts?: string[];\n /** Derivation keys to subscribe to (omit for all) */\n derived?: string[];\n}\n\n/**\n * Create a scoped Directive system with automatic lifecycle management.\n * When no `facts` or `derived` keys are specified, subscribes to ALL\n * facts and derivations and returns Svelte readable stores.\n *\n * @example\n * ```svelte\n * // Subscribe to everything\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n *\n * // Selective keys\n * const { facts, derived } = useDirective(counterModule, { facts: [\"count\"], derived: [\"doubled\"] });\n * ```\n */\nexport function useDirective<M extends ModuleSchema>(\n moduleDef: ModuleDef<M>,\n config?: UseDirectiveConfig,\n): {\n system: SingleModuleSystem<M>;\n facts: Readable<InferFacts<M>>;\n derived: Readable<InferDerivations<M>>;\n events: SingleModuleSystem<M>[\"events\"];\n dispatch: (event: InferEvents<M>) => void;\n statusPlugin: StatusPlugin | undefined;\n} {\n const allPlugins = [...(config?.plugins ?? [])];\n let statusPlugin: StatusPlugin | undefined;\n\n if (config?.status) {\n const sp = createRequirementStatusPlugin();\n statusPlugin = sp;\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins.push(sp.plugin as Plugin<any>);\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: moduleDef,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n trace: config?.trace,\n errorBoundary: config?.errorBoundary,\n tickMs: config?.tickMs,\n zeroConfig: config?.zeroConfig,\n initialFacts: config?.initialFacts,\n } as any) as unknown as SingleModuleSystem<M>;\n\n // SSR guard: initialize facts for SSR rendering, start reconciliation only in the browser\n if (typeof window !== \"undefined\") {\n system.start();\n } else {\n system.initialize();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n const factKeys = config?.facts;\n const derivedKeys = config?.derived;\n const subscribeAll = !factKeys && !derivedKeys;\n\n // Subscribe to facts\n const factsStore: Readable<InferFacts<M>> = subscribeAll\n ? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n return system.facts.$store.subscribeAll(() => {\n set(system.facts.$store.toObject() as InferFacts<M>);\n });\n })\n : readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n if (!factKeys || factKeys.length === 0) return () => {};\n return system.facts.$store.subscribe(factKeys, () => {\n set(pickFacts(system, factKeys) as InferFacts<M>);\n });\n });\n\n // Subscribe to derivations\n const allDerivationKeys = subscribeAll\n ? Object.keys(system.derive ?? {})\n : (derivedKeys ?? []);\n const getDerived = (): InferDerivations<M> => {\n const result: Record<string, unknown> = {};\n for (const key of allDerivationKeys) {\n result[key] = system.read(key);\n }\n return result as InferDerivations<M>;\n };\n const derivedStore: Readable<InferDerivations<M>> =\n allDerivationKeys.length > 0\n ? readable(getDerived(), (set) => {\n return system.subscribe(allDerivationKeys, () => {\n set(getDerived());\n });\n })\n : readable(getDerived(), () => () => {});\n\n const events = system.events;\n const dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n return {\n system,\n facts: factsStore,\n derived: derivedStore,\n events,\n dispatch,\n statusPlugin,\n };\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => Readable<InferFacts<M>[K] | undefined>;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => Readable<InferDerivations<M>[K]>;\n useDispatch: (\n system: SingleModuleSystem<M>,\n ) => (event: InferEvents<M>) => void;\n useEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>[\"events\"];\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) => void;\n} {\n return {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useFact(system as SingleModuleSystem<any>, factKey) as Readable<\n InferFacts<M>[K] | undefined\n >,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useDerived(system as SingleModuleSystem<any>, derivationId) as Readable<\n InferDerivations<M>[K]\n >,\n useDispatch: (system: SingleModuleSystem<M>) => {\n return (event: InferEvents<M>) => {\n system.dispatch(event);\n };\n },\n useEvents: (system: SingleModuleSystem<M>) => useEvents<M>(system),\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem\n// ============================================================================\n\n/**\n * Svelte readable store that selects from a NamespacedSystem.\n * Subscribes to specified keys and provides reactive updates.\n *\n * @param system - The namespaced system\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```svelte\n * const token$ = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): Readable<R> {\n return readable<R>(selector(system), (set) => {\n const unsubscribe = system.subscribe(keys, () => {\n set(selector(system));\n });\n\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useQuerySystem — Stable query system with lifecycle management\n// ============================================================================\n\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nlet _createQuerySystem: ((config: Record<string, unknown>) => any) | null =\n null;\n\nfunction getCreateQuerySystem() {\n if (!_createQuerySystem) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@directive-run/query\");\n _createQuerySystem = mod.createQuerySystem;\n } catch {\n throw new Error(\n \"[Directive] @directive-run/query is not installed. \" +\n \"Install it with: pnpm add @directive-run/query\",\n );\n }\n }\n\n return _createQuerySystem!;\n}\n\n/**\n * Svelte composable to create and manage a query system with proper lifecycle.\n *\n * Accepts a config object or a factory function that creates the system.\n * Handles cleanup on component destroy.\n *\n * @example\n * ```svelte\n * <script>\n * import { useQuerySystem, useDerived } from \"@directive-run/svelte\";\n *\n * const app = useQuerySystem({\n * facts: { userId: \"\" },\n * queries: { user: { key: ..., fetcher: ... } },\n * });\n *\n * const user = useDerived(app, \"user\");\n * </script>\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nexport function useQuerySystem<\n T extends {\n start: () => void;\n destroy: () => void;\n isRunning?: boolean;\n [key: string]: any;\n },\n>(config: Record<string, unknown>): T {\n const createQuerySystem = getCreateQuerySystem();\n const system = createQuerySystem(config) as T;\n\n if (typeof window !== \"undefined\" && !system.isRunning) {\n system.start();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n return system;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["createDerivedStore","system","derivationId","readable","set","createDerivedsStore","derivationIds","getValues","result","id","createFactStore","factKey","createInspectStore","update","unsubFacts","unsubSettled","useFact","keyOrKeys","assertSystem","_useFactMulti","factKeys","key","useDerived","idOrIds","useSelector","selector","equalityFn","defaultEquality","deriveKeySet","runWithTracking","runTrackedSelector","initial","currentSelected","trackedFactKeys","trackedDeriveKeys","unsubs","resubscribe","unsub","onUpdate","depsChanged","useDispatch","event","useEvents","useWatch","callback","unsubscribe","onDestroy","useInspect","options","computeInspectState","throttled","cleanup","createThrottle","useRequirementStatus","statusPlugin","typeOrTypes","type","useExplain","requirementId","useConstraintStatus","constraintId","_getConstraintValue","inspection","c","useOptimisticUpdate","requirementType","isPendingValue","errorValue","snapshot","statusUnsub","pendingSubscribers","errorSubscribers","isPending","fn","error","setPending","v","setError","rollback","mutate","updateFn","status","useHistory","buildHistoryState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks","useNamespacedSelector","keys","_createQuerySystem","getCreateQuerySystem","useQuerySystem","HYDRATION_KEY","setHydrationSnapshot","setContext","useHydratedSystem","getContext","mergedFacts","mergeHydrationFacts"],"mappings":"sKA4BA,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAA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dvB,EACAC,CAAAA,CACuB,CACvB,IAAMlB,CAAAA,CAAWyC,kBAAgDJ,CAAa,CAAA,CACxEK,EAAcC,gCAAAA,CAAoB3C,CAAAA,CAAUkB,GAAQ,YAAuC,CAAA,CAEjG,OAAOF,CAAAA,CAAaC,CAAAA,CAAW,CAAE,GAAGC,CAAAA,CAAQ,aAAcwB,CAAY,CAAC,EAAE,MAC3E","file":"index.cjs","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n ErrorBoundaryConfig,\n HistoryState,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemInspection,\n SystemSnapshot,\n TraceOption,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n pickFacts,\n runTrackedSelector,\n mergeHydrationFacts,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { getContext, onDestroy, setContext } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationId: string,\n): Readable<T> {\n if (process.env.NODE_ENV !== \"production\") {\n const initialValue = system.read(derivationId);\n if (initialValue === undefined) {\n console.warn(\n `[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n return readable<T>(system.read(derivationId) as T, (set) => {\n const unsubscribe = system.subscribe([derivationId], () => {\n set(system.read(derivationId) as T);\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Readable<T> {\n const getValues = (): T => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n return result as T;\n };\n\n return readable<T>(getValues(), (set) => {\n const unsubscribe = system.subscribe(derivationIds, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n factKey: string,\n): Readable<T | undefined> {\n if (process.env.NODE_ENV !== \"production\") {\n if (!system.facts.$store.has(factKey)) {\n console.warn(\n `[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n return readable<T | undefined>(\n system.facts.$store.get(factKey) as T | undefined,\n (set) => {\n const unsubscribe = system.facts.$store.subscribe([factKey], () => {\n set(system.facts.$store.get(factKey) as T | undefined);\n });\n return unsubscribe;\n },\n );\n}\n\n/**\n * Create a Svelte store for system inspection data.\n * NOTE: This updates on every fact change. Use sparingly in production.\n */\nexport function createInspectStore(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n return readable<SystemInspection>(system.inspect(), (set) => {\n const update = () => set(system.inspect());\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKey: K,\n): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKeys: K[],\n): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): Readable<unknown> {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFactMulti(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Readable<Record<string, unknown>> {\n const getValues = (): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationId: K,\n): Readable<InferDerivations<S>[K]>;\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n idOrIds: string | string[],\n): Readable<unknown> {\n assertSystem(\"useDerived\", system);\n if (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"function\") {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(idOrIds)) {\n return createDerivedsStore(system, idOrIds);\n }\n\n // Single key path\n return createDerivedStore(system, idOrIds);\n}\n\n// ============================================================================\n// useSelector — auto-tracking selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations.\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys.\n */\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n equalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n assertSystem(\"useSelector\", system);\n const deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const runWithTracking = () =>\n runTrackedSelector(system, deriveKeySet, selector);\n\n const initial = runWithTracking();\n\n return readable(initial.value, (set) => {\n let currentSelected = initial.value;\n let trackedFactKeys = initial.factKeys;\n let trackedDeriveKeys = initial.deriveKeys;\n const unsubs: Array<() => void> = [];\n\n const resubscribe = () => {\n for (const unsub of unsubs) unsub();\n unsubs.length = 0;\n\n const onUpdate = () => {\n const result = runWithTracking();\n if (!equalityFn(currentSelected, result.value)) {\n currentSelected = result.value;\n set(result.value);\n }\n // Re-track: check if deps changed\n if (\n depsChanged(\n trackedFactKeys,\n result.factKeys,\n trackedDeriveKeys,\n result.deriveKeys,\n )\n ) {\n trackedFactKeys = result.factKeys;\n trackedDeriveKeys = result.deriveKeys;\n resubscribe();\n }\n };\n\n if (trackedFactKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n } else if (trackedDeriveKeys.length === 0) {\n unsubs.push(system.facts.$store.subscribeAll(onUpdate));\n }\n if (trackedDeriveKeys.length > 0) {\n unsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n });\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return (event: InferEvents<S>) => {\n system.dispatch(event);\n };\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher.\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return system.events;\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n previousValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n previousValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n callback: (newValue: unknown, prevValue: unknown) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const unsubscribe = system.watch(key, callback);\n onDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n throttleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): Readable<InspectState> {\n assertSystem(\"useInspect\", system);\n if (options?.throttleMs && options.throttleMs > 0) {\n return readable<InspectState>(computeInspectState(system), (set) => {\n const { throttled, cleanup } = createThrottle(() => {\n set(computeInspectState(system));\n }, options.throttleMs!);\n\n const unsubFacts = system.facts.$store.subscribeAll(throttled);\n const unsubSettled = system.onSettledChange(throttled);\n\n return () => {\n cleanup();\n unsubFacts();\n unsubSettled();\n };\n });\n }\n\n return readable<InspectState>(computeInspectState(system), (set) => {\n const update = () => set(computeInspectState(system));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n):\n | Readable<RequirementTypeStatus>\n | Readable<Record<string, RequirementTypeStatus>> {\n if (Array.isArray(typeOrTypes)) {\n const getValues = (): Record<string, RequirementTypeStatus> => {\n const result: Record<string, RequirementTypeStatus> = {};\n for (const type of typeOrTypes) {\n result[type] = statusPlugin.getStatus(type);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(getValues());\n });\n return unsubscribe;\n });\n }\n\n return readable<RequirementTypeStatus>(\n statusPlugin.getStatus(typeOrTypes),\n (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(statusPlugin.getStatus(typeOrTypes));\n });\n return unsubscribe;\n },\n );\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): Readable<string | null> {\n assertSystem(\"useExplain\", system);\n return readable<string | null>(system.explain(requirementId), (set) => {\n const update = () => set(system.explain(requirementId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): Readable<ConstraintInfo | null>;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n assertSystem(\"useConstraintStatus\", system);\n return readable<ConstraintInfo[] | ConstraintInfo | null>(\n _getConstraintValue(system, constraintId),\n (set) => {\n const update = () => set(_getConstraintValue(system, constraintId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n );\n}\n\nfunction _getConstraintValue(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return (\n inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ??\n null\n );\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n mutate: (updateFn: () => void) => void;\n isPending: Readable<boolean>;\n error: Readable<Error | null>;\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n let isPendingValue = false;\n let errorValue: Error | null = null;\n let snapshot: SystemSnapshot | null = null;\n let statusUnsub: (() => void) | null = null;\n\n // We track subscribers manually since we need imperative push\n const pendingSubscribers = new Set<(v: boolean) => void>();\n const errorSubscribers = new Set<(v: Error | null) => void>();\n\n const isPending: Readable<boolean> = {\n subscribe(fn) {\n fn(isPendingValue);\n pendingSubscribers.add(fn);\n return () => pendingSubscribers.delete(fn);\n },\n };\n\n const error: Readable<Error | null> = {\n subscribe(fn) {\n fn(errorValue);\n errorSubscribers.add(fn);\n return () => errorSubscribers.delete(fn);\n },\n };\n\n const setPending = (v: boolean) => {\n isPendingValue = v;\n for (const fn of pendingSubscribers) fn(v);\n };\n\n const setError = (v: Error | null) => {\n errorValue = v;\n for (const fn of errorSubscribers) fn(v);\n };\n\n const rollback = () => {\n if (snapshot) {\n system.restore(snapshot);\n snapshot = null;\n }\n setPending(false);\n setError(null);\n statusUnsub?.();\n statusUnsub = null;\n };\n\n const mutate = (updateFn: () => void) => {\n snapshot = system.getSnapshot();\n setPending(true);\n setError(null);\n system.batch(updateFn);\n\n if (statusPlugin && requirementType) {\n statusUnsub?.();\n statusUnsub = statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n snapshot = null;\n setPending(false);\n statusUnsub?.();\n statusUnsub = null;\n } else if (status.hasError) {\n setError(status.lastError);\n rollback();\n }\n });\n }\n };\n\n onDestroy(() => {\n statusUnsub?.();\n });\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useHistory — reactive history store\n// ============================================================================\n\n/**\n * Reactive history Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const history = useHistory(system);\n * <button disabled={!$history?.canGoBack} on:click={() => $history?.goBack()}>Undo</button>\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): Readable<HistoryState | null> {\n assertSystem(\"useHistory\", system);\n return readable<HistoryState | null>(buildHistoryState(system), (set) => {\n return system.onHistoryChange(() => set(buildHistoryState(system)));\n });\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\nexport interface UseDirectiveConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n status?: boolean;\n /** Fact keys to subscribe to (omit for all) */\n facts?: string[];\n /** Derivation keys to subscribe to (omit for all) */\n derived?: string[];\n}\n\n/**\n * Create a scoped Directive system with automatic lifecycle management.\n * When no `facts` or `derived` keys are specified, subscribes to ALL\n * facts and derivations and returns Svelte readable stores.\n *\n * @example\n * ```svelte\n * // Subscribe to everything\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n *\n * // Selective keys\n * const { facts, derived } = useDirective(counterModule, { facts: [\"count\"], derived: [\"doubled\"] });\n * ```\n */\nexport function useDirective<M extends ModuleSchema>(\n moduleDef: ModuleDef<M>,\n config?: UseDirectiveConfig,\n): {\n system: SingleModuleSystem<M>;\n facts: Readable<InferFacts<M>>;\n derived: Readable<InferDerivations<M>>;\n events: SingleModuleSystem<M>[\"events\"];\n dispatch: (event: InferEvents<M>) => void;\n statusPlugin: StatusPlugin | undefined;\n} {\n const allPlugins = [...(config?.plugins ?? [])];\n let statusPlugin: StatusPlugin | undefined;\n\n if (config?.status) {\n const sp = createRequirementStatusPlugin();\n statusPlugin = sp;\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins.push(sp.plugin as Plugin<any>);\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: moduleDef,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n trace: config?.trace,\n errorBoundary: config?.errorBoundary,\n tickMs: config?.tickMs,\n zeroConfig: config?.zeroConfig,\n initialFacts: config?.initialFacts,\n } as any) as unknown as SingleModuleSystem<M>;\n\n // SSR guard: initialize facts for SSR rendering, start reconciliation only in the browser\n if (typeof window !== \"undefined\") {\n system.start();\n } else {\n system.initialize();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n const factKeys = config?.facts;\n const derivedKeys = config?.derived;\n const subscribeAll = !factKeys && !derivedKeys;\n\n // Subscribe to facts\n const factsStore: Readable<InferFacts<M>> = subscribeAll\n ? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n return system.facts.$store.subscribeAll(() => {\n set(system.facts.$store.toObject() as InferFacts<M>);\n });\n })\n : readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n if (!factKeys || factKeys.length === 0) return () => {};\n return system.facts.$store.subscribe(factKeys, () => {\n set(pickFacts(system, factKeys) as InferFacts<M>);\n });\n });\n\n // Subscribe to derivations\n const allDerivationKeys = subscribeAll\n ? Object.keys(system.derive ?? {})\n : (derivedKeys ?? []);\n const getDerived = (): InferDerivations<M> => {\n const result: Record<string, unknown> = {};\n for (const key of allDerivationKeys) {\n result[key] = system.read(key);\n }\n return result as InferDerivations<M>;\n };\n const derivedStore: Readable<InferDerivations<M>> =\n allDerivationKeys.length > 0\n ? readable(getDerived(), (set) => {\n return system.subscribe(allDerivationKeys, () => {\n set(getDerived());\n });\n })\n : readable(getDerived(), () => () => {});\n\n const events = system.events;\n const dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n return {\n system,\n facts: factsStore,\n derived: derivedStore,\n events,\n dispatch,\n statusPlugin,\n };\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => Readable<InferFacts<M>[K] | undefined>;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => Readable<InferDerivations<M>[K]>;\n useDispatch: (\n system: SingleModuleSystem<M>,\n ) => (event: InferEvents<M>) => void;\n useEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>[\"events\"];\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) => void;\n} {\n return {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useFact(system as SingleModuleSystem<any>, factKey) as Readable<\n InferFacts<M>[K] | undefined\n >,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useDerived(system as SingleModuleSystem<any>, derivationId) as Readable<\n InferDerivations<M>[K]\n >,\n useDispatch: (system: SingleModuleSystem<M>) => {\n return (event: InferEvents<M>) => {\n system.dispatch(event);\n };\n },\n useEvents: (system: SingleModuleSystem<M>) => useEvents<M>(system),\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem\n// ============================================================================\n\n/**\n * Svelte readable store that selects from a NamespacedSystem.\n * Subscribes to specified keys and provides reactive updates.\n *\n * @param system - The namespaced system\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```svelte\n * const token$ = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): Readable<R> {\n return readable<R>(selector(system), (set) => {\n const unsubscribe = system.subscribe(keys, () => {\n set(selector(system));\n });\n\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useQuerySystem — Stable query system with lifecycle management\n// ============================================================================\n\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nlet _createQuerySystem: ((config: Record<string, unknown>) => any) | null =\n null;\n\nfunction getCreateQuerySystem() {\n if (!_createQuerySystem) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@directive-run/query\");\n _createQuerySystem = mod.createQuerySystem;\n } catch {\n throw new Error(\n \"[Directive] @directive-run/query is not installed. \" +\n \"Install it with: pnpm add @directive-run/query\",\n );\n }\n }\n\n return _createQuerySystem!;\n}\n\n/**\n * Svelte composable to create and manage a query system with proper lifecycle.\n *\n * Accepts a config object or a factory function that creates the system.\n * Handles cleanup on component destroy.\n *\n * @example\n * ```svelte\n * <script>\n * import { useQuerySystem, useDerived } from \"@directive-run/svelte\";\n *\n * const app = useQuerySystem({\n * facts: { userId: \"\" },\n * queries: { user: { key: ..., fetcher: ... } },\n * });\n *\n * const user = useDerived(app, \"user\");\n * </script>\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nexport function useQuerySystem<\n T extends {\n start: () => void;\n destroy: () => void;\n isRunning?: boolean;\n [key: string]: any;\n },\n>(config: Record<string, unknown>): T {\n const createQuerySystem = getCreateQuerySystem();\n const system = createQuerySystem(config) as T;\n\n if (typeof window !== \"undefined\" && !system.isRunning) {\n system.start();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n return system;\n}\n\n// ============================================================================\n// SSR Hydration\n// ============================================================================\n\n/** @internal Context key for SSR hydration snapshot */\nconst HYDRATION_KEY = Symbol(\"directive-hydration\");\n\n/**\n * Provide a DistributableSnapshot for child components to hydrate from.\n * Call this in your layout or parent component (e.g., SvelteKit +layout.svelte).\n *\n * @example\n * ```svelte\n * <script>\n * import { setHydrationSnapshot } from \"@directive-run/svelte\";\n * export let data; // from SvelteKit load()\n * setHydrationSnapshot(data.snapshot);\n * </script>\n * <slot />\n * ```\n */\nexport function setHydrationSnapshot(snapshot: Record<string, unknown>): void {\n setContext(HYDRATION_KEY, snapshot);\n}\n\n/**\n * Create a system hydrated from a server snapshot.\n * Must be called in a component that is a descendant of one that called `setHydrationSnapshot`.\n *\n * @example\n * ```svelte\n * <script>\n * import { useHydratedSystem, useDerived } from \"@directive-run/svelte\";\n * const system = useHydratedSystem(myModule);\n * const count = useDerived(system, \"count\");\n * </script>\n * ```\n */\nexport function useHydratedSystem<S extends ModuleSchema>(\n moduleDef: ModuleDef<S>,\n config?: UseDirectiveConfig,\n): SingleModuleSystem<S> {\n const snapshot = getContext<Record<string, unknown> | undefined>(HYDRATION_KEY);\n const mergedFacts = mergeHydrationFacts(snapshot, config?.initialFacts as Record<string, unknown>);\n\n return useDirective(moduleDef, { ...config, initialFacts: mergedFacts }).system;\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createRequirementStatusPlugin, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef,
|
|
1
|
+
import { createRequirementStatusPlugin, Plugin, TraceOption, ErrorBoundaryConfig, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, HistoryState, ModulesMap, NamespacedSystem, RequirementTypeStatus, InferSelectorState } from '@directive-run/core';
|
|
2
2
|
export { RequirementTypeStatus } from '@directive-run/core';
|
|
3
3
|
import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
|
|
4
4
|
export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
|
|
@@ -183,5 +183,34 @@ declare function useQuerySystem<T extends {
|
|
|
183
183
|
isRunning?: boolean;
|
|
184
184
|
[key: string]: any;
|
|
185
185
|
}>(config: Record<string, unknown>): T;
|
|
186
|
+
/**
|
|
187
|
+
* Provide a DistributableSnapshot for child components to hydrate from.
|
|
188
|
+
* Call this in your layout or parent component (e.g., SvelteKit +layout.svelte).
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```svelte
|
|
192
|
+
* <script>
|
|
193
|
+
* import { setHydrationSnapshot } from "@directive-run/svelte";
|
|
194
|
+
* export let data; // from SvelteKit load()
|
|
195
|
+
* setHydrationSnapshot(data.snapshot);
|
|
196
|
+
* </script>
|
|
197
|
+
* <slot />
|
|
198
|
+
* ```
|
|
199
|
+
*/
|
|
200
|
+
declare function setHydrationSnapshot(snapshot: Record<string, unknown>): void;
|
|
201
|
+
/**
|
|
202
|
+
* Create a system hydrated from a server snapshot.
|
|
203
|
+
* Must be called in a component that is a descendant of one that called `setHydrationSnapshot`.
|
|
204
|
+
*
|
|
205
|
+
* @example
|
|
206
|
+
* ```svelte
|
|
207
|
+
* <script>
|
|
208
|
+
* import { useHydratedSystem, useDerived } from "@directive-run/svelte";
|
|
209
|
+
* const system = useHydratedSystem(myModule);
|
|
210
|
+
* const count = useDerived(system, "count");
|
|
211
|
+
* </script>
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
214
|
+
declare function useHydratedSystem<S extends ModuleSchema>(moduleDef: ModuleDef<S>, config?: UseDirectiveConfig): SingleModuleSystem<S>;
|
|
186
215
|
|
|
187
|
-
export { type OptimisticUpdateResult, type StatusPlugin, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useHistory, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useWatch };
|
|
216
|
+
export { type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveConfig, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, setHydrationSnapshot, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useHistory, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useWatch };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createRequirementStatusPlugin, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef,
|
|
1
|
+
import { createRequirementStatusPlugin, Plugin, TraceOption, ErrorBoundaryConfig, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, HistoryState, ModulesMap, NamespacedSystem, RequirementTypeStatus, InferSelectorState } from '@directive-run/core';
|
|
2
2
|
export { RequirementTypeStatus } from '@directive-run/core';
|
|
3
3
|
import { ConstraintInfo, InspectState } from '@directive-run/core/adapter-utils';
|
|
4
4
|
export { ConstraintInfo, InspectState, shallowEqual } from '@directive-run/core/adapter-utils';
|
|
@@ -183,5 +183,34 @@ declare function useQuerySystem<T extends {
|
|
|
183
183
|
isRunning?: boolean;
|
|
184
184
|
[key: string]: any;
|
|
185
185
|
}>(config: Record<string, unknown>): T;
|
|
186
|
+
/**
|
|
187
|
+
* Provide a DistributableSnapshot for child components to hydrate from.
|
|
188
|
+
* Call this in your layout or parent component (e.g., SvelteKit +layout.svelte).
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```svelte
|
|
192
|
+
* <script>
|
|
193
|
+
* import { setHydrationSnapshot } from "@directive-run/svelte";
|
|
194
|
+
* export let data; // from SvelteKit load()
|
|
195
|
+
* setHydrationSnapshot(data.snapshot);
|
|
196
|
+
* </script>
|
|
197
|
+
* <slot />
|
|
198
|
+
* ```
|
|
199
|
+
*/
|
|
200
|
+
declare function setHydrationSnapshot(snapshot: Record<string, unknown>): void;
|
|
201
|
+
/**
|
|
202
|
+
* Create a system hydrated from a server snapshot.
|
|
203
|
+
* Must be called in a component that is a descendant of one that called `setHydrationSnapshot`.
|
|
204
|
+
*
|
|
205
|
+
* @example
|
|
206
|
+
* ```svelte
|
|
207
|
+
* <script>
|
|
208
|
+
* import { useHydratedSystem, useDerived } from "@directive-run/svelte";
|
|
209
|
+
* const system = useHydratedSystem(myModule);
|
|
210
|
+
* const count = useDerived(system, "count");
|
|
211
|
+
* </script>
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
214
|
+
declare function useHydratedSystem<S extends ModuleSchema>(moduleDef: ModuleDef<S>, config?: UseDirectiveConfig): SingleModuleSystem<S>;
|
|
186
215
|
|
|
187
|
-
export { type OptimisticUpdateResult, type StatusPlugin, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useHistory, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useWatch };
|
|
216
|
+
export { type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveConfig, type UseInspectOptions, createDerivedStore, createDerivedsStore, createFactStore, createInspectStore, createTypedHooks, setHydrationSnapshot, useConstraintStatus, useDerived, useDirective, useDispatch, useEvents, useExplain, useFact, useHistory, useHydratedSystem, useInspect, useNamespacedSelector, useOptimisticUpdate, useQuerySystem, useRequirementStatus, useSelector, useWatch };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {createRequirementStatusPlugin,createSystem}from'@directive-run/core';import {defaultEquality,assertSystem,computeInspectState,createThrottle,buildHistoryState,pickFacts,runTrackedSelector,depsChanged}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {onDestroy}from'svelte';import {readable}from'svelte/store';var
|
|
1
|
+
import {createRequirementStatusPlugin,createSystem}from'@directive-run/core';import {defaultEquality,assertSystem,computeInspectState,createThrottle,buildHistoryState,pickFacts,mergeHydrationFacts,runTrackedSelector,depsChanged}from'@directive-run/core/adapter-utils';export{shallowEqual}from'@directive-run/core/adapter-utils';import {onDestroy,setContext,getContext}from'svelte';import {readable}from'svelte/store';var D=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function P(e,t){return process.env.NODE_ENV!=="production"&&e.read(t)===void 0&&console.warn(`[Directive] createDerivedStore("${t}") returned undefined. Check that "${t}" is defined in your module's derive property.`),readable(e.read(t),n=>e.subscribe([t],()=>{n(e.read(t));}))}function A(e,t){let n=()=>{let s={};for(let r of t)s[r]=e.read(r);return s};return readable(n(),s=>e.subscribe(t,()=>{s(n());}))}function N(e,t){return process.env.NODE_ENV!=="production"&&(e.facts.$store.has(t)||console.warn(`[Directive] createFactStore("${t}") \u2014 fact not found in store. Check that "${t}" is defined in your module's schema.`)),readable(e.facts.$store.get(t),n=>e.facts.$store.subscribe([t],()=>{n(e.facts.$store.get(t));}))}function X(e){return readable(e.inspect(),t=>{let n=()=>t(e.inspect()),s=e.facts.$store.subscribeAll(n),r=e.onSettledChange(n);return ()=>{s(),r();}})}function H(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)?U(e,t):N(e,t)}function U(e,t){let n=()=>{let s={};for(let r of t)s[r]=e.facts.$store.get(r);return s};return readable(n(),s=>e.facts.$store.subscribe(t,()=>{s(n());}))}function O(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)?A(e,t):P(e,t)}function Z(e,t,n=defaultEquality){assertSystem("useSelector",e);let s=new Set(Object.keys(e.derive??{})),r=()=>runTrackedSelector(e,s,t),o=r();return readable(o.value,c=>{let p=o.value,g=o.factKeys,S=o.deriveKeys,d=[],y=()=>{for(let l of d)l();d.length=0;let f=()=>{let l=r();n(p,l.value)||(p=l.value,c(l.value)),depsChanged(g,l.factKeys,S,l.deriveKeys)&&(g=l.factKeys,S=l.deriveKeys,y());};g.length>0?d.push(e.facts.$store.subscribe(g,f)):S.length===0&&d.push(e.facts.$store.subscribeAll(f)),S.length>0&&d.push(e.subscribe(S,f));};return y(),()=>{for(let f of d)f();}})}function ee(e){return assertSystem("useDispatch",e),t=>{e.dispatch(t);}}function _(e){return assertSystem("useEvents",e),e.events}function W(e,t,n){assertSystem("useWatch",e);let s=e.watch(t,n);onDestroy(s);}function te(e,t){return assertSystem("useInspect",e),t?.throttleMs&&t.throttleMs>0?readable(computeInspectState(e),n=>{let{throttled:s,cleanup:r}=createThrottle(()=>{n(computeInspectState(e));},t.throttleMs),o=e.facts.$store.subscribeAll(s),c=e.onSettledChange(s);return ()=>{r(),o(),c();}}):readable(computeInspectState(e),n=>{let s=()=>n(computeInspectState(e)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function ne(e,t){if(Array.isArray(t)){let n=()=>{let s={};for(let r of t)s[r]=e.getStatus(r);return s};return readable(n(),s=>e.subscribe(()=>{s(n());}))}return readable(e.getStatus(t),n=>e.subscribe(()=>{n(e.getStatus(t));}))}function se(e,t){return assertSystem("useExplain",e),readable(e.explain(t),n=>{let s=()=>n(e.explain(t)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function re(e,t){return assertSystem("useConstraintStatus",e),readable(k(e,t),n=>{let s=()=>n(k(e,t)),r=e.facts.$store.subscribeAll(s),o=e.onSettledChange(s);return ()=>{r(),o();}})}function k(e,t){let n=e.inspect();return t?n.constraints.find(s=>s.id===t)??null:n.constraints}function oe(e,t,n){assertSystem("useOptimisticUpdate",e);let s=false,r=null,o=null,c=null,p=new Set,g=new Set,S={subscribe(u){return u(s),p.add(u),()=>p.delete(u)}},d={subscribe(u){return u(r),g.add(u),()=>g.delete(u)}},y=u=>{s=u;for(let M of p)M(u);},f=u=>{r=u;for(let M of g)M(u);},l=()=>{o&&(e.restore(o),o=null),y(false),f(null),c?.(),c=null;},a=u=>{o=e.getSnapshot(),y(true),f(null),e.batch(u),t&&n&&(c?.(),c=t.subscribe(()=>{let M=t.getStatus(n);!M.isLoading&&!M.hasError?(o=null,y(false),c?.(),c=null):M.hasError&&(f(M.lastError),l());}));};return onDestroy(()=>{c?.();}),{mutate:a,isPending:S,error:d,rollback:l}}function ue(e){return assertSystem("useHistory",e),readable(buildHistoryState(e),t=>e.onHistoryChange(()=>t(buildHistoryState(e))))}function Q(e,t){let n=[...t?.plugins??[]],s;if(t?.status){let a=createRequirementStatusPlugin();s=a,n.push(a.plugin);}let r=createSystem({module:e,plugins:n.length>0?n:void 0,trace:t?.trace,errorBoundary:t?.errorBoundary,tickMs:t?.tickMs,zeroConfig:t?.zeroConfig,initialFacts:t?.initialFacts});typeof window<"u"?r.start():r.initialize(),onDestroy(()=>{r.destroy();});let o=t?.facts,c=t?.derived,p=!o&&!c,g=p?readable(r.facts.$store.toObject(),a=>r.facts.$store.subscribeAll(()=>{a(r.facts.$store.toObject());})):readable(pickFacts(r,o??[]),a=>!o||o.length===0?()=>{}:r.facts.$store.subscribe(o,()=>{a(pickFacts(r,o));})),S=p?Object.keys(r.derive??{}):c??[],d=()=>{let a={};for(let u of S)a[u]=r.read(u);return a},y=S.length>0?readable(d(),a=>r.subscribe(S,()=>{a(d());})):readable(d(),()=>()=>{}),f=r.events;return {system:r,facts:g,derived:y,events:f,dispatch:a=>r.dispatch(a),statusPlugin:s}}function ie(){return {useFact:(e,t)=>H(e,t),useDerived:(e,t)=>O(e,t),useDispatch:e=>t=>{e.dispatch(t);},useEvents:e=>_(e),useWatch:(e,t,n)=>W(e,t,n)}}function ae(e,t,n){return readable(n(e),s=>e.subscribe(t,()=>{s(n(e));}))}var R=null;function B(){if(!R)try{R=D("@directive-run/query").createQuerySystem;}catch{throw new Error("[Directive] @directive-run/query is not installed. Install it with: pnpm add @directive-run/query")}return R}function ce(e){let n=B()(e);return typeof window<"u"&&!n.isRunning&&n.start(),onDestroy(()=>{n.destroy();}),n}var I=Symbol("directive-hydration");function le(e){setContext(I,e);}function de(e,t){let n=getContext(I),s=mergeHydrationFacts(n,t?.initialFacts);return Q(e,{...t,initialFacts:s}).system}export{P as createDerivedStore,A as createDerivedsStore,N as createFactStore,X as createInspectStore,ie as createTypedHooks,le as setHydrationSnapshot,re as useConstraintStatus,O as useDerived,Q as useDirective,ee as useDispatch,_ as useEvents,se as useExplain,H as useFact,ue as useHistory,de as useHydratedSystem,te as useInspect,ae as useNamespacedSelector,oe as useOptimisticUpdate,ce as useQuerySystem,ne as useRequirementStatus,Z as useSelector,W as useWatch};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["createDerivedStore","system","derivationId","readable","set","createDerivedsStore","derivationIds","getValues","result","id","createFactStore","factKey","createInspectStore","update","unsubFacts","unsubSettled","useFact","keyOrKeys","assertSystem","_useFactMulti","factKeys","key","useDerived","idOrIds","useSelector","selector","equalityFn","defaultEquality","deriveKeySet","runWithTracking","runTrackedSelector","initial","currentSelected","trackedFactKeys","trackedDeriveKeys","unsubs","resubscribe","unsub","onUpdate","depsChanged","useDispatch","event","useEvents","useWatch","callback","unsubscribe","onDestroy","useInspect","options","computeInspectState","throttled","cleanup","createThrottle","useRequirementStatus","statusPlugin","typeOrTypes","type","useExplain","requirementId","useConstraintStatus","constraintId","_getConstraintValue","inspection","c","useOptimisticUpdate","requirementType","isPendingValue","errorValue","snapshot","statusUnsub","pendingSubscribers","errorSubscribers","isPending","fn","error","setPending","v","setError","rollback","mutate","updateFn","status","useHistory","buildHistoryState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks","useNamespacedSelector","keys","_createQuerySystem","getCreateQuerySystem","useQuerySystem"],"mappings":"uXA4BA,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,SAAA,CAAA,CAAA,CAAA,GAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,O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mCC,CAAY,CAAA,CAG5D,WAAA,CAAcD,GACJwC,CAAAA,EAA0B,CAChCxC,EAAO,QAAA,CAASwC,CAAK,EACvB,CAAA,CAEF,SAAA,CAAYxC,CAAAA,EAAkCyC,CAAAA,CAAazC,CAAM,CAAA,CACjE,QAAA,CAAU,CACRA,CAAAA,CACAoB,CAAAA,CACAuB,IAGAD,CAAAA,CAAS1C,CAAAA,CAAmCoB,CAAAA,CAAKuB,CAAQ,CAC7D,CACF,CAmBO,SAASwD,EAAAA,CACdnG,CAAAA,CACAoG,EACA5E,CAAAA,CACa,CACb,OAAOtB,QAAAA,CAAYsB,EAASxB,CAAM,CAAA,CAAIG,GAChBH,CAAAA,CAAO,SAAA,CAAUoG,EAAM,IAAM,CAC/CjG,CAAAA,CAAIqB,CAAAA,CAASxB,CAAM,CAAC,EACtB,CAAC,CAGF,CACH,CAOA,IAAIqG,CAAAA,CACF,IAAA,CAEF,SAASC,GAAuB,CAC9B,GAAI,CAACD,CAAAA,CACH,GAAI,CAGFA,CAAAA,CADY,CAAA,CAAQ,sBAAsB,CAAA,CACjB,kBAC3B,CAAA,KAAQ,CACN,MAAM,IAAI,KAAA,CACR,mGAEF,CACF,CAGF,OAAOA,CACT,CAuBO,SAASE,EAAAA,CAOdlB,EAAoC,CAEpC,IAAMrF,EADoBsG,CAAAA,EAAqB,CACdjB,CAAM,CAAA,CAEvC,OAAI,OAAO,MAAA,CAAW,KAAe,CAACrF,CAAAA,CAAO,WAC3CA,CAAAA,CAAO,KAAA,EAAM,CAGf6C,SAAAA,CAAU,IAAM,CACd7C,CAAAA,CAAO,UACT,CAAC,EAEMA,CACT","file":"index.js","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n ErrorBoundaryConfig,\n HistoryState,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemInspection,\n SystemSnapshot,\n TraceOption,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { onDestroy } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationId: string,\n): Readable<T> {\n if (process.env.NODE_ENV !== \"production\") {\n const initialValue = system.read(derivationId);\n if (initialValue === undefined) {\n console.warn(\n `[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n return readable<T>(system.read(derivationId) as T, (set) => {\n const unsubscribe = system.subscribe([derivationId], () => {\n set(system.read(derivationId) as T);\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Readable<T> {\n const getValues = (): T => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n return result as T;\n };\n\n return readable<T>(getValues(), (set) => {\n const unsubscribe = system.subscribe(derivationIds, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n factKey: string,\n): Readable<T | undefined> {\n if (process.env.NODE_ENV !== \"production\") {\n if (!system.facts.$store.has(factKey)) {\n console.warn(\n `[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n return readable<T | undefined>(\n system.facts.$store.get(factKey) as T | undefined,\n (set) => {\n const unsubscribe = system.facts.$store.subscribe([factKey], () => {\n set(system.facts.$store.get(factKey) as T | undefined);\n });\n return unsubscribe;\n },\n );\n}\n\n/**\n * Create a Svelte store for system inspection data.\n * NOTE: This updates on every fact change. Use sparingly in production.\n */\nexport function createInspectStore(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n return readable<SystemInspection>(system.inspect(), (set) => {\n const update = () => set(system.inspect());\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKey: K,\n): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKeys: K[],\n): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): Readable<unknown> {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFactMulti(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Readable<Record<string, unknown>> {\n const getValues = (): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationId: K,\n): Readable<InferDerivations<S>[K]>;\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n idOrIds: string | string[],\n): Readable<unknown> {\n assertSystem(\"useDerived\", system);\n if (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"function\") {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(idOrIds)) {\n return createDerivedsStore(system, idOrIds);\n }\n\n // Single key path\n return createDerivedStore(system, idOrIds);\n}\n\n// ============================================================================\n// useSelector — auto-tracking selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations.\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys.\n */\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n equalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n assertSystem(\"useSelector\", system);\n const deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const runWithTracking = () =>\n runTrackedSelector(system, deriveKeySet, selector);\n\n const initial = runWithTracking();\n\n return readable(initial.value, (set) => {\n let currentSelected = initial.value;\n let trackedFactKeys = initial.factKeys;\n let trackedDeriveKeys = initial.deriveKeys;\n const unsubs: Array<() => void> = [];\n\n const resubscribe = () => {\n for (const unsub of unsubs) unsub();\n unsubs.length = 0;\n\n const onUpdate = () => {\n const result = runWithTracking();\n if (!equalityFn(currentSelected, result.value)) {\n currentSelected = result.value;\n set(result.value);\n }\n // Re-track: check if deps changed\n if (\n depsChanged(\n trackedFactKeys,\n result.factKeys,\n trackedDeriveKeys,\n result.deriveKeys,\n )\n ) {\n trackedFactKeys = result.factKeys;\n trackedDeriveKeys = result.deriveKeys;\n resubscribe();\n }\n };\n\n if (trackedFactKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n } else if (trackedDeriveKeys.length === 0) {\n unsubs.push(system.facts.$store.subscribeAll(onUpdate));\n }\n if (trackedDeriveKeys.length > 0) {\n unsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n });\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return (event: InferEvents<S>) => {\n system.dispatch(event);\n };\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher.\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return system.events;\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n previousValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n previousValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n callback: (newValue: unknown, prevValue: unknown) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const unsubscribe = system.watch(key, callback);\n onDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n throttleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): Readable<InspectState> {\n assertSystem(\"useInspect\", system);\n if (options?.throttleMs && options.throttleMs > 0) {\n return readable<InspectState>(computeInspectState(system), (set) => {\n const { throttled, cleanup } = createThrottle(() => {\n set(computeInspectState(system));\n }, options.throttleMs!);\n\n const unsubFacts = system.facts.$store.subscribeAll(throttled);\n const unsubSettled = system.onSettledChange(throttled);\n\n return () => {\n cleanup();\n unsubFacts();\n unsubSettled();\n };\n });\n }\n\n return readable<InspectState>(computeInspectState(system), (set) => {\n const update = () => set(computeInspectState(system));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n):\n | Readable<RequirementTypeStatus>\n | Readable<Record<string, RequirementTypeStatus>> {\n if (Array.isArray(typeOrTypes)) {\n const getValues = (): Record<string, RequirementTypeStatus> => {\n const result: Record<string, RequirementTypeStatus> = {};\n for (const type of typeOrTypes) {\n result[type] = statusPlugin.getStatus(type);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(getValues());\n });\n return unsubscribe;\n });\n }\n\n return readable<RequirementTypeStatus>(\n statusPlugin.getStatus(typeOrTypes),\n (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(statusPlugin.getStatus(typeOrTypes));\n });\n return unsubscribe;\n },\n );\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): Readable<string | null> {\n assertSystem(\"useExplain\", system);\n return readable<string | null>(system.explain(requirementId), (set) => {\n const update = () => set(system.explain(requirementId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): Readable<ConstraintInfo | null>;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n assertSystem(\"useConstraintStatus\", system);\n return readable<ConstraintInfo[] | ConstraintInfo | null>(\n _getConstraintValue(system, constraintId),\n (set) => {\n const update = () => set(_getConstraintValue(system, constraintId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n );\n}\n\nfunction _getConstraintValue(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return (\n inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ??\n null\n );\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n mutate: (updateFn: () => void) => void;\n isPending: Readable<boolean>;\n error: Readable<Error | null>;\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n let isPendingValue = false;\n let errorValue: Error | null = null;\n let snapshot: SystemSnapshot | null = null;\n let statusUnsub: (() => void) | null = null;\n\n // We track subscribers manually since we need imperative push\n const pendingSubscribers = new Set<(v: boolean) => void>();\n const errorSubscribers = new Set<(v: Error | null) => void>();\n\n const isPending: Readable<boolean> = {\n subscribe(fn) {\n fn(isPendingValue);\n pendingSubscribers.add(fn);\n return () => pendingSubscribers.delete(fn);\n },\n };\n\n const error: Readable<Error | null> = {\n subscribe(fn) {\n fn(errorValue);\n errorSubscribers.add(fn);\n return () => errorSubscribers.delete(fn);\n },\n };\n\n const setPending = (v: boolean) => {\n isPendingValue = v;\n for (const fn of pendingSubscribers) fn(v);\n };\n\n const setError = (v: Error | null) => {\n errorValue = v;\n for (const fn of errorSubscribers) fn(v);\n };\n\n const rollback = () => {\n if (snapshot) {\n system.restore(snapshot);\n snapshot = null;\n }\n setPending(false);\n setError(null);\n statusUnsub?.();\n statusUnsub = null;\n };\n\n const mutate = (updateFn: () => void) => {\n snapshot = system.getSnapshot();\n setPending(true);\n setError(null);\n system.batch(updateFn);\n\n if (statusPlugin && requirementType) {\n statusUnsub?.();\n statusUnsub = statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n snapshot = null;\n setPending(false);\n statusUnsub?.();\n statusUnsub = null;\n } else if (status.hasError) {\n setError(status.lastError);\n rollback();\n }\n });\n }\n };\n\n onDestroy(() => {\n statusUnsub?.();\n });\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useHistory — reactive history store\n// ============================================================================\n\n/**\n * Reactive history Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const history = useHistory(system);\n * <button disabled={!$history?.canGoBack} on:click={() => $history?.goBack()}>Undo</button>\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): Readable<HistoryState | null> {\n assertSystem(\"useHistory\", system);\n return readable<HistoryState | null>(buildHistoryState(system), (set) => {\n return system.onHistoryChange(() => set(buildHistoryState(system)));\n });\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\ninterface UseDirectiveConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n status?: boolean;\n /** Fact keys to subscribe to (omit for all) */\n facts?: string[];\n /** Derivation keys to subscribe to (omit for all) */\n derived?: string[];\n}\n\n/**\n * Create a scoped Directive system with automatic lifecycle management.\n * When no `facts` or `derived` keys are specified, subscribes to ALL\n * facts and derivations and returns Svelte readable stores.\n *\n * @example\n * ```svelte\n * // Subscribe to everything\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n *\n * // Selective keys\n * const { facts, derived } = useDirective(counterModule, { facts: [\"count\"], derived: [\"doubled\"] });\n * ```\n */\nexport function useDirective<M extends ModuleSchema>(\n moduleDef: ModuleDef<M>,\n config?: UseDirectiveConfig,\n): {\n system: SingleModuleSystem<M>;\n facts: Readable<InferFacts<M>>;\n derived: Readable<InferDerivations<M>>;\n events: SingleModuleSystem<M>[\"events\"];\n dispatch: (event: InferEvents<M>) => void;\n statusPlugin: StatusPlugin | undefined;\n} {\n const allPlugins = [...(config?.plugins ?? [])];\n let statusPlugin: StatusPlugin | undefined;\n\n if (config?.status) {\n const sp = createRequirementStatusPlugin();\n statusPlugin = sp;\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins.push(sp.plugin as Plugin<any>);\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: moduleDef,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n trace: config?.trace,\n errorBoundary: config?.errorBoundary,\n tickMs: config?.tickMs,\n zeroConfig: config?.zeroConfig,\n initialFacts: config?.initialFacts,\n } as any) as unknown as SingleModuleSystem<M>;\n\n // SSR guard: initialize facts for SSR rendering, start reconciliation only in the browser\n if (typeof window !== \"undefined\") {\n system.start();\n } else {\n system.initialize();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n const factKeys = config?.facts;\n const derivedKeys = config?.derived;\n const subscribeAll = !factKeys && !derivedKeys;\n\n // Subscribe to facts\n const factsStore: Readable<InferFacts<M>> = subscribeAll\n ? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n return system.facts.$store.subscribeAll(() => {\n set(system.facts.$store.toObject() as InferFacts<M>);\n });\n })\n : readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n if (!factKeys || factKeys.length === 0) return () => {};\n return system.facts.$store.subscribe(factKeys, () => {\n set(pickFacts(system, factKeys) as InferFacts<M>);\n });\n });\n\n // Subscribe to derivations\n const allDerivationKeys = subscribeAll\n ? Object.keys(system.derive ?? {})\n : (derivedKeys ?? []);\n const getDerived = (): InferDerivations<M> => {\n const result: Record<string, unknown> = {};\n for (const key of allDerivationKeys) {\n result[key] = system.read(key);\n }\n return result as InferDerivations<M>;\n };\n const derivedStore: Readable<InferDerivations<M>> =\n allDerivationKeys.length > 0\n ? readable(getDerived(), (set) => {\n return system.subscribe(allDerivationKeys, () => {\n set(getDerived());\n });\n })\n : readable(getDerived(), () => () => {});\n\n const events = system.events;\n const dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n return {\n system,\n facts: factsStore,\n derived: derivedStore,\n events,\n dispatch,\n statusPlugin,\n };\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => Readable<InferFacts<M>[K] | undefined>;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => Readable<InferDerivations<M>[K]>;\n useDispatch: (\n system: SingleModuleSystem<M>,\n ) => (event: InferEvents<M>) => void;\n useEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>[\"events\"];\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) => void;\n} {\n return {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useFact(system as SingleModuleSystem<any>, factKey) as Readable<\n InferFacts<M>[K] | undefined\n >,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useDerived(system as SingleModuleSystem<any>, derivationId) as Readable<\n InferDerivations<M>[K]\n >,\n useDispatch: (system: SingleModuleSystem<M>) => {\n return (event: InferEvents<M>) => {\n system.dispatch(event);\n };\n },\n useEvents: (system: SingleModuleSystem<M>) => useEvents<M>(system),\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem\n// ============================================================================\n\n/**\n * Svelte readable store that selects from a NamespacedSystem.\n * Subscribes to specified keys and provides reactive updates.\n *\n * @param system - The namespaced system\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```svelte\n * const token$ = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): Readable<R> {\n return readable<R>(selector(system), (set) => {\n const unsubscribe = system.subscribe(keys, () => {\n set(selector(system));\n });\n\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useQuerySystem — Stable query system with lifecycle management\n// ============================================================================\n\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nlet _createQuerySystem: ((config: Record<string, unknown>) => any) | null =\n null;\n\nfunction getCreateQuerySystem() {\n if (!_createQuerySystem) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@directive-run/query\");\n _createQuerySystem = mod.createQuerySystem;\n } catch {\n throw new Error(\n \"[Directive] @directive-run/query is not installed. \" +\n \"Install it with: pnpm add @directive-run/query\",\n );\n }\n }\n\n return _createQuerySystem!;\n}\n\n/**\n * Svelte composable to create and manage a query system with proper lifecycle.\n *\n * Accepts a config object or a factory function that creates the system.\n * Handles cleanup on component destroy.\n *\n * @example\n * ```svelte\n * <script>\n * import { useQuerySystem, useDerived } from \"@directive-run/svelte\";\n *\n * const app = useQuerySystem({\n * facts: { userId: \"\" },\n * queries: { user: { key: ..., fetcher: ... } },\n * });\n *\n * const user = useDerived(app, \"user\");\n * </script>\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nexport function useQuerySystem<\n T extends {\n start: () => void;\n destroy: () => void;\n isRunning?: boolean;\n [key: string]: any;\n },\n>(config: Record<string, unknown>): T {\n const createQuerySystem = getCreateQuerySystem();\n const system = createQuerySystem(config) as T;\n\n if (typeof window !== \"undefined\" && !system.isRunning) {\n system.start();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n return system;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["createDerivedStore","system","derivationId","readable","set","createDerivedsStore","derivationIds","getValues","result","id","createFactStore","factKey","createInspectStore","update","unsubFacts","unsubSettled","useFact","keyOrKeys","assertSystem","_useFactMulti","factKeys","key","useDerived","idOrIds","useSelector","selector","equalityFn","defaultEquality","deriveKeySet","runWithTracking","runTrackedSelector","initial","currentSelected","trackedFactKeys","trackedDeriveKeys","unsubs","resubscribe","unsub","onUpdate","depsChanged","useDispatch","event","useEvents","useWatch","callback","unsubscribe","onDestroy","useInspect","options","computeInspectState","throttled","cleanup","createThrottle","useRequirementStatus","statusPlugin","typeOrTypes","type","useExplain","requirementId","useConstraintStatus","constraintId","_getConstraintValue","inspection","c","useOptimisticUpdate","requirementType","isPendingValue","errorValue","snapshot","statusUnsub","pendingSubscribers","errorSubscribers","isPending","fn","error","setPending","v","setError","rollback","mutate","updateFn","status","useHistory","buildHistoryState","useDirective","moduleDef","config","allPlugins","sp","createRequirementStatusPlugin","createSystem","derivedKeys","subscribeAll","factsStore","pickFacts","allDerivationKeys","getDerived","derivedStore","events","createTypedHooks","useNamespacedSelector","keys","_createQuerySystem","getCreateQuerySystem","useQuerySystem","HYDRATION_KEY","setHydrationSnapshot","setContext","useHydratedSystem","getContext","mergedFacts","mergeHydrationFacts"],"mappings":"iaA4BA,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAA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Q,YAAuC,CAAA,CAEjG,OAAOF,CAAAA,CAAaC,CAAAA,CAAW,CAAE,GAAGC,CAAAA,CAAQ,aAAcwB,CAAY,CAAC,EAAE,MAC3E","file":"index.js","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n ErrorBoundaryConfig,\n HistoryState,\n InferDerivations,\n InferEvents,\n InferFacts,\n InferSelectorState,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n Plugin,\n SingleModuleSystem,\n SystemInspection,\n SystemSnapshot,\n TraceOption,\n} from \"@directive-run/core\";\nimport {\n createRequirementStatusPlugin,\n createSystem,\n} from \"@directive-run/core\";\nimport type { RequirementTypeStatus } from \"@directive-run/core\";\nimport {\n type ConstraintInfo,\n type InspectState,\n assertSystem,\n buildHistoryState,\n computeInspectState,\n createThrottle,\n defaultEquality,\n depsChanged,\n pickFacts,\n runTrackedSelector,\n mergeHydrationFacts,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { getContext, onDestroy, setContext } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\n\n// Re-export for convenience\nexport type { RequirementTypeStatus, InspectState, ConstraintInfo };\nexport { shallowEqual };\n\n/** Type for the requirement status plugin return value */\nexport type StatusPlugin = ReturnType<typeof createRequirementStatusPlugin>;\n\n// ============================================================================\n// Store Factories\n// ============================================================================\n\n/**\n * Create a Svelte store for a derived value.\n */\nexport function createDerivedStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationId: string,\n): Readable<T> {\n if (process.env.NODE_ENV !== \"production\") {\n const initialValue = system.read(derivationId);\n if (initialValue === undefined) {\n console.warn(\n `[Directive] createDerivedStore(\"${derivationId}\") returned undefined. ` +\n `Check that \"${derivationId}\" is defined in your module's derive property.`,\n );\n }\n }\n\n return readable<T>(system.read(derivationId) as T, (set) => {\n const unsubscribe = system.subscribe([derivationId], () => {\n set(system.read(derivationId) as T);\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for multiple derived values.\n */\nexport function createDerivedsStore<T extends Record<string, unknown>>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n derivationIds: string[],\n): Readable<T> {\n const getValues = (): T => {\n const result: Record<string, unknown> = {};\n for (const id of derivationIds) {\n result[id] = system.read(id);\n }\n return result as T;\n };\n\n return readable<T>(getValues(), (set) => {\n const unsubscribe = system.subscribe(derivationIds, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n/**\n * Create a Svelte store for a single fact value.\n */\nexport function createFactStore<T>(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n factKey: string,\n): Readable<T | undefined> {\n if (process.env.NODE_ENV !== \"production\") {\n if (!system.facts.$store.has(factKey)) {\n console.warn(\n `[Directive] createFactStore(\"${factKey}\") — fact not found in store. ` +\n `Check that \"${factKey}\" is defined in your module's schema.`,\n );\n }\n }\n\n return readable<T | undefined>(\n system.facts.$store.get(factKey) as T | undefined,\n (set) => {\n const unsubscribe = system.facts.$store.subscribe([factKey], () => {\n set(system.facts.$store.get(factKey) as T | undefined);\n });\n return unsubscribe;\n },\n );\n}\n\n/**\n * Create a Svelte store for system inspection data.\n * NOTE: This updates on every fact change. Use sparingly in production.\n */\nexport function createInspectStore(\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: SingleModuleSystem<any>,\n): Readable<SystemInspection> {\n return readable<SystemInspection>(system.inspect(), (set) => {\n const update = () => set(system.inspect());\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useFact — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKey: K,\n): Readable<InferFacts<S>[K] | undefined>;\n/** Multi-key overload */\nexport function useFact<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n factKeys: K[],\n): Readable<Pick<InferFacts<S>, K>>;\n/** Implementation */\nexport function useFact(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n keyOrKeys: string | string[],\n): Readable<unknown> {\n assertSystem(\"useFact\", system);\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof keyOrKeys === \"function\"\n ) {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _useFactMulti(system, keyOrKeys);\n }\n\n // Single key path: useFact(system, key)\n return createFactStore(system, keyOrKeys);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Internal\nfunction _useFactMulti(\n system: SingleModuleSystem<any>,\n factKeys: string[],\n): Readable<Record<string, unknown>> {\n const getValues = (): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const key of factKeys) {\n result[key] = system.facts.$store.get(key);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = system.facts.$store.subscribe(factKeys, () => {\n set(getValues());\n });\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useDerived — single key or multi key\n// ============================================================================\n\n/** Single key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationId: K,\n): Readable<InferDerivations<S>[K]>;\n/** Multi-key overload */\nexport function useDerived<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n derivationIds: K[],\n): Readable<Pick<InferDerivations<S>, K>>;\n/** Implementation */\nexport function useDerived(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n idOrIds: string | string[],\n): Readable<unknown> {\n assertSystem(\"useDerived\", system);\n if (process.env.NODE_ENV !== \"production\" && typeof idOrIds === \"function\") {\n console.error(\n \"[Directive] useDerived() received a function. Did you mean useSelector()? \" +\n \"useDerived() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path\n if (Array.isArray(idOrIds)) {\n return createDerivedsStore(system, idOrIds);\n }\n\n // Single key path\n return createDerivedStore(system, idOrIds);\n}\n\n// ============================================================================\n// useSelector — auto-tracking selector over facts and derivations\n// ============================================================================\n\n/**\n * Auto-tracking selector over facts and derivations.\n * Uses `withTracking()` to detect which facts the selector accesses,\n * then subscribes only to those keys.\n */\nexport function useSelector<S extends ModuleSchema, R>(\n system: SingleModuleSystem<S>,\n selector: (state: InferSelectorState<S>) => R,\n equalityFn?: (a: R, b: R) => boolean,\n): Readable<R>;\nexport function useSelector(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n selector: (state: any) => unknown,\n equalityFn: (a: unknown, b: unknown) => boolean = defaultEquality,\n): Readable<unknown> {\n assertSystem(\"useSelector\", system);\n const deriveKeySet = new Set(Object.keys(system.derive ?? {}));\n\n // Build a tracking-aware state proxy that exposes both facts and derivations\n const runWithTracking = () =>\n runTrackedSelector(system, deriveKeySet, selector);\n\n const initial = runWithTracking();\n\n return readable(initial.value, (set) => {\n let currentSelected = initial.value;\n let trackedFactKeys = initial.factKeys;\n let trackedDeriveKeys = initial.deriveKeys;\n const unsubs: Array<() => void> = [];\n\n const resubscribe = () => {\n for (const unsub of unsubs) unsub();\n unsubs.length = 0;\n\n const onUpdate = () => {\n const result = runWithTracking();\n if (!equalityFn(currentSelected, result.value)) {\n currentSelected = result.value;\n set(result.value);\n }\n // Re-track: check if deps changed\n if (\n depsChanged(\n trackedFactKeys,\n result.factKeys,\n trackedDeriveKeys,\n result.deriveKeys,\n )\n ) {\n trackedFactKeys = result.factKeys;\n trackedDeriveKeys = result.deriveKeys;\n resubscribe();\n }\n };\n\n if (trackedFactKeys.length > 0) {\n unsubs.push(system.facts.$store.subscribe(trackedFactKeys, onUpdate));\n } else if (trackedDeriveKeys.length === 0) {\n unsubs.push(system.facts.$store.subscribeAll(onUpdate));\n }\n if (trackedDeriveKeys.length > 0) {\n unsubs.push(system.subscribe(trackedDeriveKeys, onUpdate));\n }\n };\n\n resubscribe();\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n });\n}\n\n// ============================================================================\n// useDispatch\n// ============================================================================\n\nexport function useDispatch<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): (event: InferEvents<S>) => void {\n assertSystem(\"useDispatch\", system);\n return (event: InferEvents<S>) => {\n system.dispatch(event);\n };\n}\n\n// ============================================================================\n// useEvents — memoized events reference\n// ============================================================================\n\n/**\n * Returns the system's events dispatcher.\n */\nexport function useEvents<S extends ModuleSchema>(\n system: SingleModuleSystem<S>,\n): SingleModuleSystem<S>[\"events\"] {\n assertSystem(\"useEvents\", system);\n return system.events;\n}\n\n// ============================================================================\n// useWatch — derivation or fact side-effect\n// ============================================================================\n\n/** Watch a derivation or fact by key (auto-detected). When a key exists in both facts and derivations, the derivation overload takes priority. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferDerivations<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferDerivations<S>[K],\n previousValue: InferDerivations<S>[K] | undefined,\n ) => void,\n): void;\n/** Watch a fact key with auto-detection. */\nexport function useWatch<\n S extends ModuleSchema,\n K extends keyof InferFacts<S> & string,\n>(\n system: SingleModuleSystem<S>,\n key: K,\n callback: (\n newValue: InferFacts<S>[K] | undefined,\n previousValue: InferFacts<S>[K] | undefined,\n ) => void,\n): void;\n/** Implementation */\nexport function useWatch(\n // biome-ignore lint/suspicious/noExplicitAny: Implementation signature\n system: SingleModuleSystem<any>,\n key: string,\n callback: (newValue: unknown, prevValue: unknown) => void,\n): void {\n assertSystem(\"useWatch\", system);\n\n const unsubscribe = system.watch(key, callback);\n onDestroy(unsubscribe);\n}\n\n// ============================================================================\n// useInspect — consolidated inspection hook\n// ============================================================================\n\n/** Options for useInspect */\nexport interface UseInspectOptions {\n throttleMs?: number;\n}\n\n/**\n * Consolidated system inspection hook.\n * Returns Readable<InspectState> with optional throttling.\n */\nexport function useInspect(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n options?: UseInspectOptions,\n): Readable<InspectState> {\n assertSystem(\"useInspect\", system);\n if (options?.throttleMs && options.throttleMs > 0) {\n return readable<InspectState>(computeInspectState(system), (set) => {\n const { throttled, cleanup } = createThrottle(() => {\n set(computeInspectState(system));\n }, options.throttleMs!);\n\n const unsubFacts = system.facts.$store.subscribeAll(throttled);\n const unsubSettled = system.onSettledChange(throttled);\n\n return () => {\n cleanup();\n unsubFacts();\n unsubSettled();\n };\n });\n }\n\n return readable<InspectState>(computeInspectState(system), (set) => {\n const update = () => set(computeInspectState(system));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useRequirementStatus — single or multi\n// ============================================================================\n\n/** Single type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n type: string,\n): Readable<RequirementTypeStatus>;\n/** Multi-type overload */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n types: string[],\n): Readable<Record<string, RequirementTypeStatus>>;\n/** Implementation */\nexport function useRequirementStatus(\n statusPlugin: StatusPlugin,\n typeOrTypes: string | string[],\n):\n | Readable<RequirementTypeStatus>\n | Readable<Record<string, RequirementTypeStatus>> {\n if (Array.isArray(typeOrTypes)) {\n const getValues = (): Record<string, RequirementTypeStatus> => {\n const result: Record<string, RequirementTypeStatus> = {};\n for (const type of typeOrTypes) {\n result[type] = statusPlugin.getStatus(type);\n }\n return result;\n };\n\n return readable(getValues(), (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(getValues());\n });\n return unsubscribe;\n });\n }\n\n return readable<RequirementTypeStatus>(\n statusPlugin.getStatus(typeOrTypes),\n (set) => {\n const unsubscribe = statusPlugin.subscribe(() => {\n set(statusPlugin.getStatus(typeOrTypes));\n });\n return unsubscribe;\n },\n );\n}\n\n// ============================================================================\n// useExplain — reactive requirement explanation\n// ============================================================================\n\n/**\n * Reactively returns the explanation string for a requirement.\n */\nexport function useExplain(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n requirementId: string,\n): Readable<string | null> {\n assertSystem(\"useExplain\", system);\n return readable<string | null>(system.explain(requirementId), (set) => {\n const update = () => set(system.explain(requirementId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n });\n}\n\n// ============================================================================\n// useConstraintStatus — reactive constraint inspection\n// ============================================================================\n\n/** Get all constraints */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n): Readable<ConstraintInfo[]>;\n/** Get a single constraint by ID */\nexport function useConstraintStatus(\n system: SingleModuleSystem<any>,\n constraintId: string,\n): Readable<ConstraintInfo | null>;\n/** Implementation */\nexport function useConstraintStatus(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): Readable<ConstraintInfo[] | ConstraintInfo | null> {\n assertSystem(\"useConstraintStatus\", system);\n return readable<ConstraintInfo[] | ConstraintInfo | null>(\n _getConstraintValue(system, constraintId),\n (set) => {\n const update = () => set(_getConstraintValue(system, constraintId));\n const unsubFacts = system.facts.$store.subscribeAll(update);\n const unsubSettled = system.onSettledChange(update);\n\n return () => {\n unsubFacts();\n unsubSettled();\n };\n },\n );\n}\n\nfunction _getConstraintValue(\n // biome-ignore lint/suspicious/noExplicitAny: Internal\n system: SingleModuleSystem<any>,\n constraintId?: string,\n): ConstraintInfo[] | ConstraintInfo | null {\n const inspection = system.inspect();\n if (!constraintId) return inspection.constraints;\n return (\n inspection.constraints.find((c: ConstraintInfo) => c.id === constraintId) ??\n null\n );\n}\n\n// ============================================================================\n// useOptimisticUpdate — batch with rollback on failure\n// ============================================================================\n\nexport interface OptimisticUpdateResult {\n mutate: (updateFn: () => void) => void;\n isPending: Readable<boolean>;\n error: Readable<Error | null>;\n rollback: () => void;\n}\n\n/**\n * Optimistic update hook. Saves a snapshot before mutating, monitors\n * a requirement type via statusPlugin, and rolls back on failure.\n */\nexport function useOptimisticUpdate(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n statusPlugin?: StatusPlugin,\n requirementType?: string,\n): OptimisticUpdateResult {\n assertSystem(\"useOptimisticUpdate\", system);\n let isPendingValue = false;\n let errorValue: Error | null = null;\n let snapshot: SystemSnapshot | null = null;\n let statusUnsub: (() => void) | null = null;\n\n // We track subscribers manually since we need imperative push\n const pendingSubscribers = new Set<(v: boolean) => void>();\n const errorSubscribers = new Set<(v: Error | null) => void>();\n\n const isPending: Readable<boolean> = {\n subscribe(fn) {\n fn(isPendingValue);\n pendingSubscribers.add(fn);\n return () => pendingSubscribers.delete(fn);\n },\n };\n\n const error: Readable<Error | null> = {\n subscribe(fn) {\n fn(errorValue);\n errorSubscribers.add(fn);\n return () => errorSubscribers.delete(fn);\n },\n };\n\n const setPending = (v: boolean) => {\n isPendingValue = v;\n for (const fn of pendingSubscribers) fn(v);\n };\n\n const setError = (v: Error | null) => {\n errorValue = v;\n for (const fn of errorSubscribers) fn(v);\n };\n\n const rollback = () => {\n if (snapshot) {\n system.restore(snapshot);\n snapshot = null;\n }\n setPending(false);\n setError(null);\n statusUnsub?.();\n statusUnsub = null;\n };\n\n const mutate = (updateFn: () => void) => {\n snapshot = system.getSnapshot();\n setPending(true);\n setError(null);\n system.batch(updateFn);\n\n if (statusPlugin && requirementType) {\n statusUnsub?.();\n statusUnsub = statusPlugin.subscribe(() => {\n const status = statusPlugin.getStatus(requirementType);\n if (!status.isLoading && !status.hasError) {\n snapshot = null;\n setPending(false);\n statusUnsub?.();\n statusUnsub = null;\n } else if (status.hasError) {\n setError(status.lastError);\n rollback();\n }\n });\n }\n };\n\n onDestroy(() => {\n statusUnsub?.();\n });\n\n return { mutate, isPending, error, rollback };\n}\n\n// ============================================================================\n// useHistory — reactive history store\n// ============================================================================\n\n/**\n * Reactive history Svelte store. Returns a Readable that updates\n * when snapshots are taken or navigation occurs.\n *\n * @example\n * ```svelte\n * const history = useHistory(system);\n * <button disabled={!$history?.canGoBack} on:click={() => $history?.goBack()}>Undo</button>\n * ```\n */\nexport function useHistory(\n // biome-ignore lint/suspicious/noExplicitAny: Must work with any schema\n system: SingleModuleSystem<any>,\n): Readable<HistoryState | null> {\n assertSystem(\"useHistory\", system);\n return readable<HistoryState | null>(buildHistoryState(system), (set) => {\n return system.onHistoryChange(() => set(buildHistoryState(system)));\n });\n}\n\n// ============================================================================\n// Scoped System\n// ============================================================================\n\n/** Configuration for useDirective */\nexport interface UseDirectiveConfig {\n // biome-ignore lint/suspicious/noExplicitAny: Plugin types vary\n plugins?: Plugin<any>[];\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n tickMs?: number;\n zeroConfig?: boolean;\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n initialFacts?: Record<string, any>;\n status?: boolean;\n /** Fact keys to subscribe to (omit for all) */\n facts?: string[];\n /** Derivation keys to subscribe to (omit for all) */\n derived?: string[];\n}\n\n/**\n * Create a scoped Directive system with automatic lifecycle management.\n * When no `facts` or `derived` keys are specified, subscribes to ALL\n * facts and derivations and returns Svelte readable stores.\n *\n * @example\n * ```svelte\n * // Subscribe to everything\n * const { facts, derived, events, dispatch } = useDirective(counterModule);\n *\n * // Selective keys\n * const { facts, derived } = useDirective(counterModule, { facts: [\"count\"], derived: [\"doubled\"] });\n * ```\n */\nexport function useDirective<M extends ModuleSchema>(\n moduleDef: ModuleDef<M>,\n config?: UseDirectiveConfig,\n): {\n system: SingleModuleSystem<M>;\n facts: Readable<InferFacts<M>>;\n derived: Readable<InferDerivations<M>>;\n events: SingleModuleSystem<M>[\"events\"];\n dispatch: (event: InferEvents<M>) => void;\n statusPlugin: StatusPlugin | undefined;\n} {\n const allPlugins = [...(config?.plugins ?? [])];\n let statusPlugin: StatusPlugin | undefined;\n\n if (config?.status) {\n const sp = createRequirementStatusPlugin();\n statusPlugin = sp;\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic issues\n allPlugins.push(sp.plugin as Plugin<any>);\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: moduleDef,\n plugins: allPlugins.length > 0 ? allPlugins : undefined,\n trace: config?.trace,\n errorBoundary: config?.errorBoundary,\n tickMs: config?.tickMs,\n zeroConfig: config?.zeroConfig,\n initialFacts: config?.initialFacts,\n } as any) as unknown as SingleModuleSystem<M>;\n\n // SSR guard: initialize facts for SSR rendering, start reconciliation only in the browser\n if (typeof window !== \"undefined\") {\n system.start();\n } else {\n system.initialize();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n const factKeys = config?.facts;\n const derivedKeys = config?.derived;\n const subscribeAll = !factKeys && !derivedKeys;\n\n // Subscribe to facts\n const factsStore: Readable<InferFacts<M>> = subscribeAll\n ? readable(system.facts.$store.toObject() as InferFacts<M>, (set) => {\n return system.facts.$store.subscribeAll(() => {\n set(system.facts.$store.toObject() as InferFacts<M>);\n });\n })\n : readable(pickFacts(system, factKeys ?? []) as InferFacts<M>, (set) => {\n if (!factKeys || factKeys.length === 0) return () => {};\n return system.facts.$store.subscribe(factKeys, () => {\n set(pickFacts(system, factKeys) as InferFacts<M>);\n });\n });\n\n // Subscribe to derivations\n const allDerivationKeys = subscribeAll\n ? Object.keys(system.derive ?? {})\n : (derivedKeys ?? []);\n const getDerived = (): InferDerivations<M> => {\n const result: Record<string, unknown> = {};\n for (const key of allDerivationKeys) {\n result[key] = system.read(key);\n }\n return result as InferDerivations<M>;\n };\n const derivedStore: Readable<InferDerivations<M>> =\n allDerivationKeys.length > 0\n ? readable(getDerived(), (set) => {\n return system.subscribe(allDerivationKeys, () => {\n set(getDerived());\n });\n })\n : readable(getDerived(), () => () => {});\n\n const events = system.events;\n const dispatch = (event: InferEvents<M>) => system.dispatch(event);\n\n return {\n system,\n facts: factsStore,\n derived: derivedStore,\n events,\n dispatch,\n statusPlugin,\n };\n}\n\n// ============================================================================\n// Typed Hooks Factory\n// ============================================================================\n\nexport function createTypedHooks<M extends ModuleSchema>(): {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) => Readable<InferFacts<M>[K] | undefined>;\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) => Readable<InferDerivations<M>[K]>;\n useDispatch: (\n system: SingleModuleSystem<M>,\n ) => (event: InferEvents<M>) => void;\n useEvents: (system: SingleModuleSystem<M>) => SingleModuleSystem<M>[\"events\"];\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) => void;\n} {\n return {\n useFact: <K extends keyof InferFacts<M> & string>(\n system: SingleModuleSystem<M>,\n factKey: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useFact(system as SingleModuleSystem<any>, factKey) as Readable<\n InferFacts<M>[K] | undefined\n >,\n useDerived: <K extends keyof InferDerivations<M> & string>(\n system: SingleModuleSystem<M>,\n derivationId: K,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useDerived(system as SingleModuleSystem<any>, derivationId) as Readable<\n InferDerivations<M>[K]\n >,\n useDispatch: (system: SingleModuleSystem<M>) => {\n return (event: InferEvents<M>) => {\n system.dispatch(event);\n };\n },\n useEvents: (system: SingleModuleSystem<M>) => useEvents<M>(system),\n useWatch: <K extends string>(\n system: SingleModuleSystem<M>,\n key: K,\n callback: (newValue: unknown, previousValue: unknown) => void,\n ) =>\n // biome-ignore lint/suspicious/noExplicitAny: Cast for overload compatibility\n useWatch(system as SingleModuleSystem<any>, key, callback),\n };\n}\n\n// ============================================================================\n// useNamespacedSelector — select from a NamespacedSystem\n// ============================================================================\n\n/**\n * Svelte readable store that selects from a NamespacedSystem.\n * Subscribes to specified keys and provides reactive updates.\n *\n * @param system - The namespaced system\n * @param keys - Namespaced keys to subscribe to (e.g., [\"auth.token\", \"data.count\"])\n * @param selector - Function that reads from system.facts / system.derive\n *\n * @example\n * ```svelte\n * const token$ = useNamespacedSelector(system, [\"auth.token\"], (s) => s.facts.auth.token);\n * ```\n */\nexport function useNamespacedSelector<Modules extends ModulesMap, R>(\n system: NamespacedSystem<Modules>,\n keys: string[],\n selector: (system: NamespacedSystem<Modules>) => R,\n): Readable<R> {\n return readable<R>(selector(system), (set) => {\n const unsubscribe = system.subscribe(keys, () => {\n set(selector(system));\n });\n\n return unsubscribe;\n });\n}\n\n// ============================================================================\n// useQuerySystem — Stable query system with lifecycle management\n// ============================================================================\n\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nlet _createQuerySystem: ((config: Record<string, unknown>) => any) | null =\n null;\n\nfunction getCreateQuerySystem() {\n if (!_createQuerySystem) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@directive-run/query\");\n _createQuerySystem = mod.createQuerySystem;\n } catch {\n throw new Error(\n \"[Directive] @directive-run/query is not installed. \" +\n \"Install it with: pnpm add @directive-run/query\",\n );\n }\n }\n\n return _createQuerySystem!;\n}\n\n/**\n * Svelte composable to create and manage a query system with proper lifecycle.\n *\n * Accepts a config object or a factory function that creates the system.\n * Handles cleanup on component destroy.\n *\n * @example\n * ```svelte\n * <script>\n * import { useQuerySystem, useDerived } from \"@directive-run/svelte\";\n *\n * const app = useQuerySystem({\n * facts: { userId: \"\" },\n * queries: { user: { key: ..., fetcher: ... } },\n * });\n *\n * const user = useDerived(app, \"user\");\n * </script>\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Factory return type varies\nexport function useQuerySystem<\n T extends {\n start: () => void;\n destroy: () => void;\n isRunning?: boolean;\n [key: string]: any;\n },\n>(config: Record<string, unknown>): T {\n const createQuerySystem = getCreateQuerySystem();\n const system = createQuerySystem(config) as T;\n\n if (typeof window !== \"undefined\" && !system.isRunning) {\n system.start();\n }\n\n onDestroy(() => {\n system.destroy();\n });\n\n return system;\n}\n\n// ============================================================================\n// SSR Hydration\n// ============================================================================\n\n/** @internal Context key for SSR hydration snapshot */\nconst HYDRATION_KEY = Symbol(\"directive-hydration\");\n\n/**\n * Provide a DistributableSnapshot for child components to hydrate from.\n * Call this in your layout or parent component (e.g., SvelteKit +layout.svelte).\n *\n * @example\n * ```svelte\n * <script>\n * import { setHydrationSnapshot } from \"@directive-run/svelte\";\n * export let data; // from SvelteKit load()\n * setHydrationSnapshot(data.snapshot);\n * </script>\n * <slot />\n * ```\n */\nexport function setHydrationSnapshot(snapshot: Record<string, unknown>): void {\n setContext(HYDRATION_KEY, snapshot);\n}\n\n/**\n * Create a system hydrated from a server snapshot.\n * Must be called in a component that is a descendant of one that called `setHydrationSnapshot`.\n *\n * @example\n * ```svelte\n * <script>\n * import { useHydratedSystem, useDerived } from \"@directive-run/svelte\";\n * const system = useHydratedSystem(myModule);\n * const count = useDerived(system, \"count\");\n * </script>\n * ```\n */\nexport function useHydratedSystem<S extends ModuleSchema>(\n moduleDef: ModuleDef<S>,\n config?: UseDirectiveConfig,\n): SingleModuleSystem<S> {\n const snapshot = getContext<Record<string, unknown> | undefined>(HYDRATION_KEY);\n const mergedFacts = mergeHydrationFacts(snapshot, config?.initialFacts as Record<string, unknown>);\n\n return useDirective(moduleDef, { ...config, initialFacts: mergedFacts }).system;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@directive-run/svelte",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.7",
|
|
4
4
|
"description": "Svelte stores adapter for Directive.",
|
|
5
5
|
"license": "(MIT OR Apache-2.0)",
|
|
6
6
|
"author": "Jason Comes",
|
|
@@ -54,12 +54,12 @@
|
|
|
54
54
|
}
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
|
-
"@directive-run/query": "^0.1.2",
|
|
58
57
|
"@types/node": "^25.2.0",
|
|
59
58
|
"svelte": "^5.54.0",
|
|
60
59
|
"tsup": "^8.3.5",
|
|
61
60
|
"typescript": "^5.7.2",
|
|
62
|
-
"@directive-run/core": "0.8.
|
|
61
|
+
"@directive-run/core": "0.8.7",
|
|
62
|
+
"@directive-run/query": "0.1.3"
|
|
63
63
|
},
|
|
64
64
|
"scripts": {
|
|
65
65
|
"build": "tsup",
|