@directive-run/svelte 1.10.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -2
- package/dist/index.d.ts +25 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
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 F=(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')});var v=typeof process<"u"&&process.env?.NODE_ENV!=="production";function
|
|
1
|
+
'use strict';var core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils'),svelte=require('svelte'),store=require('svelte/store');var F=(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')});var v=typeof process<"u"&&process.env?.NODE_ENV!=="production";function P(e,t){return v&&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 H(e,t){let n=()=>{let r={};for(let s of t)r[s]=e.read(s);return r};return store.readable(n(),r=>e.subscribe(t,()=>{r(n());}))}function U(e,t){return v&&(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 te(e){return store.readable(e.inspect(),t=>{let n=()=>t(e.inspect()),r=e.facts.$store.subscribeAll(n),s=e.onSettledChange(n);return ()=>{r(),s();}})}function Q(e,t){return adapterUtils.assertSystem("useFact",e),v&&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)?N(e,t):U(e,t)}function N(e,t){let n=()=>{let r={};for(let s of t)r[s]=e.facts.$store.get(s);return r};return store.readable(n(),r=>e.facts.$store.subscribe(t,()=>{r(n());}))}function W(e,t){return adapterUtils.assertSystem("useDerived",e),v&&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)?H(e,t):P(e,t)}function ne(e,t,n=adapterUtils.defaultEquality){adapterUtils.assertSystem("useSelector",e);let r=new Set(Object.keys(e.derive??{})),s=()=>adapterUtils.runTrackedSelector(e,r,t),o=s();return store.readable(o.value,l=>{let b=o.value,p=o.factKeys,S=o.deriveKeys,d=[],g=()=>{for(let c of d)c();d.length=0;let f=()=>{let c=s();n(b,c.value)||(b=c.value,l(c.value)),adapterUtils.depsChanged(p,c.factKeys,S,c.deriveKeys)&&(p=c.factKeys,S=c.deriveKeys,g());};p.length>0?d.push(e.facts.$store.subscribe(p,f)):S.length===0&&d.push(e.facts.$store.subscribeAll(f)),S.length>0&&d.push(e.subscribe(S,f));};return g(),()=>{for(let f of d)f();}})}function re(e){return adapterUtils.assertSystem("useDispatch",e),t=>{e.dispatch(t);}}function B(e){return adapterUtils.assertSystem("useEvents",e),e.events}function O(e,t,n){adapterUtils.assertSystem("useWatch",e);let r=e.watch(t,n);svelte.onDestroy(r);}function se(e,t){return adapterUtils.assertSystem("useInspect",e),t?.throttleMs&&t.throttleMs>0?store.readable(adapterUtils.computeInspectState(e),n=>{let{throttled:r,cleanup:s}=adapterUtils.createThrottle(()=>{n(adapterUtils.computeInspectState(e));},t.throttleMs),o=e.facts.$store.subscribeAll(r),l=e.onSettledChange(r);return ()=>{s(),o(),l();}}):store.readable(adapterUtils.computeInspectState(e),n=>{let r=()=>n(adapterUtils.computeInspectState(e)),s=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{s(),o();}})}function oe(e,t){if(Array.isArray(t)){let n=()=>{let r={};for(let s of t)r[s]=e.getStatus(s);return r};return store.readable(n(),r=>e.subscribe(()=>{r(n());}))}return store.readable(e.getStatus(t),n=>e.subscribe(()=>{n(e.getStatus(t));}))}function ue(e,t){return adapterUtils.assertSystem("useExplain",e),store.readable(e.explain(t),n=>{let r=()=>n(e.explain(t)),s=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{s(),o();}})}function ie(e,t){return adapterUtils.assertSystem("useConstraintStatus",e),store.readable(k(e,t),n=>{let r=()=>n(k(e,t)),s=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{s(),o();}})}function k(e,t){let n=e.inspect();return t?n.constraints.find(r=>r.id===t)??null:n.constraints}function ae(e,t,n){adapterUtils.assertSystem("useOptimisticUpdate",e);let r=false,s=null,o=null,l=null,b=new Set,p=new Set,S={subscribe(i){return i(r),b.add(i),()=>b.delete(i)}},d={subscribe(i){return i(s),p.add(i),()=>p.delete(i)}},g=i=>{r=i;for(let M of b)M(i);},f=i=>{s=i;for(let M of p)M(i);},c=()=>{o&&(e.restore(o),o=null),g(false),f(null),l?.(),l=null;},a=i=>{o=e.getSnapshot(),g(true),f(null),e.batch(i),t&&n&&(l?.(),l=t.subscribe(()=>{let M=t.getStatus(n);!M.isLoading&&!M.hasError?(o=null,g(false),l?.(),l=null):M.hasError&&(f(M.lastError),c());}));};return svelte.onDestroy(()=>{l?.();}),{mutate:a,isPending:S,error:d,rollback:c}}function le(e){return adapterUtils.assertSystem("useHistory",e),store.readable(adapterUtils.buildHistoryState(e),t=>e.onHistoryChange(()=>t(adapterUtils.buildHistoryState(e))))}function _(e,t){let n=[...t?.plugins??[]],r;if(t?.status){let a=core.createRequirementStatusPlugin();r=a,n.push(a.plugin);}let s=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"?s.start():s.initialize(),svelte.onDestroy(()=>{s.destroy();});let o=t?.facts,l=t?.derived,b=!o&&!l,p=b?store.readable(s.facts.$store.toObject(),a=>s.facts.$store.subscribeAll(()=>{a(s.facts.$store.toObject());})):store.readable(adapterUtils.pickFacts(s,o??[]),a=>!o||o.length===0?()=>{}:s.facts.$store.subscribe(o,()=>{a(adapterUtils.pickFacts(s,o));})),S=b?Object.keys(s.derive??{}):l??[],d=()=>{let a={};for(let i of S)a[i]=s.read(i);return a},g=S.length>0?store.readable(d(),a=>s.subscribe(S,()=>{a(d());})):store.readable(d(),()=>()=>{}),f=s.events;return {system:s,facts:p,derived:g,events:f,dispatch:a=>s.dispatch(a),statusPlugin:r}}function ce(){return {useFact:(e,t)=>Q(e,t),useDerived:(e,t)=>W(e,t),useDispatch:e=>t=>{e.dispatch(t);},useEvents:e=>B(e),useWatch:(e,t,n)=>O(e,t,n)}}function de(e,t,n){return store.readable(n(e),r=>e.subscribe(t,()=>{r(n(e));}))}var h=null;function j(){if(!h)try{h=F("@directive-run/query").createQuerySystem;}catch{throw new Error("[Directive] @directive-run/query is not installed. Install it with: pnpm add @directive-run/query")}return h}function Se(e){let n=j()(e);return typeof window<"u"&&!n.isRunning&&n.start(),svelte.onDestroy(()=>{n.destroy();}),n}var D=Symbol("directive-hydration");function fe(e){svelte.setContext(D,e);}function ye(e,t){let n=svelte.getContext(D),r=adapterUtils.mergeHydrationFacts(n,t?.initialFacts);return _(e,{...t,initialFacts:r}).system}function pe(e,t={},n={}){let r=n.pollMs??250;return store.readable(e.query(t),s=>{let o=setInterval(()=>s(e.query(t)),r);return ()=>clearInterval(o)})}Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return adapterUtils.shallowEqual}});exports.createAuditLedgerStore=pe;exports.createDerivedStore=P;exports.createDerivedsStore=H;exports.createFactStore=U;exports.createInspectStore=te;exports.createTypedHooks=ce;exports.setHydrationSnapshot=fe;exports.useConstraintStatus=ie;exports.useDerived=W;exports.useDirective=_;exports.useDispatch=re;exports.useEvents=B;exports.useExplain=ue;exports.useFact=Q;exports.useHistory=le;exports.useHydratedSystem=ye;exports.useInspect=se;exports.useNamespacedSelector=de;exports.useOptimisticUpdate=ae;exports.useQuerySystem=Se;exports.useRequirementStatus=oe;exports.useSelector=ne;exports.useWatch=O;//# 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","../src/dev-true.ts"],"names":["dev_true_default","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","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,IAAM,CACd7C,EAAO,OAAA,GACT,CAAC,CAAA,CAEMA,CACT,CAOA,IAAMwG,EAAgB,MAAA,CAAO,qBAAqB,EAgB3C,SAASC,EAAAA,CAAqBtC,EAAyC,CAC5EuC,iBAAAA,CAAWF,EAAerC,CAAQ,EACpC,CAeO,SAASwC,EAAAA,CACdvB,EACAC,CAAAA,CACuB,CACvB,IAAMlB,CAAAA,CAAWyC,kBACfJ,CACF,CAAA,CACMK,EAAcC,gCAAAA,CAClB3C,CAAAA,CACAkB,GAAQ,YACV,CAAA,CAEA,OAAOF,CAAAA,CAAaC,CAAAA,CAAW,CAAE,GAAGC,CAAAA,CAAQ,aAAcwB,CAAY,CAAC,EACpE,MACL","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 mergeHydrationFacts,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { getContext, onDestroy, setContext } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\nimport isDevelopment from \"#is-development\";\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 (isDevelopment) {\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 (isDevelopment) {\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 (isDevelopment && typeof keyOrKeys === \"function\") {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _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 (isDevelopment && 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>(\n HYDRATION_KEY,\n );\n const mergedFacts = mergeHydrationFacts(\n snapshot,\n config?.initialFacts as Record<string, unknown>,\n );\n\n return useDirective(moduleDef, { ...config, initialFacts: mergedFacts })\n .system;\n}\n","export default typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/dev-true.ts"],"names":["dev_true_default","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","mergedF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,CAOA,IAAMwG,CAAAA,CAAgB,OAAO,qBAAqB,CAAA,CAgB3C,SAASC,EAAAA,CAAqBtC,CAAAA,CAAyC,CAC5EuC,iBAAAA,CAAWF,CAAAA,CAAerC,CAAQ,EACpC,CAeO,SAASwC,EAAAA,CACdvB,CAAAA,CACAC,EACuB,CACvB,IAAMlB,EAAWyC,iBAAAA,CACfJ,CACF,EACMK,CAAAA,CAAcC,gCAAAA,CAClB3C,EACAkB,CAAAA,EAAQ,YACV,EAEA,OAAOF,CAAAA,CAAaC,EAAW,CAAE,GAAGC,EAAQ,YAAA,CAAcwB,CAAY,CAAC,CAAA,CACpE,MACL,CA+BO,SAASE,GACdC,CAAAA,CACAC,CAAAA,CAAsB,EAAC,CACvBC,CAAAA,CAA4B,EAAC,CACI,CACjC,IAAMC,CAAAA,CAASD,CAAAA,CAAK,QAAU,GAAA,CAC9B,OAAOhH,eAAgC8G,CAAAA,CAAO,KAAA,CAAMC,CAAM,CAAA,CAAI9G,CAAAA,EAAQ,CACpE,IAAMK,CAAAA,CAAK,YAAY,IAAML,CAAAA,CAAI6G,EAAO,KAAA,CAAMC,CAAM,CAAC,CAAA,CAAGE,CAAM,EAC9D,OAAO,IAAM,cAAc3G,CAAE,CAC/B,CAAC,CACH","file":"index.cjs","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n 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 mergeHydrationFacts,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { getContext, onDestroy, setContext } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\nimport isDevelopment from \"#is-development\";\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 (isDevelopment) {\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 (isDevelopment) {\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 (isDevelopment && typeof keyOrKeys === \"function\") {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _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 (isDevelopment && 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>(\n HYDRATION_KEY,\n );\n const mergedFacts = mergeHydrationFacts(\n snapshot,\n config?.initialFacts as Record<string, unknown>,\n );\n\n return useDirective(moduleDef, { ...config, initialFacts: mergedFacts })\n .system;\n}\n\n// ============================================================================\n// createAuditLedgerStore — live ledger entries with filter (R4.I parity)\n// ============================================================================\n\nimport type {\n AuditEntry,\n AuditLedger,\n QueryFilter,\n} from \"@directive-run/core\";\n\n/**\n * Create a Svelte readable store that holds the latest audit-ledger\n * entries matching `filter`. Re-emits on each poll tick (default\n * 250 ms — override with `pollMs`).\n *\n * @example\n * ```svelte\n * <script>\n * import { createAuditLedgerStore } from \"@directive-run/svelte\";\n * const entries = createAuditLedgerStore(ledger, { kind: \"constraint.evaluate\", limit: 20 });\n * </script>\n *\n * <ul>\n * {#each $entries as e (e.seq)}\n * <li>{e.kind} @ {new Date(e.ts).toISOString()}</li>\n * {/each}\n * </ul>\n * ```\n */\nexport function createAuditLedgerStore(\n ledger: AuditLedger,\n filter: QueryFilter = {},\n opts: { pollMs?: number } = {},\n): Readable<readonly AuditEntry[]> {\n const pollMs = opts.pollMs ?? 250;\n return readable<readonly AuditEntry[]>(ledger.query(filter), (set) => {\n const id = setInterval(() => set(ledger.query(filter)), pollMs);\n return () => clearInterval(id);\n });\n}\n","export default typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\";\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createRequirementStatusPlugin, Plugin, TraceOption, ErrorBoundaryConfig, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, HistoryState, ModulesMap, NamespacedSystem, RequirementTypeStatus, InferSelectorState } from '@directive-run/core';
|
|
1
|
+
import { createRequirementStatusPlugin, Plugin, TraceOption, ErrorBoundaryConfig, AuditLedger, QueryFilter, AuditEntry, 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';
|
|
@@ -213,4 +213,27 @@ declare function setHydrationSnapshot(snapshot: Record<string, unknown>): void;
|
|
|
213
213
|
*/
|
|
214
214
|
declare function useHydratedSystem<S extends ModuleSchema>(moduleDef: ModuleDef<S>, config?: UseDirectiveConfig): SingleModuleSystem<S>;
|
|
215
215
|
|
|
216
|
-
|
|
216
|
+
/**
|
|
217
|
+
* Create a Svelte readable store that holds the latest audit-ledger
|
|
218
|
+
* entries matching `filter`. Re-emits on each poll tick (default
|
|
219
|
+
* 250 ms — override with `pollMs`).
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```svelte
|
|
223
|
+
* <script>
|
|
224
|
+
* import { createAuditLedgerStore } from "@directive-run/svelte";
|
|
225
|
+
* const entries = createAuditLedgerStore(ledger, { kind: "constraint.evaluate", limit: 20 });
|
|
226
|
+
* </script>
|
|
227
|
+
*
|
|
228
|
+
* <ul>
|
|
229
|
+
* {#each $entries as e (e.seq)}
|
|
230
|
+
* <li>{e.kind} @ {new Date(e.ts).toISOString()}</li>
|
|
231
|
+
* {/each}
|
|
232
|
+
* </ul>
|
|
233
|
+
* ```
|
|
234
|
+
*/
|
|
235
|
+
declare function createAuditLedgerStore(ledger: AuditLedger, filter?: QueryFilter, opts?: {
|
|
236
|
+
pollMs?: number;
|
|
237
|
+
}): Readable<readonly AuditEntry[]>;
|
|
238
|
+
|
|
239
|
+
export { type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveConfig, type UseInspectOptions, createAuditLedgerStore, 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, Plugin, TraceOption, ErrorBoundaryConfig, SingleModuleSystem, SystemInspection, ModuleSchema, InferFacts, InferDerivations, InferEvents, ModuleDef, HistoryState, ModulesMap, NamespacedSystem, RequirementTypeStatus, InferSelectorState } from '@directive-run/core';
|
|
1
|
+
import { createRequirementStatusPlugin, Plugin, TraceOption, ErrorBoundaryConfig, AuditLedger, QueryFilter, AuditEntry, 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';
|
|
@@ -213,4 +213,27 @@ declare function setHydrationSnapshot(snapshot: Record<string, unknown>): void;
|
|
|
213
213
|
*/
|
|
214
214
|
declare function useHydratedSystem<S extends ModuleSchema>(moduleDef: ModuleDef<S>, config?: UseDirectiveConfig): SingleModuleSystem<S>;
|
|
215
215
|
|
|
216
|
-
|
|
216
|
+
/**
|
|
217
|
+
* Create a Svelte readable store that holds the latest audit-ledger
|
|
218
|
+
* entries matching `filter`. Re-emits on each poll tick (default
|
|
219
|
+
* 250 ms — override with `pollMs`).
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```svelte
|
|
223
|
+
* <script>
|
|
224
|
+
* import { createAuditLedgerStore } from "@directive-run/svelte";
|
|
225
|
+
* const entries = createAuditLedgerStore(ledger, { kind: "constraint.evaluate", limit: 20 });
|
|
226
|
+
* </script>
|
|
227
|
+
*
|
|
228
|
+
* <ul>
|
|
229
|
+
* {#each $entries as e (e.seq)}
|
|
230
|
+
* <li>{e.kind} @ {new Date(e.ts).toISOString()}</li>
|
|
231
|
+
* {/each}
|
|
232
|
+
* </ul>
|
|
233
|
+
* ```
|
|
234
|
+
*/
|
|
235
|
+
declare function createAuditLedgerStore(ledger: AuditLedger, filter?: QueryFilter, opts?: {
|
|
236
|
+
pollMs?: number;
|
|
237
|
+
}): Readable<readonly AuditEntry[]>;
|
|
238
|
+
|
|
239
|
+
export { type OptimisticUpdateResult, type StatusPlugin, type UseDirectiveConfig, type UseInspectOptions, createAuditLedgerStore, 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,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 F=(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')});var v=typeof process<"u"&&process.env?.NODE_ENV!=="production";function
|
|
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 F=(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')});var v=typeof process<"u"&&process.env?.NODE_ENV!=="production";function P(e,t){return v&&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 H(e,t){let n=()=>{let r={};for(let s of t)r[s]=e.read(s);return r};return readable(n(),r=>e.subscribe(t,()=>{r(n());}))}function U(e,t){return v&&(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 te(e){return readable(e.inspect(),t=>{let n=()=>t(e.inspect()),r=e.facts.$store.subscribeAll(n),s=e.onSettledChange(n);return ()=>{r(),s();}})}function Q(e,t){return assertSystem("useFact",e),v&&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)?N(e,t):U(e,t)}function N(e,t){let n=()=>{let r={};for(let s of t)r[s]=e.facts.$store.get(s);return r};return readable(n(),r=>e.facts.$store.subscribe(t,()=>{r(n());}))}function W(e,t){return assertSystem("useDerived",e),v&&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)?H(e,t):P(e,t)}function ne(e,t,n=defaultEquality){assertSystem("useSelector",e);let r=new Set(Object.keys(e.derive??{})),s=()=>runTrackedSelector(e,r,t),o=s();return readable(o.value,l=>{let b=o.value,p=o.factKeys,S=o.deriveKeys,d=[],g=()=>{for(let c of d)c();d.length=0;let f=()=>{let c=s();n(b,c.value)||(b=c.value,l(c.value)),depsChanged(p,c.factKeys,S,c.deriveKeys)&&(p=c.factKeys,S=c.deriveKeys,g());};p.length>0?d.push(e.facts.$store.subscribe(p,f)):S.length===0&&d.push(e.facts.$store.subscribeAll(f)),S.length>0&&d.push(e.subscribe(S,f));};return g(),()=>{for(let f of d)f();}})}function re(e){return assertSystem("useDispatch",e),t=>{e.dispatch(t);}}function B(e){return assertSystem("useEvents",e),e.events}function O(e,t,n){assertSystem("useWatch",e);let r=e.watch(t,n);onDestroy(r);}function se(e,t){return assertSystem("useInspect",e),t?.throttleMs&&t.throttleMs>0?readable(computeInspectState(e),n=>{let{throttled:r,cleanup:s}=createThrottle(()=>{n(computeInspectState(e));},t.throttleMs),o=e.facts.$store.subscribeAll(r),l=e.onSettledChange(r);return ()=>{s(),o(),l();}}):readable(computeInspectState(e),n=>{let r=()=>n(computeInspectState(e)),s=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{s(),o();}})}function oe(e,t){if(Array.isArray(t)){let n=()=>{let r={};for(let s of t)r[s]=e.getStatus(s);return r};return readable(n(),r=>e.subscribe(()=>{r(n());}))}return readable(e.getStatus(t),n=>e.subscribe(()=>{n(e.getStatus(t));}))}function ue(e,t){return assertSystem("useExplain",e),readable(e.explain(t),n=>{let r=()=>n(e.explain(t)),s=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{s(),o();}})}function ie(e,t){return assertSystem("useConstraintStatus",e),readable(k(e,t),n=>{let r=()=>n(k(e,t)),s=e.facts.$store.subscribeAll(r),o=e.onSettledChange(r);return ()=>{s(),o();}})}function k(e,t){let n=e.inspect();return t?n.constraints.find(r=>r.id===t)??null:n.constraints}function ae(e,t,n){assertSystem("useOptimisticUpdate",e);let r=false,s=null,o=null,l=null,b=new Set,p=new Set,S={subscribe(i){return i(r),b.add(i),()=>b.delete(i)}},d={subscribe(i){return i(s),p.add(i),()=>p.delete(i)}},g=i=>{r=i;for(let M of b)M(i);},f=i=>{s=i;for(let M of p)M(i);},c=()=>{o&&(e.restore(o),o=null),g(false),f(null),l?.(),l=null;},a=i=>{o=e.getSnapshot(),g(true),f(null),e.batch(i),t&&n&&(l?.(),l=t.subscribe(()=>{let M=t.getStatus(n);!M.isLoading&&!M.hasError?(o=null,g(false),l?.(),l=null):M.hasError&&(f(M.lastError),c());}));};return onDestroy(()=>{l?.();}),{mutate:a,isPending:S,error:d,rollback:c}}function le(e){return assertSystem("useHistory",e),readable(buildHistoryState(e),t=>e.onHistoryChange(()=>t(buildHistoryState(e))))}function _(e,t){let n=[...t?.plugins??[]],r;if(t?.status){let a=createRequirementStatusPlugin();r=a,n.push(a.plugin);}let s=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"?s.start():s.initialize(),onDestroy(()=>{s.destroy();});let o=t?.facts,l=t?.derived,b=!o&&!l,p=b?readable(s.facts.$store.toObject(),a=>s.facts.$store.subscribeAll(()=>{a(s.facts.$store.toObject());})):readable(pickFacts(s,o??[]),a=>!o||o.length===0?()=>{}:s.facts.$store.subscribe(o,()=>{a(pickFacts(s,o));})),S=b?Object.keys(s.derive??{}):l??[],d=()=>{let a={};for(let i of S)a[i]=s.read(i);return a},g=S.length>0?readable(d(),a=>s.subscribe(S,()=>{a(d());})):readable(d(),()=>()=>{}),f=s.events;return {system:s,facts:p,derived:g,events:f,dispatch:a=>s.dispatch(a),statusPlugin:r}}function ce(){return {useFact:(e,t)=>Q(e,t),useDerived:(e,t)=>W(e,t),useDispatch:e=>t=>{e.dispatch(t);},useEvents:e=>B(e),useWatch:(e,t,n)=>O(e,t,n)}}function de(e,t,n){return readable(n(e),r=>e.subscribe(t,()=>{r(n(e));}))}var h=null;function j(){if(!h)try{h=F("@directive-run/query").createQuerySystem;}catch{throw new Error("[Directive] @directive-run/query is not installed. Install it with: pnpm add @directive-run/query")}return h}function Se(e){let n=j()(e);return typeof window<"u"&&!n.isRunning&&n.start(),onDestroy(()=>{n.destroy();}),n}var D=Symbol("directive-hydration");function fe(e){setContext(D,e);}function ye(e,t){let n=getContext(D),r=mergeHydrationFacts(n,t?.initialFacts);return _(e,{...t,initialFacts:r}).system}function pe(e,t={},n={}){let r=n.pollMs??250;return readable(e.query(t),s=>{let o=setInterval(()=>s(e.query(t)),r);return ()=>clearInterval(o)})}export{pe as createAuditLedgerStore,P as createDerivedStore,H as createDerivedsStore,U as createFactStore,te as createInspectStore,ce as createTypedHooks,fe as setHydrationSnapshot,ie as useConstraintStatus,W as useDerived,_ as useDirective,re as useDispatch,B as useEvents,ue as useExplain,Q as useFact,le as useHistory,ye as useHydratedSystem,se as useInspect,de as useNamespacedSelector,ae as useOptimisticUpdate,Se as useQuerySystem,oe as useRequirementStatus,ne as useSelector,O 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","../src/dev-true.ts"],"names":["dev_true_default","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,EAAA,SAAA,CAAA,CAAA,CAAA,GAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,KAAA,CAAA,IAAA,CAAA,SAAA,CAAA,CAAA,MAAA,KAAA,CAAA,sBAAA,CAAA,CAAA,CA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AC7D,CACF,CAmBO,SAASwD,EAAAA,CACdnG,EACAoG,CAAAA,CACA5E,CAAAA,CACa,CACb,OAAOtB,QAAAA,CAAYsB,EAASxB,CAAM,CAAA,CAAIG,CAAAA,EAChBH,CAAAA,CAAO,UAAUoG,CAAAA,CAAM,IAAM,CAC/CjG,CAAAA,CAAIqB,CAAAA,CAASxB,CAAM,CAAC,EACtB,CAAC,CAGF,CACH,CAOA,IAAIqG,CAAAA,CACF,KAEF,SAASC,CAAAA,EAAuB,CAC9B,GAAI,CAACD,CAAAA,CACH,GAAI,CAGFA,CAAAA,CADY,CAAA,CAAQ,sBAAsB,CAAA,CACjB,kBAC3B,MAAQ,CACN,MAAM,IAAI,KAAA,CACR,mGAEF,CACF,CAGF,OAAOA,CACT,CAuBO,SAASE,EAAAA,CAOdlB,CAAAA,CAAoC,CAEpC,IAAMrF,EADoBsG,CAAAA,EAAqB,CACdjB,CAAM,CAAA,CAEvC,OAAI,OAAO,MAAA,CAAW,GAAA,EAAe,CAACrF,CAAAA,CAAO,SAAA,EAC3CA,EAAO,KAAA,EAAM,CAGf6C,UAAU,IAAM,CACd7C,EAAO,OAAA,GACT,CAAC,CAAA,CAEMA,CACT,CAOA,IAAMwG,EAAgB,MAAA,CAAO,qBAAqB,EAgB3C,SAASC,EAAAA,CAAqBtC,EAAyC,CAC5EuC,UAAAA,CAAWF,EAAerC,CAAQ,EACpC,CAeO,SAASwC,EAAAA,CACdvB,EACAC,CAAAA,CACuB,CACvB,IAAMlB,CAAAA,CAAWyC,WACfJ,CACF,CAAA,CACMK,EAAcC,mBAAAA,CAClB3C,CAAAA,CACAkB,GAAQ,YACV,CAAA,CAEA,OAAOF,CAAAA,CAAaC,CAAAA,CAAW,CAAE,GAAGC,CAAAA,CAAQ,aAAcwB,CAAY,CAAC,EACpE,MACL","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 mergeHydrationFacts,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { getContext, onDestroy, setContext } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\nimport isDevelopment from \"#is-development\";\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 (isDevelopment) {\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 (isDevelopment) {\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 (isDevelopment && typeof keyOrKeys === \"function\") {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _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 (isDevelopment && 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>(\n HYDRATION_KEY,\n );\n const mergedFacts = mergeHydrationFacts(\n snapshot,\n config?.initialFacts as Record<string, unknown>,\n );\n\n return useDirective(moduleDef, { ...config, initialFacts: mergedFacts })\n .system;\n}\n","export default typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/dev-true.ts"],"names":["dev_true_default","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","createAuditLedgerStore","ledger","filter","opts","pollMs"],"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,EAAA,SAAA,CAAA,CAAA,CAAA,GAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,KAAA,CAAA,IAAA,CAAA,SAAA,CAAA,CAAA,MAAA,KAAA,CAAA,sBAAA,CAAA,CAAA,CAAA,oBAAA,CAAA,CAAA,CAAA,CC5BA,I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AA,CAAMC,CAAM,CAAA,CAAI9G,CAAAA,EAAQ,CACpE,IAAMK,CAAAA,CAAK,YAAY,IAAML,CAAAA,CAAI6G,EAAO,KAAA,CAAMC,CAAM,CAAC,CAAA,CAAGE,CAAM,EAC9D,OAAO,IAAM,cAAc3G,CAAE,CAC/B,CAAC,CACH","file":"index.js","sourcesContent":["/**\n * Svelte Adapter - Consolidated Svelte stores for Directive\n *\n * 15 active exports: useFact, useDerived, useDispatch, useSelector,\n * useWatch, useInspect, useRequirementStatus, useEvents, useExplain,\n * useConstraintStatus, useOptimisticUpdate, useDirective, useHistory,\n * createTypedHooks, shallowEqual\n *\n * Store factories: createDerivedStore, createDerivedsStore, createFactStore, createInspectStore\n */\n\nimport type {\n 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 mergeHydrationFacts,\n pickFacts,\n runTrackedSelector,\n shallowEqual,\n} from \"@directive-run/core/adapter-utils\";\nimport { getContext, onDestroy, setContext } from \"svelte\";\nimport { type Readable, readable } from \"svelte/store\";\nimport isDevelopment from \"#is-development\";\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 (isDevelopment) {\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 (isDevelopment) {\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 (isDevelopment && typeof keyOrKeys === \"function\") {\n console.error(\n \"[Directive] useFact() received a function. Did you mean useSelector()? \" +\n \"useFact() takes a string key or array of keys, not a selector function.\",\n );\n }\n\n // Multi-key path: useFact(system, [keys])\n if (Array.isArray(keyOrKeys)) {\n return _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 (isDevelopment && 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>(\n HYDRATION_KEY,\n );\n const mergedFacts = mergeHydrationFacts(\n snapshot,\n config?.initialFacts as Record<string, unknown>,\n );\n\n return useDirective(moduleDef, { ...config, initialFacts: mergedFacts })\n .system;\n}\n\n// ============================================================================\n// createAuditLedgerStore — live ledger entries with filter (R4.I parity)\n// ============================================================================\n\nimport type {\n AuditEntry,\n AuditLedger,\n QueryFilter,\n} from \"@directive-run/core\";\n\n/**\n * Create a Svelte readable store that holds the latest audit-ledger\n * entries matching `filter`. Re-emits on each poll tick (default\n * 250 ms — override with `pollMs`).\n *\n * @example\n * ```svelte\n * <script>\n * import { createAuditLedgerStore } from \"@directive-run/svelte\";\n * const entries = createAuditLedgerStore(ledger, { kind: \"constraint.evaluate\", limit: 20 });\n * </script>\n *\n * <ul>\n * {#each $entries as e (e.seq)}\n * <li>{e.kind} @ {new Date(e.ts).toISOString()}</li>\n * {/each}\n * </ul>\n * ```\n */\nexport function createAuditLedgerStore(\n ledger: AuditLedger,\n filter: QueryFilter = {},\n opts: { pollMs?: number } = {},\n): Readable<readonly AuditEntry[]> {\n const pollMs = opts.pollMs ?? 250;\n return readable<readonly AuditEntry[]>(ledger.query(filter), (set) => {\n const id = setInterval(() => set(ledger.query(filter)), pollMs);\n return () => clearInterval(id);\n });\n}\n","export default typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@directive-run/svelte",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0",
|
|
4
4
|
"imports": {
|
|
5
5
|
"#is-development": {
|
|
6
6
|
"production": "./src/dev-false.ts",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"svelte": "^5.54.0",
|
|
65
65
|
"tsup": "^8.3.5",
|
|
66
66
|
"typescript": "^5.7.2",
|
|
67
|
-
"@directive-run/core": "1.
|
|
67
|
+
"@directive-run/core": "1.12.0",
|
|
68
68
|
"@directive-run/query": "1.1.0"
|
|
69
69
|
},
|
|
70
70
|
"scripts": {
|