@directive-run/core 1.1.2 → 1.4.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.
Files changed (61) hide show
  1. package/dist/adapter-utils.cjs +1 -1
  2. package/dist/adapter-utils.d.cts +1 -1
  3. package/dist/adapter-utils.d.ts +1 -1
  4. package/dist/adapter-utils.js +1 -1
  5. package/dist/chunk-DDUARSUH.cjs +7 -0
  6. package/dist/chunk-DDUARSUH.cjs.map +1 -0
  7. package/dist/chunk-E2WETPLH.js +3 -0
  8. package/dist/chunk-E2WETPLH.js.map +1 -0
  9. package/dist/chunk-FK7BD7XT.js +7 -0
  10. package/dist/chunk-FK7BD7XT.js.map +1 -0
  11. package/dist/chunk-LFMRWCIG.js +16 -0
  12. package/dist/chunk-LFMRWCIG.js.map +1 -0
  13. package/dist/chunk-TUS5WDVE.cjs +3 -0
  14. package/dist/chunk-TUS5WDVE.cjs.map +1 -0
  15. package/dist/chunk-VSHSYVSY.cjs +16 -0
  16. package/dist/chunk-VSHSYVSY.cjs.map +1 -0
  17. package/dist/{helpers-mM-gApmO.d.cts → helpers-BUY1lYCX.d.cts} +1 -1
  18. package/dist/{helpers-BLtqbSnA.d.ts → helpers-D6LcRum7.d.ts} +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +307 -8
  22. package/dist/index.d.ts +307 -8
  23. package/dist/index.js +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/internals.cjs +1 -1
  26. package/dist/internals.d.cts +42 -4
  27. package/dist/internals.d.ts +42 -4
  28. package/dist/internals.js +1 -1
  29. package/dist/plugins/index.d.cts +1 -1
  30. package/dist/plugins/index.d.ts +1 -1
  31. package/dist/{plugins-2i_wXhw1.d.cts → plugins-Dy1C8GtT.d.cts} +182 -2
  32. package/dist/{plugins-2i_wXhw1.d.ts → plugins-Dy1C8GtT.d.ts} +182 -2
  33. package/dist/system-2THXJBFM.cjs +2 -0
  34. package/dist/{system-GTVD42IW.cjs.map → system-2THXJBFM.cjs.map} +1 -1
  35. package/dist/system-JIO36ALC.js +2 -0
  36. package/dist/{system-RSS5FWVO.js.map → system-JIO36ALC.js.map} +1 -1
  37. package/dist/testing.cjs +1 -1
  38. package/dist/testing.cjs.map +1 -1
  39. package/dist/testing.d.cts +37 -2
  40. package/dist/testing.d.ts +37 -2
  41. package/dist/testing.js +1 -1
  42. package/dist/testing.js.map +1 -1
  43. package/dist/worker.cjs +1 -1
  44. package/dist/worker.d.cts +1 -1
  45. package/dist/worker.d.ts +1 -1
  46. package/dist/worker.js +1 -1
  47. package/package.json +1 -1
  48. package/dist/chunk-2CAU4M66.cjs +0 -3
  49. package/dist/chunk-2CAU4M66.cjs.map +0 -1
  50. package/dist/chunk-7K4NABPI.js +0 -16
  51. package/dist/chunk-7K4NABPI.js.map +0 -1
  52. package/dist/chunk-EUWV4Y5C.js +0 -3
  53. package/dist/chunk-EUWV4Y5C.js.map +0 -1
  54. package/dist/chunk-GMFH2Z6C.cjs +0 -16
  55. package/dist/chunk-GMFH2Z6C.cjs.map +0 -1
  56. package/dist/chunk-KKHSUZA5.cjs +0 -2
  57. package/dist/chunk-KKHSUZA5.cjs.map +0 -1
  58. package/dist/chunk-LN4YQDLL.js +0 -2
  59. package/dist/chunk-LN4YQDLL.js.map +0 -1
  60. package/dist/system-GTVD42IW.cjs +0 -2
  61. package/dist/system-RSS5FWVO.js +0 -2
@@ -1,16 +0,0 @@
1
- import {z as z$1,a}from'./chunk-EUWV4Y5C.js';import {f,l}from'./chunk-LN4YQDLL.js';import {c}from'./chunk-4CMO5OVZ.js';var y="::";function x(n){return new Proxy({},{get(e,t){if(typeof t!="symbol"&&!l.has(t))return n.get(t)},set(e,t,o){return typeof t=="symbol"||l.has(t)?false:n.set?n.set(t,o):false},has(e,t){return typeof t=="symbol"||l.has(t)?false:n.has?n.has(t):false},deleteProperty(e,t){return typeof t=="symbol"||l.has(t)?false:n.delete?n.delete(t):false},ownKeys(){return n.ownKeys?n.ownKeys():[]},getOwnPropertyDescriptor(e,t){if(typeof t!="symbol"&&n.has&&typeof t=="string"&&n.has(t))return {configurable:true,enumerable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}var H=new WeakMap,W=new WeakMap,z=new WeakMap,V=new WeakMap,U=new WeakMap,G=new WeakMap;function D(n,e){let t=H.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,H.set(n,t);let o=x({get:r=>r==="$store"||r==="$snapshot"?n[r]:n[`${e}${y}${r}`],set:(r,a)=>(n[`${e}${y}${r}`]=a,true),has:r=>`${e}${y}${r}`in n,delete:r=>(delete n[`${e}${y}${r}`],true)});return t.set(e,o),o}function L(n,e,t){let o=W.get(n);if(o)return o;let r=x({get:a=>{if(Object.hasOwn(e,a))return D(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return W.set(n,r),r}function Z(n,e,t){let o=`${e}|${t.join(",")}`,r=U.get(n);if(r){let i=r.get(o);if(i)return i}else r=new Map,U.set(n,r);let a=new Set(t),u=["self",...t],f$1=x({get:i=>{if(i==="self")return D(n,e);if(a.has(i))return D(n,i);f&&console.warn(`[Directive] Module "${e}" accessed undeclared cross-module property "${i}". Add it to crossModuleDeps or use "facts.self.${i}" for own module facts.`);},has:i=>i==="self"||a.has(i),ownKeys:()=>u});return r.set(o,f$1),f$1}function T(n,e){let t=V.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,V.set(n,t);let o=x({get:r=>n[`${e}${y}${r}`],has:r=>`${e}${y}${r}`in n});return t.set(e,o),o}function J(n,e,t){let o=z.get(n);if(o)return o;let r=x({get:a=>{if(Object.hasOwn(e,a))return T(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return z.set(n,r),r}function Q(n,e,t){let o=G.get(n);return o||(o=new Map,G.set(n,o)),x({get:r=>{if(!Object.hasOwn(e,r))return;let a=o.get(r);if(a)return a;let u=x({get:f=>i=>{n.dispatch({type:`${r}${y}${f}`,...i});}});return o.set(r,u),u},has:r=>Object.hasOwn(e,r),ownKeys:()=>t()})}function b(n){if(n.includes(".")){let[e,...t]=n.split(".");return `${e}${y}${t.join(y)}`}return n}function N(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.indexOf(y);if(r>0){let a=t.slice(0,r),u=t.slice(r+y.length);e[a]||(e[a]={}),e[a][u]=o;}else e._root||(e._root={}),e._root[t]=o;}return e}function O(n,e,t,o){return t?Z(n,e,o):D(n,e)}function M(n,e){return `${n}${y}${e}`}function P(n){return Object.keys(n).length>0?n:void 0}function se(n,e){let t={};for(let[o,r]of Object.entries(n.schema.facts))t[M(e,o)]=r;return t}function oe(n,e){if(n.init)return t=>{let o=D(t,e);n.init(o);}}function ie(n,e,t,o){if(!n.derive)return;let r={};for(let[a$1,u]of Object.entries(n.derive)){let f=a(u),i=f?u.compute:u,w=f?u.meta:void 0,g=(d,m)=>{let R=O(d,e,t,o),h=T(m,e);return i(R,h)};r[M(e,a$1)]=w?{compute:g,meta:w}:g;}return P(r)}function ae(n,e){if(!n.events)return;let t={};for(let[o,r]of Object.entries(n.events)){let a=typeof r=="object"&&r!==null&&Object.hasOwn(r,"handler"),u=a?r.handler:r,f=a?r.meta:void 0,i=(w,g)=>{let d=D(w,e);u(d,g);};t[M(e,o)]=f?{handler:i,meta:f}:i;}return P(t)}function ce(n,e,t,o){if(!n.constraints)return;let r={};for(let[a,u]of Object.entries(n.constraints)){let f=u;r[M(e,a)]={...f,deps:f.deps?.map(i=>M(e,i)),after:f.after?.map(i=>i.includes(y)?i:M(e,i)),when:i=>{let w=O(i,e,t,o);return f.when(w)},require:typeof f.require=="function"?i=>{let w=O(i,e,t,o);return f.require(w)}:f.require};}return P(r)}function ue(n,e,t,o){if(!n.resolvers)return;let r={};for(let[u,f]of Object.entries(n.resolvers)){let w=function(g){return {facts:O(g.facts,e,t,o),signal:g.signal}};let i=f;r[M(e,u)]={...i,...i.resolve&&{resolve:async(g,d)=>{await i.resolve(g,w(d));}},...i.resolveBatch&&{resolveBatch:async(g,d)=>{await i.resolveBatch(g,w(d));}},...i.resolveBatchWithResults&&{resolveBatchWithResults:async(g,d)=>i.resolveBatchWithResults(g,w(d))}};}return P(r)}function de(n,e,t,o){if(!n.effects)return;let r={};for(let[a,u]of Object.entries(n.effects)){let f=u;r[M(e,a)]={...f,run:(i,w)=>{let g=O(i,e,t,o),d=w?O(w,e,t,o):void 0;return f.run(g,d)},deps:f.deps?.map(i=>M(e,i))};}return P(r)}function le(n,e,t){return {snapshotEvents:t&&!t.has(e)?[]:n.history?.snapshotEvents?.map(o=>M(e,o))}}function _(n){let{mod:e,namespace:t,snapshotModulesSet:o}=n,r=!!(e.crossModuleDeps&&Object.keys(e.crossModuleDeps).length>0),a=r?Object.keys(e.crossModuleDeps):[];return {id:e.id,schema:se(e,t),requirements:e.schema.requirements??{},init:oe(e,t),derive:ie(e,t,r,a),events:ae(e,t),effects:de(e,t,r,a),constraints:ce(e,t,r,a),resolvers:ue(e,t,r,a),hooks:e.hooks,meta:e.meta,history:le(e,t,o)}}function fe(n){let e=Object.keys(n),t=new Set(e),o=new Set,r=new Set,a=[],u=[];function f(i){if(o.has(i))return;if(r.has(i)){let g=u.indexOf(i),d=[...u.slice(g),i].join(" \u2192 ");throw new Error(`[Directive] Circular dependency detected: ${d}. Modules cannot have circular crossModuleDeps. Break the cycle by removing one of the cross-module references.`)}r.add(i),u.push(i);let w=n[i];if(w?.crossModuleDeps)for(let g of Object.keys(w.crossModuleDeps))t.has(g)&&f(g);u.pop(),r.delete(i),o.add(i),a.push(i);}for(let i of e)f(i);return a}function X(n,e){let t=[];for(let o of Object.keys(e.schema.facts))t.push(`${n}${y}${o}`);if(e.schema.derivations)for(let o of Object.keys(e.schema.derivations))t.push(`${n}${y}${o}`);return t}function Oe(n){if("module"in n){if(!n.module)throw new Error("[Directive] createSystem requires a module. Got: "+typeof n.module);return ge(n)}let e=n;if(Array.isArray(e.modules))throw new Error(`[Directive] createSystem expects modules as an object, not an array.
2
-
3
- Instead of:
4
- createSystem({ modules: [authModule, dataModule] })
5
-
6
- Use:
7
- createSystem({ modules: { auth: authModule, data: dataModule } })
8
-
9
- Or for a single module:
10
- createSystem({ module: counterModule })`);let t=e.modules;if(t&&typeof t=="object"&&"id"in t&&"schema"in t)throw new Error(`[Directive] A single module was passed to \`modules:\`. For a single module, use \`module:\` instead:
11
-
12
- createSystem({ module: myModule })
13
-
14
- For multiple modules, wrap in an object:
15
- createSystem({ modules: { myName: myModule } })`);return ye(e)}function ye(n){let e=n.modules,t=new Set(Object.keys(e)),o=typeof n.history=="object"?n.history:null,r=o?.snapshotModules?new Set(o.snapshotModules):null;if(n.tickMs!==void 0&&n.tickMs<=0)throw new Error("[Directive] tickMs must be a positive number");if(f){for(let[s,c]of Object.entries(e))if(c.crossModuleDeps)for(let l of Object.keys(c.crossModuleDeps))l===s?console.warn(`[Directive] Module "${s}" references itself in crossModuleDeps. Use "facts.self" to access own module's facts instead.`):t.has(l)||console.warn(`[Directive] Module "${s}" declares crossModuleDeps.${l}, but no module with namespace "${l}" exists in the system. Available modules: ${[...t].join(", ")}`);}if(f&&o?.snapshotModules)for(let s of o.snapshotModules)t.has(s)||console.warn(`[Directive] history.snapshotModules entry "${s}" doesn't match any module. Available modules: ${[...t].join(", ")}`);let a,u=n.initOrder??"auto";if(Array.isArray(u)){let s=u,c=Object.keys(e).filter(l=>!s.includes(l));if(c.length>0)throw new Error(`[Directive] initOrder is missing modules: ${c.join(", ")}. All modules must be included in the explicit order.`);a=s;}else u==="declaration"?a=Object.keys(e):a=fe(e);let{history:f$1,trace:i,errorBoundary:w}=Y(n);for(let s of Object.keys(e)){if(s.includes(y))throw new Error(`[Directive] Module name "${s}" contains the reserved separator "${y}". Module names cannot contain "${y}".`);let c=e[s];if(c){for(let l of Object.keys(c.schema.facts))if(l.includes(y))throw new Error(`[Directive] Schema key "${l}" in module "${s}" contains the reserved separator "${y}". Schema keys cannot contain "${y}".`)}}let g={names:null};function d(){return g.names===null&&(g.names=Object.keys(e)),g.names}let m=a.map(s=>{let c=e[s];return c?_({mod:c,namespace:s,snapshotModulesSet:r}):null}).filter(s=>s!==null);f&&n.tickMs&&n.tickMs>0&&(m.some(c=>c.events&&Object.keys(c.events).some(l=>l.endsWith(`${y}tick`)))||console.warn(`[Directive] tickMs is set to ${n.tickMs}ms but no module defines a "tick" event handler.`));let R=null,h=null;function B(s){for(let[c$1,l$1]of Object.entries(s)){if(l.has(c$1)){f&&console.warn(`[Directive] initialFacts/hydrate contains blocked namespace "${c$1}". Skipping.`);continue}if(!t.has(c$1)){f&&console.warn(`[Directive] initialFacts/hydrate contains unknown namespace "${c$1}". Available modules: ${[...t].join(", ")}`);continue}if(l$1&&typeof l$1=="object"&&!c(l$1))throw new Error(`[Directive] initialFacts/hydrate for namespace "${c$1}" contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.`);for(let[v,S]of Object.entries(l$1))l.has(v)||(h.facts[`${c$1}${y}${v}`]=S);}}h=z$1({modules:m,plugins:n.plugins,history:f$1,trace:i,errorBoundary:w,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{n.initialFacts&&B(n.initialFacts),R&&(B(R),R=null);}});let $=new Map;for(let s of Object.keys(e)){let c=e[s];c&&$.set(s,X(s,c));}let K=L(h.facts,e,d),te=J(h.derive,e,d),re=Q(h,e,d),j=null,C=n.tickMs,F={_mode:"namespaced",facts:K,history:h.history,derive:te,events:re,constraints:h.constraints,effects:h.effects,resolvers:h.resolvers,async hydrate(s){if(h.isRunning)throw new Error("[Directive] hydrate() must be called before start(). The system is already running.");let c=await s();c&&typeof c=="object"&&(R=c);},initialize(){h.initialize();},start(){if(h.start(),C&&C>0){let s;for(let c of m)if(c?.events&&(s=Object.keys(c.events).find(l=>l.endsWith(`${y}tick`)),s))break;if(s){let c=s;j=setInterval(()=>{h.dispatch({type:c});},C);}}},stop(){j&&(clearInterval(j),j=null),h.stop();},destroy(){this.stop(),h.destroy();},dispatch(s){h.dispatch(s);},read(s){return h.read(b(s))},subscribe(s,c){let l=[];for(let v of s)if(v.endsWith(".*")){let S=v.slice(0,-2),q=$.get(S);q?l.push(...q):f&&console.warn(`[Directive] subscribe wildcard "${v}" \u2014 namespace "${S}" not found.`);}else l.push(b(v));return h.subscribe(l,c)},subscribeModule(s,c){let l=$.get(s);return !l||l.length===0?(f&&console.warn(`[Directive] subscribeModule("${s}") \u2014 namespace not found. Available: ${[...$.keys()].join(", ")}`),()=>{}):h.subscribe(l,c)},watch(s,c,l){return h.watch(b(s),c,l)},when(s,c){return h.when(()=>s(K),c)},getDistributableSnapshot(s){let c={...s,includeDerivations:s?.includeDerivations?.map(b),excludeDerivations:s?.excludeDerivations?.map(b),includeFacts:s?.includeFacts?.map(b)},l=h.getDistributableSnapshot(c);return {...l,data:N(l.data)}},watchDistributableSnapshot(s,c){let l={...s,includeDerivations:s?.includeDerivations?.map(b),excludeDerivations:s?.excludeDerivations?.map(b),includeFacts:s?.includeFacts?.map(b)};return h.watchDistributableSnapshot(l,v=>{c({...v,data:N(v.data)});})},registerModule(s,c){if(t.has(s))throw new Error(`[Directive] Module namespace "${s}" already exists. Cannot register a duplicate namespace.`);if(s.includes(y))throw new Error(`[Directive] Module name "${s}" contains the reserved separator "${y}".`);if(l.has(s))throw new Error(`[Directive] Module name "${s}" is a blocked property.`);for(let S of Object.keys(c.schema.facts))if(S.includes(y))throw new Error(`[Directive] Schema key "${S}" in module "${s}" contains the reserved separator "${y}".`);let l$1=c,v=_({mod:l$1,namespace:s,snapshotModulesSet:r});t.add(s),e[s]=l$1,g.names=null,$.set(s,X(s,l$1)),h.registerModule(v);}};return ee(F,h),ne(F),F}function Y(n){let e=n.history,t=n.trace,o=n.errorBoundary;return n.zeroConfig&&(e=e??f,o={onConstraintError:"skip",onResolverError:"skip",onEffectError:"skip",onDerivationError:"skip",...n.errorBoundary}),{history:e,trace:t,errorBoundary:o}}function ee(n,e){Object.defineProperties(n,{trace:{get(){return e.trace},enumerable:true,configurable:true},meta:{value:e.meta,enumerable:true,configurable:true},isRunning:{get(){return e.isRunning},enumerable:true,configurable:true},isSettled:{get(){return e.isSettled},enumerable:true,configurable:true},isInitialized:{get(){return e.isInitialized},enumerable:true,configurable:true},isReady:{get(){return e.isReady},enumerable:true,configurable:true}}),n.whenReady=e.whenReady.bind(e),n.batch=e.batch.bind(e),n.onSettledChange=e.onSettledChange.bind(e),n.onHistoryChange=e.onHistoryChange.bind(e),n.inspect=e.inspect.bind(e),n.settle=e.settle.bind(e),n.explain=e.explain.bind(e),n.getSnapshot=e.getSnapshot.bind(e),n.restore=e.restore.bind(e),n.observe=e.observe.bind(e);let t=["dispatch","read","subscribe","watch","when","getDistributableSnapshot","watchDistributableSnapshot"];for(let o of t)o in n||(n[o]=e[o].bind(e));}function ne(n){f&&process.env.NODE_ENV!=="test"&&setTimeout(()=>{!n.isRunning&&!n.isInitialized&&console.warn("[Directive] System created but start() was never called. Constraints, resolvers, and effects will not run until you call system.start().");},0);}function ge(n){let e=n.module;if(!e)throw new Error("[Directive] createSystem requires a module. Got: "+typeof e);if(n.tickMs!==void 0&&n.tickMs<=0)throw new Error("[Directive] tickMs must be a positive number");if(n.initialFacts&&!c(n.initialFacts))throw new Error("[Directive] initialFacts contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");f&&(e.crossModuleDeps&&Object.keys(e.crossModuleDeps).length>0&&console.warn("[Directive] Single module mode ignores crossModuleDeps. Use multiple modules if cross-module access is needed: createSystem({ modules: { ... } })"),n.tickMs&&n.tickMs>0&&(e.events&&"tick"in e.events||console.warn(`[Directive] tickMs is set to ${n.tickMs}ms but module has no "tick" event handler.`)),(typeof n.history=="object"?n.history:null)?.snapshotModules&&console.warn("[Directive] history.snapshotModules has no effect in single-module mode. Use history.snapshotEvents on the module definition instead, or switch to createSystem({ modules: { ... } }) for multi-module filtering."));let{history:t,trace:o,errorBoundary:r}=Y(n),a=null,u=null;u=z$1({modules:[{id:e.id,schema:e.schema.facts,requirements:e.schema.requirements,init:e.init,derive:e.derive,events:e.events,effects:e.effects,constraints:e.constraints,resolvers:e.resolvers,hooks:e.hooks,meta:e.meta,history:e.history}],plugins:n.plugins,history:t,trace:o,errorBoundary:r,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{if(n.initialFacts)for(let[d,m]of Object.entries(n.initialFacts))l.has(d)||(u.facts[d]=m);if(a){if(!c(a))f&&console.warn("[Directive] hydrate() data contains potentially dangerous keys. Skipping.");else for(let[d,m]of Object.entries(a))l.has(d)||(u.facts[d]=m);a=null;}}});let f$1=new Proxy({},{get(d,m){if(typeof m!="symbol"&&!l.has(m))return R=>{u.dispatch({type:m,...R});}},has(d,m){return typeof m=="symbol"||l.has(m)?false:e.events?m in e.events:false},ownKeys(){return e.events?Object.keys(e.events):[]},getOwnPropertyDescriptor(d,m){if(typeof m!="symbol"&&!l.has(m)&&e.events&&m in e.events)return {configurable:true,enumerable:true}},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),i=null,w=n.tickMs,g={_mode:"single",facts:u.facts,history:u.history,derive:u.derive,events:f$1,constraints:u.constraints,effects:u.effects,resolvers:u.resolvers,async hydrate(d){if(u.isRunning)throw new Error("[Directive] hydrate() must be called before start(). The system is already running.");let m=await d();m&&typeof m=="object"&&(a=m);},initialize(){u.initialize();},start(){u.start(),w&&w>0&&e.events&&"tick"in e.events&&(i=setInterval(()=>{u.dispatch({type:"tick"});},w));},stop(){i&&(clearInterval(i),i=null),u.stop();},destroy(){this.stop(),u.destroy();},registerModule(d){u.registerModule({id:d.id,schema:d.schema.facts,requirements:d.schema.requirements,init:d.init,derive:d.derive,events:d.events,effects:d.effects,constraints:d.constraints,resolvers:d.resolvers,hooks:d.hooks,history:d.history});}};return ee(g,u),ne(g),g}export{Oe as a};//# sourceMappingURL=chunk-7K4NABPI.js.map
16
- //# sourceMappingURL=chunk-7K4NABPI.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/system-proxies.ts","../src/core/system-module-transform.ts","../src/core/system.ts"],"names":["SEPARATOR","createHardenedProxy","config","_","prop","BLOCKED_PROPS","value","moduleFactsProxyCache","namespacedFactsProxyCache","namespacedDeriveProxyCache","moduleDeriveProxyCache","crossModuleFactsProxyCache","moduleEventsProxyCache","createModuleFactsProxy","facts","namespace","namespaceCache","cached","proxy","createNamespacedFactsProxy","modulesMap","getModuleNames","createCrossModuleFactsProxy","selfNamespace","depNamespaces","cacheKey","depNamesSet","allKeys","key","dev_true_default","createModuleDeriveProxy","derive","createNamespacedDeriveProxy","createNamespacedEventsProxy","engine","moduleEventsProxy","eventName","payload","toInternalKey","rest","denormalizeFlatKeys","flatData","result","sepIndex","ns","local","createScopedFactsProxy","hasCrossModuleDeps","prefixKey","nonEmpty","rec","prefixSchema","mod","prefixInit","moduleFactsProxy","prefixDerive","raw","isObj","isDerivationWithMeta","fn","meta","wrapper","factsProxy","deriveProxy","prefixEventHandlers","handler","event","prefixConstraints","constraint","constraintDef","dep","prefixResolvers","resolver","wrapCtx","ctx","resolverDef","req","reqs","prefixEffects","effect","effectDef","prev","prevProxy","prefixHistory","snapshotModulesSet","e","prefixModuleDefinition","options","topologicalSort","namespaces","namespacesSet","visited","visiting","path","visit","cycleStart","cycle","depNamespace","collectNamespaceKeys","keys","createSystem","createSingleModuleSystem","namedOptions","mods","createNamespacedSystem","moduleNamespaces","historyConfig","name","orderedNamespaces","initOrder","explicitOrder","missingModules","history","trace","errorBoundary","applyZeroConfigDefaults","moduleNamesCache","flatModules","m","k","hydratedFacts","applyNamespacedFacts","namespacedFacts","isPrototypeSafe","createEngine","namespaceKeysMap","namespacedFactsProxy","namespacedDeriveProxy","namespacedEventsProxy","tickInterval","tickMs","system","loader","tickEventKey","derivationId","ids","listener","internalIds","id","callback","predicate","internalOptions","snapshot","moduleDef","flat","bindEnginePassthroughs","warnIfNotStarted","overridableMethods","method","eventsProxy"],"mappings":"uHAmBO,IA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ASA,CAAAA,CAAU,OACrB,CAAC,EACH,CAEF,CAAA,CAEA,OAAAE,EAAAA,CAAuBd,CAAAA,CAAQjG,CAAM,CAAA,CACrCgH,EAAAA,CAAiBf,CAAM,CAAA,CAEhBA,CACT","file":"chunk-7K4NABPI.js","sourcesContent":["/**\n * Proxy factory functions for system-level namespace translation.\n *\n * Extracted from system.ts to reduce file size. All functions are pure\n * proxy factories — they create proxies that translate between unprefixed\n * module keys and prefixed internal keys (e.g., `token` ↔ `auth::token`).\n *\n * @internal\n */\n\nimport isDevelopment from \"#is-development\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type { ModulesMap } from \"./types.js\";\n\n/**\n * Namespace separator for internal key prefixing (e.g., \"auth::token\").\n *\n * @internal\n */\nexport const SEPARATOR = \"::\";\n\n// ============================================================================\n// Hardened Proxy Factory\n// ============================================================================\n\n/**\n * Configuration for creating a hardened proxy with consistent security traps.\n *\n * @internal\n */\ninterface HardenedProxyConfig {\n /** Return the value for a string property access */\n get: (prop: string) => unknown;\n /** Handle property assignment. Omit for read-only proxies (returns false). */\n set?: (prop: string, value: unknown) => boolean;\n /** Check if a string property exists */\n has?: (prop: string) => boolean;\n /** Return all own keys for enumeration */\n ownKeys?: () => string[];\n /** Handle property deletion. Omit to reject deletions. */\n delete?: (prop: string) => boolean;\n}\n\n/**\n * Create a proxy with consistent security hardening.\n *\n * Every proxy created by this factory includes:\n * - Symbol access returns `undefined`\n * - BLOCKED_PROPS (`__proto__`, `constructor`, `prototype`) rejected\n * - `defineProperty` returns `false`\n * - `getPrototypeOf` returns `null`\n * - `setPrototypeOf` returns `false`\n *\n * @internal\n */\nfunction createHardenedProxy<T extends object>(config: HardenedProxyConfig): T {\n return new Proxy({} as T, {\n get(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n\n return config.get(prop);\n },\n set(_, prop: string | symbol, value: unknown) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.set ? config.set(prop, value) : false;\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.has ? config.has(prop) : false;\n },\n deleteProperty(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.delete ? config.delete(prop) : false;\n },\n ownKeys() {\n return config.ownKeys ? config.ownKeys() : [];\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (config.has && typeof prop === \"string\" && config.has(prop)) {\n return { configurable: true, enumerable: true };\n }\n\n return undefined;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n });\n}\n\n// ============================================================================\n// Proxy Cache (Performance)\n// ============================================================================\n\n/**\n * WeakMap to cache module facts proxies. Keyed by the facts store object.\n * Inner map is keyed by namespace string.\n */\nconst moduleFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced facts proxies.\n */\nconst namespacedFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Record<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced derive proxies.\n */\nconst namespacedDeriveProxyCache = new WeakMap<\n Record<string, unknown>,\n Record<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache module derive proxies.\n */\nconst moduleDeriveProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache cross-module facts proxies.\n * Keyed by facts store, then by \"selfNamespace|depKeys\" string.\n */\nconst crossModuleFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, Record<string, unknown>>>\n>();\n\n/**\n * WeakMap to cache module events proxies.\n */\nconst moduleEventsProxyCache = new WeakMap<\n // biome-ignore lint/suspicious/noExplicitAny: Engine type for cache key\n any,\n Map<string, Record<string, (payload?: Record<string, unknown>) => void>>\n>();\n\n// ============================================================================\n// Module Facts Proxy\n// ============================================================================\n\n/**\n * Create a proxy for a single module's facts (used in init, event handlers).\n * Translates unprefixed keys to prefixed: `token` → `auth::token`\n *\n * Proxies are cached per facts store and namespace for performance.\n *\n * @param facts - The flat facts store\n * @param namespace - The module namespace for key prefixing\n * @returns A proxy that translates property access to prefixed keys\n *\n * @internal\n */\nexport function createModuleFactsProxy(\n facts: Record<string, unknown>,\n namespace: string,\n): Record<string, unknown> {\n // Check cache first\n let namespaceCache = moduleFactsProxyCache.get(facts);\n if (namespaceCache) {\n const cached = namespaceCache.get(namespace);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n moduleFactsProxyCache.set(facts, namespaceCache);\n }\n\n const proxy = createHardenedProxy<Record<string, unknown>>({\n get: (prop) => {\n // Reserved properties bypass namespace prefixing (used by engine internals)\n if (prop === \"$store\" || prop === \"$snapshot\") {\n return facts[prop];\n }\n\n return facts[`${namespace}${SEPARATOR}${prop}`];\n },\n set: (prop, value) => {\n facts[`${namespace}${SEPARATOR}${prop}`] = value;\n\n return true;\n },\n has: (prop) => `${namespace}${SEPARATOR}${prop}` in facts,\n delete: (prop) => {\n delete facts[`${namespace}${SEPARATOR}${prop}`];\n\n return true;\n },\n });\n\n namespaceCache.set(namespace, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Facts Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced facts access.\n * `facts.auth.token` → reads `auth::token` from flat store\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n *\n * @param facts - The flat facts store\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names (supports dynamic registration)\n * @returns A proxy that delegates to per-module facts proxies\n *\n * @internal\n */\nexport function createNamespacedFactsProxy(\n facts: Record<string, unknown>,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n // Check cache first\n const cached = namespacedFactsProxyCache.get(facts);\n if (cached) {\n return cached;\n }\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n return createModuleFactsProxy(facts, namespace);\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n\n namespacedFactsProxyCache.set(facts, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Cross-Module Facts Proxy\n// ============================================================================\n\n/**\n * Create a proxy for cross-module facts access with \"self\" for own module.\n * `facts.self.users` → reads own module's facts\n * `facts.auth.token` → reads dependency module's facts\n *\n * Used when a module has crossModuleDeps defined.\n *\n * @param facts - The flat facts store\n * @param selfNamespace - The namespace of the module that owns this proxy\n * @param depNamespaces - Array of declared dependency namespaces\n * @returns A proxy that provides `self` and declared dependency access\n *\n * @internal\n */\nexport function createCrossModuleFactsProxy(\n facts: Record<string, unknown>,\n selfNamespace: string,\n depNamespaces: string[],\n): Record<string, Record<string, unknown>> {\n // depNamespaces comes from Object.keys() which has stable order per module,\n // so join is sufficient (no need to sort)\n const cacheKey = `${selfNamespace}|${depNamespaces.join(\",\")}`;\n\n // Check cache first\n let namespaceCache = crossModuleFactsProxyCache.get(facts);\n if (namespaceCache) {\n const cached = namespaceCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n crossModuleFactsProxyCache.set(facts, namespaceCache);\n }\n\n const depNamesSet = new Set(depNamespaces);\n const allKeys = [\"self\", ...depNamespaces];\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (key) => {\n // \"self\" maps to own module's namespace\n if (key === \"self\") {\n return createModuleFactsProxy(facts, selfNamespace);\n }\n\n // Check if it's a declared dependency\n if (depNamesSet.has(key)) {\n return createModuleFactsProxy(facts, key);\n }\n\n // Dev-mode warning for undeclared cross-module access\n if (isDevelopment) {\n console.warn(\n `[Directive] Module \"${selfNamespace}\" accessed undeclared cross-module property \"${key}\". ` +\n `Add it to crossModuleDeps or use \"facts.self.${key}\" for own module facts.`,\n );\n }\n\n return undefined;\n },\n has: (key) => key === \"self\" || depNamesSet.has(key),\n ownKeys: () => allKeys,\n });\n\n namespaceCache.set(cacheKey, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Module Derive Proxy\n// ============================================================================\n\n/**\n * Create a proxy for a single module's derivations.\n * Translates unprefixed keys to prefixed: `status` → `auth::status`\n *\n * Proxies are cached per derive store and namespace for performance.\n *\n * @param derive - The flat derivations store\n * @param namespace - The module namespace for key prefixing\n * @returns A read-only proxy that translates property access to prefixed keys\n *\n * @internal\n */\nexport function createModuleDeriveProxy(\n derive: Record<string, unknown>,\n namespace: string,\n): Record<string, unknown> {\n // Check cache first\n let namespaceCache = moduleDeriveProxyCache.get(derive);\n if (namespaceCache) {\n const cached = namespaceCache.get(namespace);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n moduleDeriveProxyCache.set(derive, namespaceCache);\n }\n\n const proxy = createHardenedProxy<Record<string, unknown>>({\n get: (prop) => derive[`${namespace}${SEPARATOR}${prop}`],\n has: (prop) => `${namespace}${SEPARATOR}${prop}` in derive,\n });\n\n namespaceCache.set(namespace, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Derive Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced derivations access.\n * `derive.auth.status` → reads `auth::status` from flat derive\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n *\n * @param derive - The flat derivations store\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names\n * @returns A read-only proxy that delegates to per-module derive proxies\n *\n * @internal\n */\nexport function createNamespacedDeriveProxy(\n derive: Record<string, unknown>,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n // Check cache first\n const cached = namespacedDeriveProxyCache.get(derive);\n if (cached) {\n return cached;\n }\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n return createModuleDeriveProxy(derive, namespace);\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n\n namespacedDeriveProxyCache.set(derive, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Events Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced events access.\n * `events.auth.login({ token })` → dispatches `{ type: \"auth::login\", token }`\n *\n * Uses Set for O(1) namespace lookups and caches proxies for performance.\n *\n * @param engine - The engine instance (used for dispatch)\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names\n * @returns A read-only proxy that returns event dispatcher functions per namespace\n *\n * @internal\n */\nexport function createNamespacedEventsProxy(\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n engine: any,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, (payload?: Record<string, unknown>) => void>> {\n // Get or create the namespace cache for this engine\n let namespaceCache = moduleEventsProxyCache.get(engine);\n if (!namespaceCache) {\n namespaceCache = new Map();\n moduleEventsProxyCache.set(engine, namespaceCache);\n }\n\n return createHardenedProxy<\n Record<string, Record<string, (payload?: Record<string, unknown>) => void>>\n >({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n // Check cache for this namespace's event proxy\n const cached = namespaceCache!.get(namespace);\n if (cached) {\n return cached;\n }\n\n // Create and cache the module events proxy\n const moduleEventsProxy = createHardenedProxy<\n Record<string, (payload?: Record<string, unknown>) => void>\n >({\n get: (eventName) => {\n return (payload?: Record<string, unknown>) => {\n engine.dispatch({\n type: `${namespace}${SEPARATOR}${eventName}`,\n ...payload,\n });\n };\n },\n });\n\n namespaceCache!.set(namespace, moduleEventsProxy);\n\n return moduleEventsProxy;\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n}\n\n// ============================================================================\n// Key Conversion Helpers\n// ============================================================================\n\n/**\n * Convert a namespaced key (e.g., \"auth.status\") to internal prefixed format (\"auth::status\").\n * If the key is already in prefixed format, returns it unchanged.\n *\n * @param key - The key to convert (dot-separated or already prefixed)\n * @returns The internal prefixed key\n *\n * @example\n * toInternalKey(\"auth.status\") // → \"auth::status\"\n * toInternalKey(\"auth::status\") // → \"auth::status\" (unchanged)\n * toInternalKey(\"status\") // → \"status\" (unchanged)\n *\n * @internal\n */\nexport function toInternalKey(key: string): string {\n // If key contains a dot, convert to separator format\n if (key.includes(\".\")) {\n const [namespace, ...rest] = key.split(\".\");\n\n return `${namespace}${SEPARATOR}${rest.join(SEPARATOR)}`;\n }\n // Already in internal format or simple key\n\n return key;\n}\n\n// ============================================================================\n// Snapshot Helpers\n// ============================================================================\n\n/**\n * Convert flat internal keys (e.g., `\"auth::token\"`) to nested namespaced\n * format (e.g., `{ auth: { token: ... } }`).\n *\n * Keys without a separator are grouped under `_root`.\n *\n * @param flatData - Object with internal prefixed keys\n * @returns Nested object grouped by namespace\n *\n * @internal\n */\nexport function denormalizeFlatKeys(\n flatData: Record<string, unknown>,\n): Record<string, Record<string, unknown>> {\n const result: Record<string, Record<string, unknown>> = {};\n\n for (const [key, value] of Object.entries(flatData)) {\n const sepIndex = key.indexOf(SEPARATOR);\n if (sepIndex > 0) {\n const ns = key.slice(0, sepIndex);\n const local = key.slice(sepIndex + SEPARATOR.length);\n if (!result[ns]) {\n result[ns] = {};\n }\n result[ns][local] = value;\n } else {\n if (!result._root) {\n result._root = {};\n }\n result._root[key] = value;\n }\n }\n\n return result;\n}\n","/**\n * Module transformation for namespaced systems.\n *\n * Converts a module's unprefixed keys to prefixed internal format\n * (e.g., `token` → `auth::token`). Used by both the initial system\n * setup loop and `registerModule()`.\n *\n * @internal\n */\n\nimport {\n SEPARATOR,\n createCrossModuleFactsProxy,\n createModuleDeriveProxy,\n createModuleFactsProxy,\n} from \"./system-proxies.js\";\nimport type { ModuleDef, ModuleSchema } from \"./types.js\";\nimport { isDerivationWithMeta } from \"./types/meta.js\";\n\n/**\n * The flat engine module format produced by prefixModuleDefinition.\n * Ready to be passed to createEngine or engine.registerModule.\n *\n * @internal\n */\nexport interface FlatModuleDefinition {\n id: string;\n schema: Record<string, unknown>;\n requirements: Record<string, unknown>;\n init: ((facts: Record<string, unknown>) => void) | undefined;\n derive: Record<string, unknown> | undefined;\n events: Record<string, unknown> | undefined;\n effects: Record<string, unknown> | undefined;\n constraints: Record<string, unknown> | undefined;\n resolvers: Record<string, unknown> | undefined;\n hooks: ModuleDef<ModuleSchema>[\"hooks\"];\n meta?: ModuleDef<ModuleSchema>[\"meta\"];\n history: { snapshotEvents?: string[] };\n}\n\n/**\n * Options for prefixModuleDefinition.\n *\n * @internal\n */\nexport interface PrefixModuleOptions {\n /** The module to transform */\n mod: ModuleDef<ModuleSchema>;\n /** The namespace to prefix keys with */\n namespace: string;\n /** Set of modules to snapshot (null = all). Used for history filtering. */\n snapshotModulesSet: Set<string> | null;\n}\n\n/**\n * Create a facts proxy appropriate for the module's cross-module configuration.\n * Returns a cross-module proxy when deps are declared, otherwise a module proxy.\n *\n * @internal\n */\nfunction createScopedFactsProxy(\n facts: Record<string, unknown>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> {\n return hasCrossModuleDeps\n ? createCrossModuleFactsProxy(facts, namespace, depNamespaces)\n : createModuleFactsProxy(facts, namespace);\n}\n\n/** Prefix a key with the namespace separator */\nfunction prefixKey(namespace: string, key: string): string {\n return `${namespace}${SEPARATOR}${key}`;\n}\n\n/** Return a non-empty record or undefined */\nfunction nonEmpty<T extends Record<string, unknown>>(rec: T): T | undefined {\n return Object.keys(rec).length > 0 ? rec : undefined;\n}\n\n/** Prefix schema fact keys */\nfunction prefixSchema(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(mod.schema.facts)) {\n result[prefixKey(namespace, key)] = value;\n }\n\n return result;\n}\n\n/** Create a prefixed init function */\nfunction prefixInit(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): ((facts: Record<string, unknown>) => void) | undefined {\n if (!mod.init) {\n return undefined;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Facts proxy type coercion\n return (facts: any) => {\n const moduleFactsProxy = createModuleFactsProxy(facts, namespace);\n // biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n (mod.init as any)(moduleFactsProxy);\n };\n}\n\n/** Prefix derivation keys and wrap derivation functions with scoped proxies */\nfunction prefixDerive(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.derive) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(mod.derive)) {\n const isObj = isDerivationWithMeta(raw);\n const fn = isObj ? raw.compute : raw;\n const meta = isObj ? raw.meta : undefined;\n\n const wrapper = (facts: unknown, derive: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n const deriveProxy = createModuleDeriveProxy(\n derive as Record<string, unknown>,\n namespace,\n );\n // biome-ignore lint/suspicious/noExplicitAny: Derive function type coercion\n return (fn as any)(factsProxy, deriveProxy);\n };\n\n // Pass through as { compute, meta } so derivationsManager can unwrap\n result[prefixKey(namespace, key)] = meta\n ? { compute: wrapper, meta }\n : wrapper;\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix event handler keys and wrap handlers with module-scoped proxies */\nfunction prefixEventHandlers(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): Record<string, unknown> | undefined {\n if (!mod.events) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(mod.events)) {\n // Unwrap { handler, meta } form\n const isObj =\n typeof raw === \"object\" && raw !== null && Object.hasOwn(raw, \"handler\");\n const handler = isObj\n ? (raw as { handler: Function }).handler\n : raw;\n const meta = isObj\n ? (raw as { meta?: unknown }).meta\n : undefined;\n\n const wrapper = (facts: unknown, event: unknown) => {\n const moduleFactsProxy = createModuleFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n );\n // biome-ignore lint/suspicious/noExplicitAny: Event handler type coercion\n (handler as any)(moduleFactsProxy, event);\n };\n\n // Pass through as { handler, meta } so engine can extract meta\n result[prefixKey(namespace, key)] = meta\n ? { handler: wrapper, meta }\n : wrapper;\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix constraint keys and wrap when/require with scoped proxies */\nfunction prefixConstraints(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.constraints) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, constraint] of Object.entries(mod.constraints)) {\n const constraintDef = constraint as {\n when: (facts: unknown) => boolean | Promise<boolean>;\n require: unknown | ((facts: unknown) => unknown);\n priority?: number;\n async?: boolean;\n timeout?: number;\n deps?: string[];\n after?: string[];\n };\n\n result[prefixKey(namespace, key)] = {\n ...constraintDef,\n deps: constraintDef.deps?.map((dep) => prefixKey(namespace, dep)),\n after: constraintDef.after?.map((dep) =>\n dep.includes(SEPARATOR) ? dep : prefixKey(namespace, dep),\n ),\n when: (facts: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n\n return constraintDef.when(factsProxy);\n },\n require:\n typeof constraintDef.require === \"function\"\n ? (facts: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n\n return (constraintDef.require as (facts: unknown) => unknown)(\n factsProxy,\n );\n }\n : constraintDef.require,\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix resolver keys and wrap resolve/resolveBatch/resolveBatchWithResults with scoped proxies */\nfunction prefixResolvers(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.resolvers) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, resolver] of Object.entries(mod.resolvers)) {\n const resolverDef = resolver as {\n requirement: string;\n resolve?: (\n req: unknown,\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<void>;\n resolveBatch?: (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<void>;\n resolveBatchWithResults?: (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<unknown>;\n key?: (req: unknown) => string;\n retry?: unknown;\n timeout?: number;\n };\n\n /** Wrap resolver ctx.facts with the module-scoped proxy */\n function wrapCtx(ctx: { facts: unknown; signal: AbortSignal }): {\n facts: unknown;\n signal: AbortSignal;\n } {\n return {\n facts: createScopedFactsProxy(\n ctx.facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n signal: ctx.signal,\n };\n }\n\n result[prefixKey(namespace, key)] = {\n ...resolverDef,\n ...(resolverDef.resolve && {\n resolve: async (\n req: unknown,\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n await resolverDef.resolve!(req, wrapCtx(ctx));\n },\n }),\n ...(resolverDef.resolveBatch && {\n resolveBatch: async (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n await resolverDef.resolveBatch!(reqs, wrapCtx(ctx));\n },\n }),\n ...(resolverDef.resolveBatchWithResults && {\n resolveBatchWithResults: async (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n return resolverDef.resolveBatchWithResults!(reqs, wrapCtx(ctx));\n },\n }),\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix effect keys and wrap run functions with scoped proxies */\nfunction prefixEffects(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.effects) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, effect] of Object.entries(mod.effects)) {\n const effectDef = effect as {\n // biome-ignore lint/suspicious/noExplicitAny: Effect run function type\n run: (facts: any, prev: any) => void | Promise<void>;\n deps?: string[];\n };\n\n result[prefixKey(namespace, key)] = {\n ...effectDef,\n // biome-ignore lint/suspicious/noExplicitAny: Effect run function wrapper\n run: (facts: any, prev: any) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n const prevProxy = prev\n ? createScopedFactsProxy(\n prev as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n )\n : undefined;\n\n return effectDef.run(factsProxy, prevProxy);\n },\n deps: effectDef.deps?.map((dep) => prefixKey(namespace, dep)),\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Compute history config with prefixed snapshot events */\nfunction prefixHistory(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n snapshotModulesSet: Set<string> | null,\n): { snapshotEvents?: string[] } {\n return {\n snapshotEvents:\n snapshotModulesSet && !snapshotModulesSet.has(namespace)\n ? [] // Module excluded from snapshots\n : mod.history?.snapshotEvents?.map((e: string) =>\n prefixKey(namespace, e),\n ),\n };\n}\n\n/**\n * Transform a module definition by prefixing all keys with a namespace.\n *\n * Handles: facts, derivations, events schema, init, derive, events handlers,\n * constraints (with deps/after), resolvers, and effects.\n *\n * @returns A flat module definition ready for the engine\n *\n * @internal\n */\nexport function prefixModuleDefinition(\n options: PrefixModuleOptions,\n): FlatModuleDefinition {\n const { mod, namespace, snapshotModulesSet } = options;\n\n // Compute cross-module deps info once (used by derive, constraints, effects)\n const hasCrossModuleDeps = !!(\n mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0\n );\n const depNamespaces = hasCrossModuleDeps\n ? Object.keys(mod.crossModuleDeps!)\n : [];\n\n return {\n id: mod.id,\n schema: prefixSchema(mod, namespace),\n requirements: mod.schema.requirements ?? {},\n init: prefixInit(mod, namespace),\n derive: prefixDerive(mod, namespace, hasCrossModuleDeps, depNamespaces),\n events: prefixEventHandlers(mod, namespace),\n effects: prefixEffects(mod, namespace, hasCrossModuleDeps, depNamespaces),\n constraints: prefixConstraints(\n mod,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n resolvers: prefixResolvers(\n mod,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n hooks: mod.hooks,\n meta: mod.meta,\n history: prefixHistory(mod, namespace, snapshotModulesSet),\n };\n}\n","/**\n * System - The top-level API for creating a Directive runtime\n *\n * A system combines modules with plugins and configuration.\n * Modules are passed as an object with namespaced access:\n *\n * @example\n * ```typescript\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n *\n * system.facts.auth.token // Namespaced facts\n * system.derive.data.userCount // Namespaced derivations\n * system.events.auth.login() // Namespaced events\n * ```\n */\n\nimport isDevelopment from \"#is-development\";\nimport { isPrototypeSafe } from \"../utils/utils.js\";\nimport { createEngine } from \"./engine.js\";\nimport { prefixModuleDefinition } from \"./system-module-transform.js\";\nimport {\n SEPARATOR,\n createNamespacedDeriveProxy,\n createNamespacedEventsProxy,\n createNamespacedFactsProxy,\n denormalizeFlatKeys,\n toInternalKey,\n} from \"./system-proxies.js\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type {\n CreateSystemOptionsNamed,\n CreateSystemOptionsSingle,\n ErrorBoundaryConfig,\n HistoryOption,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n SingleModuleSystem,\n TraceOption,\n} from \"./types.js\";\n\n// ============================================================================\n// Topological Sort for Module Dependencies\n// ============================================================================\n\n/**\n * Perform topological sort on modules based on crossModuleDeps.\n * Returns module namespaces in dependency order (dependencies first).\n *\n * @throws Error if circular dependency detected\n */\nfunction topologicalSort<Modules extends ModulesMap>(\n modulesMap: Modules,\n): Array<keyof Modules & string> {\n const namespaces = Object.keys(modulesMap) as Array<keyof Modules & string>;\n const namespacesSet = new Set<string>(namespaces);\n const visited = new Set<string>();\n const visiting = new Set<string>(); // For cycle detection\n const result: Array<keyof Modules & string> = [];\n const path: string[] = []; // Reuse array to avoid O(n²) memory\n\n function visit(namespace: string): void {\n if (visited.has(namespace)) return;\n\n // Cycle detection\n if (visiting.has(namespace)) {\n const cycleStart = path.indexOf(namespace);\n const cycle = [...path.slice(cycleStart), namespace].join(\" → \");\n throw new Error(\n `[Directive] Circular dependency detected: ${cycle}. ` +\n \"Modules cannot have circular crossModuleDeps. \" +\n \"Break the cycle by removing one of the cross-module references.\",\n );\n }\n\n visiting.add(namespace);\n path.push(namespace);\n\n // Visit dependencies first\n const mod = modulesMap[namespace];\n if (mod?.crossModuleDeps) {\n for (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n if (namespacesSet.has(depNamespace)) {\n visit(depNamespace);\n }\n }\n }\n\n path.pop();\n visiting.delete(namespace);\n visited.add(namespace);\n result.push(namespace as keyof Modules & string);\n }\n\n for (const namespace of namespaces) {\n visit(namespace);\n }\n\n return result;\n}\n\n/**\n * Build the list of internal prefixed keys (facts + derivations) for a module namespace.\n * Used by subscribe/subscribeModule to map namespaces to their engine keys.\n */\nfunction collectNamespaceKeys(\n namespace: string,\n mod: ModuleDef<ModuleSchema>,\n): string[] {\n const keys: string[] = [];\n for (const key of Object.keys(mod.schema.facts)) {\n keys.push(`${namespace}${SEPARATOR}${key}`);\n }\n if (mod.schema.derivations) {\n for (const key of Object.keys(mod.schema.derivations)) {\n keys.push(`${namespace}${SEPARATOR}${key}`);\n }\n }\n\n return keys;\n}\n\n// ============================================================================\n// createSystem\n// ============================================================================\n\n/**\n * Create a Directive system.\n *\n * Supports two modes:\n * - **Single module**: Use `module` prop for direct access without namespace\n * - **Multiple modules**: Use `modules` prop for namespaced access\n *\n * @remarks\n * The system is the top-level runtime object. It owns the reconciliation loop,\n * manages plugins, and exposes reactive accessors for facts, derivations, and events.\n * Call `system.start()` to begin the lifecycle (init → ready → running → settled).\n *\n * @param options - System configuration with either `module` (single) or `modules` (namespaced)\n * @returns A fully-typed {@link System} instance with reactive accessors\n *\n * @example Single module (direct access)\n * ```ts\n * const system = createSystem({ module: counterModule });\n * system.facts.count // Direct access\n * system.events.increment() // Direct events\n * ```\n *\n * @example Multiple modules (namespaced access)\n * ```ts\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n * system.facts.auth.token // Namespaced access\n * system.events.auth.login() // Namespaced events\n * ```\n *\n * @public\n */\nexport function createSystem<S extends ModuleSchema>(\n options: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S>;\nexport function createSystem<const Modules extends ModulesMap>(\n options: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules>;\n/** @internal Implementation overload — see public overloads above. */\nexport function createSystem<\n S extends ModuleSchema,\n Modules extends ModulesMap,\n>(\n options: CreateSystemOptionsSingle<S> | CreateSystemOptionsNamed<Modules>,\n): SingleModuleSystem<S> | NamespacedSystem<Modules> {\n // Single module mode (module prop)\n if (\"module\" in options) {\n if (!options.module) {\n throw new Error(\n \"[Directive] createSystem requires a module. Got: \" +\n typeof options.module,\n );\n }\n return createSingleModuleSystem(\n options as CreateSystemOptionsSingle<S>,\n ) as SingleModuleSystem<S>;\n }\n\n // Namespaced mode (modules prop)\n const namedOptions = options as CreateSystemOptionsNamed<Modules>;\n\n // Validate not an array\n if (Array.isArray(namedOptions.modules)) {\n throw new Error(\n \"[Directive] createSystem expects modules as an object, not an array.\\n\\n\" +\n \"Instead of:\\n\" +\n \" createSystem({ modules: [authModule, dataModule] })\\n\\n\" +\n \"Use:\\n\" +\n \" createSystem({ modules: { auth: authModule, data: dataModule } })\\n\\n\" +\n \"Or for a single module:\\n\" +\n \" createSystem({ module: counterModule })\",\n );\n }\n\n // Detect single ModuleDef accidentally passed to `modules:` instead of `module:`\n const mods = namedOptions.modules as Record<string, unknown>;\n if (mods && typeof mods === \"object\" && \"id\" in mods && \"schema\" in mods) {\n throw new Error(\n \"[Directive] A single module was passed to `modules:`. \" +\n \"For a single module, use `module:` instead:\\n\\n\" +\n \" createSystem({ module: myModule })\\n\\n\" +\n \"For multiple modules, wrap in an object:\\n\" +\n \" createSystem({ modules: { myName: myModule } })\",\n );\n }\n\n return createNamespacedSystem(namedOptions) as NamespacedSystem<Modules>;\n}\n\n// ============================================================================\n// Internal Implementation\n// ============================================================================\n\nfunction createNamespacedSystem<Modules extends ModulesMap>(\n options: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules> {\n const modulesMap = options.modules;\n const moduleNamespaces = new Set(Object.keys(modulesMap));\n\n // Build snapshot module filter set (null = all modules snapshot)\n const historyConfig =\n typeof options.history === \"object\" ? options.history : null;\n const snapshotModulesSet = historyConfig?.snapshotModules\n ? new Set(historyConfig.snapshotModules)\n : null;\n\n // Validate tickMs if provided\n if (options.tickMs !== undefined && options.tickMs <= 0) {\n throw new Error(\"[Directive] tickMs must be a positive number\");\n }\n\n // Dev-mode: Validate crossModuleDeps reference existing modules\n if (isDevelopment) {\n for (const [namespace, mod] of Object.entries(modulesMap)) {\n if (mod.crossModuleDeps) {\n for (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n if (depNamespace === namespace) {\n console.warn(\n `[Directive] Module \"${namespace}\" references itself in crossModuleDeps. ` +\n `Use \"facts.self\" to access own module's facts instead.`,\n );\n } else if (!moduleNamespaces.has(depNamespace)) {\n console.warn(\n `[Directive] Module \"${namespace}\" declares crossModuleDeps.${depNamespace}, ` +\n `but no module with namespace \"${depNamespace}\" exists in the system. ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n }\n }\n }\n }\n\n // Dev-mode: Validate snapshotModules references existing modules\n if (isDevelopment && historyConfig?.snapshotModules) {\n for (const name of historyConfig.snapshotModules) {\n if (!moduleNamespaces.has(name)) {\n console.warn(\n `[Directive] history.snapshotModules entry \"${name}\" doesn't match any module. ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n }\n }\n\n // Determine module initialization order\n let orderedNamespaces: Array<keyof Modules & string>;\n const initOrder = options.initOrder ?? \"auto\";\n\n if (Array.isArray(initOrder)) {\n // Explicit order provided - validate it includes all modules\n const explicitOrder = initOrder as Array<keyof Modules & string>;\n const missingModules = Object.keys(modulesMap).filter(\n (ns) => !explicitOrder.includes(ns as keyof Modules & string),\n );\n if (missingModules.length > 0) {\n throw new Error(\n `[Directive] initOrder is missing modules: ${missingModules.join(\", \")}. ` +\n \"All modules must be included in the explicit order.\",\n );\n }\n orderedNamespaces = explicitOrder;\n } else if (initOrder === \"declaration\") {\n // Use object key order (current behavior)\n orderedNamespaces = Object.keys(modulesMap) as Array<\n keyof Modules & string\n >;\n } else {\n // \"auto\" - use topological sort based on crossModuleDeps\n orderedNamespaces = topologicalSort(modulesMap);\n }\n\n // Apply zero-config defaults if enabled\n const { history, trace, errorBoundary } = applyZeroConfigDefaults(options);\n\n // Validate module names and schema keys don't contain the separator\n for (const namespace of Object.keys(modulesMap)) {\n if (namespace.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n `Module names cannot contain \"${SEPARATOR}\".`,\n );\n }\n const mod = modulesMap[namespace];\n if (mod) {\n for (const key of Object.keys(mod.schema.facts)) {\n if (key.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n `Schema keys cannot contain \"${SEPARATOR}\".`,\n );\n }\n }\n }\n }\n\n // Cached module names array, shared by all namespaced proxies.\n // Set to null on registerModule to lazily recompute.\n const moduleNamesCache: { names: string[] | null } = { names: null };\n function getModuleNames(): string[] {\n if (moduleNamesCache.names === null) {\n moduleNamesCache.names = Object.keys(modulesMap);\n }\n\n return moduleNamesCache.names;\n }\n\n // Transform modules to flat format with prefixed keys\n // auth.token → auth::token internally\n // Process in dependency order (determined above)\n const flatModules = orderedNamespaces\n .map((namespace) => {\n const mod = modulesMap[namespace];\n if (!mod) return null; // TypeScript guard - should never happen\n\n return prefixModuleDefinition({\n mod,\n namespace,\n snapshotModulesSet,\n });\n })\n .filter((m): m is NonNullable<typeof m> => m !== null);\n\n // Dev-mode warning: tickMs set without tick event handler\n if (\n isDevelopment &&\n options.tickMs &&\n options.tickMs > 0\n ) {\n const hasTickHandler = flatModules.some(\n (m) =>\n m.events &&\n Object.keys(m.events).some((k) => k.endsWith(`${SEPARATOR}tick`)),\n );\n if (!hasTickHandler) {\n console.warn(\n `[Directive] tickMs is set to ${options.tickMs}ms but no module defines a \"tick\" event handler.`,\n );\n }\n }\n\n // Store for hydrated facts (set by hydrate(), applied during init)\n let hydratedFacts: Record<string, Record<string, unknown>> | null = null;\n\n // Engine reference (set after creation, used by applyNamespacedFacts)\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n let engine: any = null;\n\n /**\n * Apply namespaced facts to the engine's flat store.\n * Converts { auth: { token: \"x\" } } to { \"auth::token\": \"x\" }\n * Includes prototype pollution protection.\n */\n function applyNamespacedFacts(\n namespacedFacts: Record<string, Record<string, unknown>>,\n ): void {\n for (const [namespace, facts] of Object.entries(namespacedFacts)) {\n // Skip blocked property names\n if (BLOCKED_PROPS.has(namespace)) {\n if (isDevelopment) {\n console.warn(\n `[Directive] initialFacts/hydrate contains blocked namespace \"${namespace}\". Skipping.`,\n );\n }\n continue;\n }\n\n if (!moduleNamespaces.has(namespace)) {\n if (isDevelopment) {\n console.warn(\n `[Directive] initialFacts/hydrate contains unknown namespace \"${namespace}\". ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n continue;\n }\n\n // Validate facts object for prototype pollution\n if (facts && typeof facts === \"object\" && !isPrototypeSafe(facts)) {\n throw new Error(\n `[Directive] initialFacts/hydrate for namespace \"${namespace}\" contains potentially ` +\n \"dangerous keys (__proto__, constructor, or prototype). This may indicate a \" +\n \"prototype pollution attack.\",\n );\n }\n\n for (const [key, value] of Object.entries(facts)) {\n // Skip blocked keys\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[\n `${namespace}${SEPARATOR}${key}`\n ] = value;\n }\n }\n }\n\n // Create engine with flat modules\n engine = createEngine({\n // biome-ignore lint/suspicious/noExplicitAny: Module format conversion\n modules: flatModules as any,\n plugins: options.plugins,\n history,\n trace,\n errorBoundary,\n tickMs: options.tickMs,\n cloud: options.cloud,\n // Callback to apply initialFacts/hydrate during init phase (after module inits, before reconcile)\n onAfterModuleInit: () => {\n // Apply initialFacts first\n if (options.initialFacts) {\n applyNamespacedFacts(\n options.initialFacts as Record<string, Record<string, unknown>>,\n );\n }\n // Apply hydrated facts second (takes precedence)\n if (hydratedFacts) {\n applyNamespacedFacts(hydratedFacts);\n hydratedFacts = null;\n }\n },\n });\n\n // Build namespace → internal keys map (for subscribeModule / wildcard support)\n const namespaceKeysMap = new Map<string, string[]>();\n for (const namespace of Object.keys(modulesMap)) {\n const mod = modulesMap[namespace];\n if (!mod) continue;\n namespaceKeysMap.set(namespace, collectNamespaceKeys(namespace, mod));\n }\n\n // Create namespaced proxies for external access\n const namespacedFactsProxy = createNamespacedFactsProxy(\n engine.facts as unknown as Record<string, unknown>,\n modulesMap,\n getModuleNames,\n );\n const namespacedDeriveProxy = createNamespacedDeriveProxy(\n engine.derive as unknown as Record<string, unknown>,\n modulesMap,\n getModuleNames,\n );\n const namespacedEventsProxy = createNamespacedEventsProxy(\n engine,\n modulesMap,\n getModuleNames,\n );\n\n // Build the namespaced system\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n const tickMs = options.tickMs;\n\n const system: NamespacedSystem<Modules> = {\n _mode: \"namespaced\",\n facts: namespacedFactsProxy,\n history: engine.history,\n derive: namespacedDeriveProxy,\n events: namespacedEventsProxy,\n constraints: engine.constraints,\n effects: engine.effects,\n resolvers: engine.resolvers,\n\n async hydrate(\n loader: () =>\n | Promise<Record<string, Record<string, unknown>>>\n | Record<string, Record<string, unknown>>,\n ) {\n if (engine.isRunning) {\n throw new Error(\n \"[Directive] hydrate() must be called before start(). \" +\n \"The system is already running.\",\n );\n }\n\n const result = await loader();\n if (result && typeof result === \"object\") {\n hydratedFacts = result;\n }\n },\n\n initialize(): void {\n engine.initialize();\n },\n\n start(): void {\n // Engine.start() runs module inits, then applies initialFacts/hydrate via callback\n engine.start();\n\n if (tickMs && tickMs > 0) {\n // Find the first module with a tick event and dispatch to it\n let tickEventKey: string | undefined;\n for (const m of flatModules) {\n if (m?.events) {\n tickEventKey = Object.keys(m.events).find((k) =>\n k.endsWith(`${SEPARATOR}tick`),\n );\n if (tickEventKey) break;\n }\n }\n if (tickEventKey) {\n const key = tickEventKey;\n tickInterval = setInterval(() => {\n engine.dispatch({ type: key });\n }, tickMs);\n }\n }\n },\n\n stop(): void {\n if (tickInterval) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n engine.stop();\n },\n\n destroy(): void {\n this.stop();\n engine.destroy();\n },\n\n dispatch(event: { type: string; [key: string]: unknown }) {\n engine.dispatch(event);\n },\n\n /**\n * Read a derivation value using namespaced syntax.\n * Accepts \"namespace.key\" format.\n *\n * @example\n * system.read(\"auth.status\") // → \"authenticated\"\n * system.read(\"data.count\") // → 5\n */\n read<T = unknown>(derivationId: string): T {\n return engine.read(toInternalKey(derivationId));\n },\n\n /**\n * Subscribe to derivation changes using namespaced syntax.\n * Accepts \"namespace.key\" format.\n * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n *\n * @example\n * system.subscribe([\"auth.status\", \"data.count\"], () => {\n * console.log(\"Auth or data changed\");\n * });\n *\n * @example Wildcard\n * system.subscribe([\"game.*\", \"chat.*\"], () => render());\n */\n subscribe(ids: string[], listener: () => void): () => void {\n const internalIds: string[] = [];\n for (const id of ids) {\n if (id.endsWith(\".*\")) {\n const ns = id.slice(0, -2);\n const keys = namespaceKeysMap.get(ns);\n if (keys) {\n internalIds.push(...keys);\n } else if (isDevelopment) {\n console.warn(\n `[Directive] subscribe wildcard \"${id}\" — namespace \"${ns}\" not found.`,\n );\n }\n } else {\n internalIds.push(toInternalKey(id));\n }\n }\n return engine.subscribe(internalIds, listener);\n },\n\n /**\n * Subscribe to ALL fact and derivation changes in a module namespace.\n * Shorthand for subscribing to every key in a module.\n *\n * @example\n * const unsub = system.subscribeModule(\"game\", () => render());\n */\n subscribeModule(namespace: string, listener: () => void): () => void {\n const keys = namespaceKeysMap.get(namespace);\n if (!keys || keys.length === 0) {\n if (isDevelopment) {\n console.warn(\n `[Directive] subscribeModule(\"${namespace}\") — namespace not found. ` +\n `Available: ${[...namespaceKeysMap.keys()].join(\", \")}`,\n );\n }\n return () => {};\n }\n return engine.subscribe(keys, listener);\n },\n\n /**\n * Watch a fact or derivation for changes using namespaced syntax.\n * The key is auto-detected -- works with both fact keys and derivation keys.\n * Accepts \"namespace.key\" format.\n *\n * @example\n * system.watch(\"auth.token\", (newVal, oldVal) => { ... }) // fact\n * system.watch(\"auth.status\", (newVal, oldVal) => { ... }) // derivation\n */\n watch<T = unknown>(\n id: string,\n callback: (newValue: T, previousValue: T | undefined) => void,\n options?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n ): () => void {\n return engine.watch(toInternalKey(id), callback, options);\n },\n\n /**\n * Returns a promise that resolves when the predicate becomes true.\n * The predicate receives namespaced facts (e.g., facts.auth.token).\n */\n when(\n predicate: (facts: Record<string, unknown>) => boolean,\n options?: { timeout?: number },\n ): Promise<void> {\n // Wrap predicate to provide namespaced facts view\n return engine.when(\n () =>\n predicate(namespacedFactsProxy as unknown as Record<string, unknown>),\n options,\n );\n },\n\n /**\n * Get a distributable snapshot with namespaced key translation.\n * Accepts \"namespace.key\" format in options (e.g., \"auth.effectivePlan\").\n * Returns data with namespaced keys (e.g., { auth: { effectivePlan: ... } }).\n */\n getDistributableSnapshot<T = Record<string, unknown>>(options?: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n }): {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n } {\n // Translate namespaced keys to internal format\n const internalOptions = {\n ...options,\n includeDerivations: options?.includeDerivations?.map(toInternalKey),\n excludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n includeFacts: options?.includeFacts?.map(toInternalKey),\n };\n\n const snapshot = engine.getDistributableSnapshot(internalOptions);\n\n // Transform data keys from internal format (auth::status) to namespaced format (auth: { status })\n return {\n ...snapshot,\n data: denormalizeFlatKeys(\n snapshot.data as Record<string, unknown>,\n ) as T,\n };\n },\n\n /**\n * Watch for changes to distributable snapshot derivations.\n * Accepts \"namespace.key\" format in options.\n * Callback receives data with namespaced keys.\n */\n watchDistributableSnapshot<T = Record<string, unknown>>(\n options: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n },\n callback: (snapshot: {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => void,\n ): () => void {\n // Translate namespaced keys to internal format\n const internalOptions = {\n ...options,\n includeDerivations: options?.includeDerivations?.map(toInternalKey),\n excludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n includeFacts: options?.includeFacts?.map(toInternalKey),\n };\n\n return engine.watchDistributableSnapshot(\n internalOptions,\n (snapshot: {\n data: Record<string, unknown>;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => {\n // Transform data keys from internal format to namespaced format\n callback({\n ...snapshot,\n data: denormalizeFlatKeys(\n snapshot.data as Record<string, unknown>,\n ) as T,\n });\n },\n );\n },\n registerModule(\n namespace: string,\n moduleDef: ModuleDef<ModuleSchema>,\n ): void {\n // Validate namespace\n if (moduleNamespaces.has(namespace)) {\n throw new Error(\n `[Directive] Module namespace \"${namespace}\" already exists. ` +\n \"Cannot register a duplicate namespace.\",\n );\n }\n if (namespace.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n );\n }\n if (BLOCKED_PROPS.has(namespace)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" is a blocked property.`,\n );\n }\n\n // Validate schema keys\n for (const key of Object.keys(moduleDef.schema.facts)) {\n if (key.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n );\n }\n }\n\n const mod = moduleDef;\n\n // Transform module definition with namespace prefixing\n const flat = prefixModuleDefinition({\n mod,\n namespace,\n snapshotModulesSet,\n });\n\n // Register namespace\n moduleNamespaces.add(namespace);\n (modulesMap as Record<string, ModuleDef<ModuleSchema>>)[namespace] = mod;\n // Invalidate cached module names so proxies see the new namespace\n moduleNamesCache.names = null;\n\n // Update namespace keys map\n namespaceKeysMap.set(namespace, collectNamespaceKeys(namespace, mod));\n\n // Delegate to engine's registerModule\n // biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n (engine as any).registerModule(flat);\n },\n\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for NamespacedSystem\n } as any;\n\n bindEnginePassthroughs(system, engine);\n warnIfNotStarted(system);\n\n return system;\n}\n\n// ============================================================================\n// Shared Helpers (deduplication between single-module and namespaced systems)\n// ============================================================================\n\n/**\n * Apply zero-config defaults to system options (history, trace, errorBoundary).\n * Returns the resolved values; does not mutate the options object.\n */\nfunction applyZeroConfigDefaults(options: {\n zeroConfig?: boolean;\n history?: HistoryOption;\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n}): {\n history: HistoryOption | undefined;\n trace: TraceOption | undefined;\n errorBoundary: ErrorBoundaryConfig | undefined;\n} {\n let history: HistoryOption | undefined = options.history;\n const trace: TraceOption | undefined = options.trace;\n let errorBoundary: ErrorBoundaryConfig | undefined = options.errorBoundary;\n\n if (options.zeroConfig) {\n const isDev = isDevelopment;\n\n history = history ?? isDev;\n\n errorBoundary = {\n onConstraintError: \"skip\",\n onResolverError: \"skip\",\n onEffectError: \"skip\",\n onDerivationError: \"skip\",\n ...options.errorBoundary,\n };\n }\n\n return { history, trace, errorBoundary };\n}\n\n/**\n * Bind shared engine passthrough properties and methods onto a system object.\n * These are identical between single-module and namespaced systems.\n *\n * For methods that namespaced systems override (dispatch, read, subscribe,\n * watch, when, getDistributableSnapshot, watchDistributableSnapshot),\n * only binds them if not already defined on the system object.\n */\nfunction bindEnginePassthroughs(\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n system: any,\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n engine: any,\n): void {\n Object.defineProperties(system, {\n trace: {\n get() {\n return engine.trace;\n },\n enumerable: true,\n configurable: true,\n },\n meta: {\n value: engine.meta,\n enumerable: true,\n configurable: true,\n },\n isRunning: {\n get() {\n return engine.isRunning;\n },\n enumerable: true,\n configurable: true,\n },\n isSettled: {\n get() {\n return engine.isSettled;\n },\n enumerable: true,\n configurable: true,\n },\n isInitialized: {\n get() {\n return engine.isInitialized;\n },\n enumerable: true,\n configurable: true,\n },\n isReady: {\n get() {\n return engine.isReady;\n },\n enumerable: true,\n configurable: true,\n },\n });\n\n system.whenReady = engine.whenReady.bind(engine);\n system.batch = engine.batch.bind(engine);\n system.onSettledChange = engine.onSettledChange.bind(engine);\n system.onHistoryChange = engine.onHistoryChange.bind(engine);\n system.inspect = engine.inspect.bind(engine);\n system.settle = engine.settle.bind(engine);\n system.explain = engine.explain.bind(engine);\n system.getSnapshot = engine.getSnapshot.bind(engine);\n system.restore = engine.restore.bind(engine);\n system.observe = engine.observe.bind(engine);\n\n // Direct engine passthroughs — only bind if not already defined\n // (namespaced systems override these with key-translating versions)\n const overridableMethods = [\n \"dispatch\",\n \"read\",\n \"subscribe\",\n \"watch\",\n \"when\",\n \"getDistributableSnapshot\",\n \"watchDistributableSnapshot\",\n ] as const;\n for (const method of overridableMethods) {\n if (!(method in system)) {\n system[method] = engine[method].bind(engine);\n }\n }\n}\n\n/**\n * Emit a dev-mode warning if system.start() is never called.\n */\nfunction warnIfNotStarted(\n // biome-ignore lint/suspicious/noExplicitAny: System type\n system: any,\n): void {\n if (\n isDevelopment &&\n process.env.NODE_ENV !== \"test\"\n ) {\n setTimeout(() => {\n if (!system.isRunning && !system.isInitialized) {\n console.warn(\n \"[Directive] System created but start() was never called. \" +\n \"Constraints, resolvers, and effects will not run until you call system.start().\",\n );\n }\n }, 0);\n }\n}\n\n// Proxy helpers and key conversion utilities are in system-proxies.ts\n\n// ============================================================================\n// Single Module System\n// ============================================================================\n\n/**\n * Create a system with a single module (no namespacing).\n * Facts, derivations, and events are accessed directly.\n */\nfunction createSingleModuleSystem<S extends ModuleSchema>(\n options: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S> {\n const mod = options.module;\n\n // Validate module is provided\n if (!mod) {\n throw new Error(\n \"[Directive] createSystem requires a module. Got: \" + typeof mod,\n );\n }\n\n // Validate tickMs if provided\n if (options.tickMs !== undefined && options.tickMs <= 0) {\n throw new Error(\"[Directive] tickMs must be a positive number\");\n }\n\n // Validate initialFacts for prototype pollution\n if (options.initialFacts && !isPrototypeSafe(options.initialFacts)) {\n throw new Error(\n \"[Directive] initialFacts contains potentially dangerous keys \" +\n \"(__proto__, constructor, or prototype). This may indicate a \" +\n \"prototype pollution attack.\",\n );\n }\n\n // Dev-mode warnings\n if (isDevelopment) {\n // Warn if crossModuleDeps is defined (ignored in single module mode)\n if (mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0) {\n console.warn(\n \"[Directive] Single module mode ignores crossModuleDeps. \" +\n \"Use multiple modules if cross-module access is needed: \" +\n \"createSystem({ modules: { ... } })\",\n );\n }\n\n // Warn if tickMs set without tick event handler\n if (options.tickMs && options.tickMs > 0) {\n const hasTickHandler = mod.events && \"tick\" in mod.events;\n if (!hasTickHandler) {\n console.warn(\n `[Directive] tickMs is set to ${options.tickMs}ms but module has no \"tick\" event handler.`,\n );\n }\n }\n\n // Warn if snapshotModules is set (has no effect in single-module mode)\n const singleHistoryConfig =\n typeof options.history === \"object\" ? options.history : null;\n if (singleHistoryConfig?.snapshotModules) {\n console.warn(\n \"[Directive] history.snapshotModules has no effect in single-module mode. \" +\n \"Use history.snapshotEvents on the module definition instead, or switch to \" +\n \"createSystem({ modules: { ... } }) for multi-module filtering.\",\n );\n }\n }\n\n // Apply zero-config defaults if enabled\n const { history, trace, errorBoundary } = applyZeroConfigDefaults(options);\n\n // Store for hydrated facts\n let hydratedFacts: Record<string, unknown> | null = null;\n\n // Engine reference\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n let engine: any = null;\n\n // Create engine with the module directly (no prefixing needed)\n engine = createEngine({\n modules: [\n {\n id: mod.id,\n schema: mod.schema.facts,\n requirements: mod.schema.requirements,\n init: mod.init,\n derive: mod.derive,\n events: mod.events,\n effects: mod.effects,\n constraints: mod.constraints,\n resolvers: mod.resolvers,\n hooks: mod.hooks,\n meta: mod.meta,\n history: mod.history,\n },\n // biome-ignore lint/suspicious/noExplicitAny: Module format\n ] as any,\n plugins: options.plugins,\n history,\n trace,\n errorBoundary,\n tickMs: options.tickMs,\n cloud: options.cloud,\n onAfterModuleInit: () => {\n // Apply initialFacts (already validated for prototype safety above)\n if (options.initialFacts) {\n for (const [key, value] of Object.entries(options.initialFacts)) {\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[key] = value;\n }\n }\n // Apply hydrated facts (takes precedence)\n if (hydratedFacts) {\n if (!isPrototypeSafe(hydratedFacts)) {\n if (isDevelopment) {\n console.warn(\n \"[Directive] hydrate() data contains potentially dangerous keys. Skipping.\",\n );\n }\n } else {\n for (const [key, value] of Object.entries(hydratedFacts)) {\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[key] = value;\n }\n }\n hydratedFacts = null;\n }\n },\n });\n\n // Create events proxy for direct access\n const eventsProxy = new Proxy(\n {} as Record<string, (payload?: Record<string, unknown>) => void>,\n {\n get(_, eventName: string | symbol) {\n if (typeof eventName === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(eventName)) {\n return undefined;\n }\n\n return (payload?: Record<string, unknown>) => {\n engine.dispatch({ type: eventName, ...payload });\n };\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return mod.events ? prop in mod.events : false;\n },\n ownKeys() {\n return mod.events ? Object.keys(mod.events) : [];\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n if (mod.events && prop in mod.events) {\n return { configurable: true, enumerable: true };\n }\n\n return undefined;\n },\n set() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n },\n );\n\n // Build the single module system\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n const tickMs = options.tickMs;\n\n const system: SingleModuleSystem<S> = {\n _mode: \"single\",\n facts: engine.facts,\n history: engine.history,\n derive: engine.derive,\n events: eventsProxy as SingleModuleSystem<S>[\"events\"],\n constraints: engine.constraints,\n effects: engine.effects,\n resolvers: engine.resolvers,\n\n async hydrate(\n loader: () => Promise<Record<string, unknown>> | Record<string, unknown>,\n ) {\n if (engine.isRunning) {\n throw new Error(\n \"[Directive] hydrate() must be called before start(). \" +\n \"The system is already running.\",\n );\n }\n\n const result = await loader();\n if (result && typeof result === \"object\") {\n hydratedFacts = result as Record<string, unknown>;\n }\n },\n\n initialize(): void {\n engine.initialize();\n },\n\n start(): void {\n engine.start();\n\n if (tickMs && tickMs > 0) {\n const hasTickHandler = mod.events && \"tick\" in mod.events;\n if (hasTickHandler) {\n tickInterval = setInterval(() => {\n engine.dispatch({ type: \"tick\" });\n }, tickMs);\n }\n }\n },\n\n stop(): void {\n if (tickInterval) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n engine.stop();\n },\n\n destroy(): void {\n this.stop();\n engine.destroy();\n },\n\n registerModule(moduleDef: ModuleDef<ModuleSchema>): void {\n // biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n (engine as any).registerModule({\n id: moduleDef.id,\n schema: moduleDef.schema.facts,\n requirements: moduleDef.schema.requirements,\n init: moduleDef.init,\n derive: moduleDef.derive,\n events: moduleDef.events,\n effects: moduleDef.effects,\n constraints: moduleDef.constraints,\n resolvers: moduleDef.resolvers,\n hooks: moduleDef.hooks,\n history: moduleDef.history,\n });\n },\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing\n } as any;\n\n bindEnginePassthroughs(system, engine);\n warnIfNotStarted(system);\n\n return system;\n}\n"]}
@@ -1,3 +0,0 @@
1
- import {f,l,k,i,j}from'./chunk-LN4YQDLL.js';import {c,b,a,e}from'./chunk-4CMO5OVZ.js';var we=class extends Error{constructor(j,S,I,m,h=true){super(j);this.source=S;this.sourceId=I;this.context=m;this.recoverable=h;this.name="DirectiveError";}};function Ze(){return {create(v){return v}}}function Ye(){return {create(v){return v}}}function Qe(v){return v}function et(v){return v}function vt(v){return v._mode==="single"}function yt(v){return v._mode==="namespaced"}function me(v){if(!v)return;let i=Object.assign(Object.create(null),v);return Array.isArray(i.tags)&&Object.freeze(i.tags),Object.freeze(i)}function xe(v){return typeof v=="object"&&v!==null&&Object.hasOwn(v,"compute")&&typeof v.compute=="function"}function tt(v){return typeof v=="boolean"?{enabled:v,maxSnapshots:100}:{enabled:true,maxSnapshots:v.maxSnapshots??100}}function Ae(v){let{historyOption:i,facts:j,store:S,onSnapshot:I,onHistoryChange:m}=v,{enabled:h,maxSnapshots:_}=tt(i),O=[],b=-1,B=1,A=false,U=false,T=[],x=null,k=-1;function H(){return S.toObject()}function W(){let L=H();try{return structuredClone(L)}catch{try{return JSON.parse(JSON.stringify(L))}catch{return {...L}}}}function te(L){if(!c(L)){console.error("[Directive] Potential prototype pollution detected in snapshot data, skipping restore");return}S.batch(()=>{for(let[V,Y]of Object.entries(L)){if(V==="__proto__"||V==="constructor"||V==="prototype"){console.warn(`[Directive] Skipping dangerous key "${V}" during fact restoration`);continue}j[V]=Y;}});}return {get isEnabled(){return h},get isRestoring(){return U},get isPaused(){return A},get snapshots(){return [...O]},get currentIndex(){return b},takeSnapshot(L){if(!h||A)return {id:-1,timestamp:Date.now(),facts:{},trigger:L};let V={id:B++,timestamp:Date.now(),facts:W(),trigger:L};for(b<O.length-1&&O.splice(b+1),O.push(V),b=O.length-1;O.length>_;)O.shift(),b--;return I?.(V),V},restore(L){if(h){A=true,U=true;try{te(L.facts);}finally{A=false,U=false;}}},goBack(L=1){if(!h||O.length===0)return;let V=b,Y=b,d=T.find(o=>b>o.startIndex&&b<=o.endIndex);if(d)Y=d.startIndex;else if(T.find(l=>b===l.startIndex)){let l=T.find(y=>y.endIndex<b&&b-y.endIndex<=L);Y=l?l.startIndex:Math.max(0,b-L);}else Y=Math.max(0,b-L);if(V===Y)return;b=Y;let f=O[b];f&&(this.restore(f),m?.(V,Y));},goForward(L=1){if(!h||O.length===0)return;let V=b,Y=b,d=T.find(o=>b>=o.startIndex&&b<o.endIndex);if(d?Y=d.endIndex:Y=Math.min(O.length-1,b+L),V===Y)return;b=Y;let f=O[b];f&&(this.restore(f),m?.(V,Y));},goTo(L){if(!h)return;let V=O.findIndex(f=>f.id===L);if(V===-1){console.warn(`[Directive] Snapshot ${L} not found`);return}let Y=b;b=V;let d=O[b];d&&(this.restore(d),m?.(Y,V));},replay(){if(!h||O.length===0)return;b=0;let L=O[0];L&&this.restore(L);},export(){return JSON.stringify({version:1,snapshots:O,currentIndex:b})},import(L){if(h)try{let V=JSON.parse(L);if(typeof V!="object"||V===null)throw new Error("[Directive] Invalid history data: expected object");if(V.version!==1)throw new Error(`[Directive] Unsupported history export version: ${V.version}`);if(!Array.isArray(V.snapshots))throw new Error("[Directive] Invalid history data: snapshots must be an array");if(typeof V.currentIndex!="number")throw new Error("Invalid history data: currentIndex must be a number");for(let d of V.snapshots){if(typeof d!="object"||d===null)throw new Error("[Directive] Invalid snapshot: expected object");if(typeof d.id!="number"||typeof d.timestamp!="number"||typeof d.trigger!="string"||typeof d.facts!="object")throw new Error("Invalid snapshot structure");if(!c(d.facts))throw new Error("[Directive] Invalid fact data: potential prototype pollution detected in nested objects")}O.length=0,O.push(...V.snapshots),b=V.currentIndex;let Y=O[b];Y&&this.restore(Y);}catch(V){console.error("[Directive] Failed to import history data:",V);}},beginChangeset(L){h&&(x=L,k=b);},endChangeset(){!h||x===null||(b>k&&T.push({label:x,startIndex:k,endIndex:b}),x=null,k=-1);},pause(){A=true;},resume(){A=false;}}}function je(){let v={id:-1,timestamp:0,facts:{},trigger:""};return {isEnabled:false,isRestoring:false,isPaused:false,snapshots:[],currentIndex:-1,takeSnapshot:()=>v,restore:()=>{},goBack:()=>{},goForward:()=>{},goTo:()=>{},replay:()=>{},export:()=>"{}",import:()=>{},beginChangeset:()=>{},endChangeset:()=>{},pause:()=>{},resume:()=>{}}}var $e=new WeakMap;function nt(v,i){if(i)return i(v);let j=$e.get(v);if(j!==void 0)return j;let{type:S,...I}=v,m=b(I),h=`${S}:${m}`;return $e.set(v,h),h}function Ie(v,i,j){return {requirement:v,id:nt(v,j),fromConstraint:i}}function Et(v){return i=>({type:v,...i})}function Mt(v,i){return v.type===i}function Ct(v){return i=>i.type===v}var be=class v{map=new Map;add(i){this.map.has(i.id)||this.map.set(i.id,i);}remove(i){return this.map.delete(i)}has(i){return this.map.has(i)}get(i){return this.map.get(i)}all(){return [...this.map.values()]}ids(){return [...this.map.keys()]}get size(){return this.map.size}clear(){this.map.clear();}clone(){let i=new v;for(let j of this.map.values())i.add(j);return i}diff(i){let j=[],S=[];for(let I of this.map.values())i.has(I.id)||j.push(I);for(let I of i.map.values())this.map.has(I.id)||S.push(I);return {added:j,removed:S}}};var rt=5e3;function Fe(v){let{definitions:i$1,facts:j,requirementKeys:S={},defaultTimeout:I=rt,onEvaluate:m,onError:h}=v,_=new Map,O=new Set,b=new Set,B=new Map,A=new Map,U=new Set,T=new Map,x=new Map,k=false,H=new Set,W=new Set,te=new Map,Q=[],L=new Map;function V(t,s){i$1[t]&&(te.has(t)||te.set(t,new Set),te.get(t).add(s));}function Y(){te.clear();for(let[t,s]of Object.entries(i$1))if(s.after)for(let u of s.after)V(u,t);}function d(t,s,u,q,F){if(u.has(t))return;if(q.has(t)){let de=s.indexOf(t),ge=[...s.slice(de),t].join(" \u2192 ");throw new Error(`[Directive] Constraint cycle detected: ${ge}. Remove one of the \`after\` dependencies to break the cycle.`)}q.add(t),s.push(t);let ne=i$1[t];if(ne?.after)for(let de of ne.after)i$1[de]&&d(de,s,u,q,F);s.pop(),q.delete(t),u.add(t),F.push(t);}function f$1(){let t=new Set,s=new Set,u=[];for(let q of Object.keys(i$1))d(q,[],t,s,u);Q=u,L=new Map(Q.map((q,F)=>[q,F]));}f$1(),Y();function o(){for(let[t,s]of Object.entries(i$1))if(s.after)for(let u of s.after)i$1[u]||console.warn(`[Directive] Constraint "${t}" references unknown constraint "${u}" in \`after\`. This dependency will be ignored. Check for typos or ensure the constraint exists.`);}f&&o();function l(t,s){return s.async!==void 0?s.async:!!b.has(t)}function y(t){let s=i$1[t];if(!s)throw new Error(`[Directive] Unknown constraint: ${t}`);let u=l(t,s);u&&b.add(t);let q={id:t,priority:s.priority??0,isAsync:u,lastResult:null,isEvaluating:false,error:null,lastResolvedAt:null,after:s.after??[],hitCount:0,lastActiveAt:null};return _.set(t,q),q}function P(t){return _.get(t)??y(t)}function J(t,s){if(t.size!==s.size||t.size===0)return false;for(let u of s)if(!t.has(u))return false;return true}function oe(t,s){for(let u of s){let q=A.get(u);q&&(q.delete(t),q.size===0&&A.delete(u));}}function pe(t,s){for(let u of s)A.has(u)||A.set(u,new Set),A.get(u).add(t);}function g(t){let s=B.get(t);s&&(oe(t,s),B.delete(t));}function C(t){te.delete(t);for(let s of te.values())s.delete(t);}function r(t,s){let u=B.get(t)??new Set;J(u,s)||(oe(t,u),pe(t,s),B.set(t,s));}function D(t,s){if(s.deps)return T.set(t,new Set(s.deps)),s.when(j);let u=i(()=>s.when(j));return T.set(t,u.deps),u.value}function z(t,s,u){s.lastResult=u,u&&(s.hitCount++,s.lastActiveAt=Date.now()),s.isEvaluating=false,m?.(t,u);}function ee(t,s,u){s.error=u instanceof Error?u:new Error(String(u)),s.lastResult=false,s.isEvaluating=false,h?.(t,u);}function ye(t,s,u){return b.add(t),s.isAsync=true,f&&console.warn(`[Directive] Constraint "${t}" returned a Promise but was not marked as async. Add \`async: true\` to the constraint definition to avoid this warning and improve performance.`),u.then(q=>(z(t,s,q),q)).catch(q=>(ee(t,s,q),false))}function ve(t){let s=i$1[t];if(!s)return false;let u=P(t);u.isEvaluating=true,u.error=null;try{let q=D(t,s);return q instanceof Promise?ye(t,u,q):(z(t,u,q),q)}catch(q){return ee(t,u,q),false}}async function he(t){let s=i$1[t];if(!s)return false;let u=P(t),q=s.timeout??I;if(u.isEvaluating=true,u.error=null,s.deps?.length){let F=new Set(s.deps);r(t,F),T.set(t,F);}try{let F=s.when(j),ne=await a(F,q,`Constraint "${t}" timed out after ${q}ms`);return u.lastResult=ne,ne&&(u.hitCount++,u.lastActiveAt=Date.now()),u.isEvaluating=!1,m?.(t,ne),ne}catch(F){return u.error=F instanceof Error?F:new Error(String(F)),u.lastResult=false,u.isEvaluating=false,h?.(t,F),false}}let Se=10;function Re(t,s){if(t==null)return [];if(Array.isArray(t)){let u=t.filter(q=>q!=null);return f&&u.length>Se&&s&&console.warn(`[Directive] Constraint "${s}" produced ${u.length} requirements. Consider splitting into multiple constraints for better performance.`),u}return [t]}function K(t){let s=i$1[t];if(!s)return {requirements:[],deps:new Set};let u=s.require;if(typeof u=="function"){let{value:F,deps:ne}=i(()=>u(j));return {requirements:Re(F,t),deps:ne}}return {requirements:Re(u,t),deps:new Set}}function re(t,s){if(s.size===0)return;let u=B.get(t)??new Set;for(let q of s)u.add(q);pe(t,s),B.set(t,u);}let ue=null;function a$1(){return ue||(ue=Object.keys(i$1).sort((t,s)=>{let u=P(t),F=P(s).priority-u.priority;if(F!==0)return F;let ne=L.get(t)??0,de=L.get(s)??0;return ne-de})),ue}for(let t of Object.keys(i$1))y(t);function p(t){for(let[s,u]of Object.entries(t))u.async&&!u.deps&&console.warn(`[Directive] Async constraint "${s}" has no \`deps\` declared. Auto-tracking cannot work across async boundaries. Add \`deps: ["key1", "key2"]\` to enable dependency tracking.`);}f&&p(i$1);function R(t){return !i$1[t]||O.has(t)||W.has(t)?true:H.has(t)}function $(t){let s=_.get(t);if(!s||s.after.length===0)return true;for(let u of s.after)if(!R(u))return false;return true}function N(t){let s=T.get(t);s!==void 0&&r(t,s),W.add(t),x.set(t,[]);}function X(t,s,u){if(s!==void 0){let q=new Set(s);for(let F of u)q.add(F);r(t,q);}else re(t,u);}function fe(t,s,u){if(s.length===0){x.set(t,[]);return}let q=s.map(F=>Ie(F,t,S[F.type]));for(let F of q)u.add(F);x.set(t,q);}function e(t,s){for(let u of t)s.add(u);}function n(t,s,u){if(O.has(t))return;if(!s){N(t);return}W.delete(t);let q=T.get(t),F,ne;try{let de=K(t);F=de.requirements,ne=de.deps;}catch(de){h?.(t,de),N(t);return}X(t,q,ne),fe(t,F,u);}function c(t,s){let u=[],q=[];for(let F of t){if($(F)){q.push(F);continue}u.push(F);let ne=x.get(F);ne&&e(ne,s);}return {blocked:u,ready:q}}function E(t,s){let u=[];for(let q of t){let F=ve(q);if(F instanceof Promise){u.push({id:q,promise:F});continue}n(q,F,s);}return u}async function M(t,s){let u=await Promise.all(t.map(async({id:q,promise:F})=>({id:q,active:await F})));for(let{id:q,active:F}of u)n(q,F,s);}async function w(t,s){let{blocked:u,ready:q}=c(t,s);if(q.length===0)return u;let F=[],ne=[];for(let ge of q)P(ge).isAsync?ne.push(ge):F.push(ge);let de=E(F,s);if(de.length>0&&await M(de,s),ne.length>0){let ge=ne.map(ke=>({id:ke,promise:he(ke)}));await M(ge,s);}return u}function G(t,s){for(let u of t){let q=A.get(u);if(q)for(let F of q)O.has(F)||s.add(F);}}function se(t){for(let s of U)O.has(s)||t.add(s);U.clear();}function ae(t){let s=new Set;return G(t,s),se(s),s}function Z(t,s,u){for(let q of t){if(s.has(q))continue;let F=x.get(q);F&&e(F,u);}}return {async evaluate(t){let s=new be;W.clear();let u=a$1(),q=O.size===0?u:u.filter(ge=>!O.has(ge)),F;if(!k||!t||t.size===0)F=q,k=true;else {let ge=ae(t);F=[...ge],Z(q,ge,s);}let ne=F,de=F.length+1;for(;ne.length>0&&de>0;){let ge=ne.length;if(ne=await w(ne,s),ne.length===ge)break;de--;}return s.all()},getState(t){return _.get(t)},getDependencies(t){return B.get(t)},getAllStates(){return [..._.values()]},disable(t){if(!_.has(t)){console.warn(`[Directive] constraints.disable("${t}") \u2014 no such constraint`);return}O.add(t),ue=null,x.delete(t),g(t),T.delete(t);},enable(t){if(!_.has(t)){console.warn(`[Directive] constraints.enable("${t}") \u2014 no such constraint`);return}O.delete(t),ue=null,U.add(t);},isDisabled(t){return O.has(t)},invalidate(t){let s=A.get(t);if(s)for(let u of s)U.add(u);},markResolved(t){H.add(t);let s=_.get(t);s&&(s.lastResolvedAt=Date.now());let u=te.get(t);if(u)for(let q of u)U.add(q);},isResolved(t){return H.has(t)},registerDefinitions(t){let s=false;for(let[u,q]of Object.entries(t))i$1[u]=q,y(u),U.add(u),q.after?.length&&(s=true);ue=null,s&&f$1(),Y();},assignDefinition(t,s){if(!i$1[t])throw new Error(`[Directive] Cannot assign constraint "${t}" \u2014 it does not exist. Use register() to create it.`);i$1[t]=s,y(t),U.add(t),ue=null,f$1(),Y();},unregisterDefinition(t){i$1[t]&&(delete i$1[t],_.delete(t),O.delete(t),b.delete(t),U.delete(t),W.delete(t),H.delete(t),x.delete(t),T.delete(t),g(t),C(t),ue=null,f$1(),Y());},async callOne(t,s){if(!i$1[t])throw new Error(`[Directive] Cannot call constraint "${t}" \u2014 it does not exist.`);if(O.has(t))return [];let q=P(t),F;if(q.isAsync)F=await he(t);else {let ge=ve(t);F=ge instanceof Promise?await ge:ge;}if(!F)return [];let{requirements:ne}=K(t);if(ne.length===0)return [];let de=[];for(let ge of ne){let ke=s?{...ge,...s}:ge;de.push(Ie(ke,t,S[ke.type]));}return de},setRequirementKey(t,s){S[t]=s;},removeRequirementKey(t){delete S[t];}}}function Ke(v){let{definitions:i$1,facts:j,onCompute:S,onInvalidate:I,onError:m}=v,h=3,_=new Map;for(let[g,C]of Object.entries(i$1))if(xe(C)){i$1[g]=C.compute;let r=me(C.meta);r&&_.set(g,r);}let O=new Map,b=new Map,B=new Map,A=new Map,U=0,T=new Set,x=false,k$1=100,H;function W(g,C){let r=O.has(g)?A:B,D=r.get(g);D?.delete(C),D&&D.size===0&&r.delete(g);}function te(g,C){let r=i$1[g]?A:B,D=r.get(g);D||(D=new Set,r.set(g,D)),D.add(C);}function Q(g){let C=O.get(g);if(C)for(let r of C.dependencies)W(r,g);}function L(g){let C=A.get(g);if(C){U++;try{for(let r of C)oe(r);}finally{U--;}A.delete(g);}}function V(g){delete i$1[g],O.delete(g),b.delete(g),T.delete(g),_.delete(g);}function Y(g){if(!i$1[g])throw new Error(`[Directive] Unknown derivation: ${g}`);let r={id:g,compute:()=>f(g),cachedValue:void 0,dependencies:new Set,isStale:true,isComputing:false,stableRunCount:0,depsStable:false};return O.set(g,r),r}function d(g){return O.get(g)??Y(g)}function f(g){let C=d(g),r=i$1[g];if(!r)throw new Error(`[Directive] Unknown derivation: ${g}`);if(C.isComputing)throw new Error(`[Directive] Circular dependency detected in derivation: ${g}`);C.isComputing=true;try{let D=C.cachedValue,z,ee;if(C.depsStable&&C.dependencies.size>0)z=r(j,H),ee=C.dependencies;else {let ye=i(()=>r(j,H));z=ye.value,ee=ye.deps,C.dependencies.size>0&&o(ee,C.dependencies)?(C.stableRunCount++,C.stableRunCount>=h&&(C.depsStable=!0)):C.stableRunCount=0;}return C.cachedValue=z,C.isStale=!1,l$1(g,ee),S&&S(g,z,D,[...ee]),z}catch(D){throw m?.(g,D),D}finally{C.isComputing=false;}}function o(g,C){if(g.size!==C.size)return false;for(let r of C)if(!g.has(r))return false;return true}function l$1(g,C){let r=d(g),D=r.dependencies;if(!o(D,C)){for(let z of D)W(z,g);for(let z of C)te(z,g);r.dependencies=C;}}function y(g){for(let C of g){let r=b.get(C);if(r)for(let D of r)D();}}function P(){if(!(U>0||x)){x=true;try{let g=0;for(;T.size>0;){if(++g>k$1){let r=[...T];throw T.clear(),new Error(`[Directive] Infinite derivation notification loop detected after ${k$1} iterations. Remaining: ${r.join(", ")}. This usually means a derivation listener is mutating facts that re-trigger the same derivation.`)}let C=[...T];T.clear(),y(C);}}finally{x=false;}}}function J(g,C){let r=A.get(g);if(r)for(let D of r)C.push(D);}function oe(g,C=new Set){let r=[g];for(;r.length>0;){let D=r.pop();if(C.has(D))continue;C.add(D);let z=O.get(D);!z||z.isStale||(z.isStale=true,z.depsStable=false,z.stableRunCount=0,I?.(D),T.add(D),J(D,r));}}return H=new Proxy({},{get(g,C){if(typeof C=="symbol"||l.has(C)||!i$1[C])return;k(C);let r=d(C);return r.isStale&&f(C),r.cachedValue},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),{get(g){let C=d(g);return C.isStale&&f(g),C.cachedValue},isStale(g){return O.get(g)?.isStale??true},invalidate(g){let C=B.get(g);if(!C)return;U++;let r=new Set;try{for(let D of C)oe(D,r);}finally{U--,P();}},invalidateMany(g){U++;let C=new Set;try{for(let r of g){let D=B.get(r);if(D)for(let z of D)oe(z,C);}}finally{U--,P();}},invalidateAll(){U++;try{for(let g of O.values())g.isStale||(g.isStale=!0,g.depsStable=!1,g.stableRunCount=0,T.add(g.id));}finally{U--,P();}},subscribe(g,C){for(let r of g){let D=r;b.has(D)||b.set(D,new Set),b.get(D).add(C);}return ()=>{for(let r of g){let D=r,z=b.get(D);z?.delete(C),z&&z.size===0&&b.delete(D);}}},getProxy(){return H},getDependencies(g){return d(g).dependencies},registerDefinitions(g){for(let[C,r]of Object.entries(g)){if(xe(r)){i$1[C]=r.compute;let D=me(r.meta);D&&_.set(C,D);}else i$1[C]=r;Y(C);}},assignDefinition(g,C){if(!i$1[g])throw new Error(`[Directive] Cannot assign derivation "${g}" \u2014 it does not exist. Use register() to create it.`);if(xe(C)){i$1[g]=C.compute;let D=me(C.meta);D?_.set(g,D):_.delete(g);}else i$1[g]=C;let r=O.get(g);r&&(r.isStale=true,r.depsStable=false,r.stableRunCount=0,T.add(g)),P();},unregisterDefinition(g){i$1[g]&&(Q(g),L(g),V(g),P());},getMeta(g){return _.get(g)},callOne(g){if(!i$1[g])throw new Error(`[Directive] Cannot call derivation "${g}" \u2014 it does not exist.`);return f(g)}}}var it=3;function _e(v){let{definitions:i$1,facts:j,store:S,onRun:I,onError:m}=v,h=new Map,_=null,O=false;function b(d){let f=i$1[d];if(!f)throw new Error(`[Directive] Unknown effect: ${d}`);let o={id:d,enabled:true,hasExplicitDeps:!!f.deps,dependencies:f.deps?new Set(f.deps):null,cleanup:null,stableRunCount:0,depsStable:false};return h.set(d,o),o}function B(d){return h.get(d)??b(d)}function A(){return S.toObject()}function U(d){d.depsStable=false,d.stableRunCount=0;}function T(d,f){for(let o of d)if(f.has(o))return true;return false}function x(d,f){let o=B(d);return o.enabled?o.dependencies?T(o.dependencies,f)?(o.depsStable&&U(o),true):false:true:false}function k(d){if(d.cleanup){try{d.cleanup();}catch(f){m?.(d.id,f),console.error(`[Directive] Effect "${d.id}" cleanup threw an error:`,f);}d.cleanup=null;}}function H(d,f){if(typeof f=="function")if(O)try{f();}catch(o){m?.(d.id,o),console.error(`[Directive] Effect "${d.id}" cleanup threw an error:`,o);}else d.cleanup=f;}async function W(d,f){let o;if(S.batch(()=>{o=f.run(j,_);}),o instanceof Promise){let l=await o;H(d,l);}else H(d,o);}function te(d,f){if(d.size!==f.size)return false;for(let o of f)if(!d.has(o))return false;return true}function Q(d,f){if(!(d.dependencies&&te(d.dependencies,f))){U(d);return}d.stableRunCount++,d.stableRunCount>=it&&(d.depsStable=true);}async function L(d,f){if(d.depsStable&&d.dependencies){await W(d,f);return}let o,l=i(()=>(S.batch(()=>{o=f.run(j,_);}),o)),y=l.deps,P=l.value;P instanceof Promise&&(P=await P),H(d,P),Q(d,y),d.dependencies=y.size>0?y:null;}async function V(d){let f=B(d),o=i$1[d];if(!(!f.enabled||!o)){k(f),I?.(d,f.dependencies?[...f.dependencies]:[]);try{f.hasExplicitDeps?await W(f,o):await L(f,o);}catch(l){m?.(d,l),console.error(`[Directive] Effect "${d}" threw an error:`,l),f.hasExplicitDeps||U(f);}}}for(let d of Object.keys(i$1))b(d);return {async runEffects(d){let f=[];for(let o of Object.keys(i$1))x(o,d)&&f.push(o);await Promise.all(f.map(V)),_=A();},async runAll(){let d=Object.keys(i$1);await Promise.all(d.map(f=>{let o=B(f);return o.enabled?(U(o),V(f)):Promise.resolve()})),_=A();},disable(d){let f=B(d);f.enabled=false;},enable(d){let f=B(d);f.enabled=true;},isEnabled(d){return B(d).enabled},cleanupAll(){O=true;for(let d of h.values())k(d);},registerDefinitions(d){for(let[f,o]of Object.entries(d))i$1[f]=o,b(f);},assignDefinition(d,f){if(!i$1[d])throw new Error(`[Directive] Cannot assign effect "${d}" \u2014 it does not exist. Use register() to create it.`);let o=h.get(d);o&&k(o),i$1[d]=f,b(d);},unregisterDefinition(d){if(!i$1[d])return;let f=h.get(d);f&&k(f),delete i$1[d],h.delete(d);},async callOne(d){let f=i$1[d];if(!f)throw new Error(`[Directive] Cannot call effect "${d}" \u2014 it does not exist.`);let o=B(d);if(o.enabled){k(o),I?.(d,o.dependencies?[...o.dependencies]:[]);try{let l;if(S.batch(()=>{l=f.run(j,_);}),l instanceof Promise){let y=await l;H(o,y);}else H(o,l);}catch(l){m?.(d,l),console.error(`[Directive] Effect "${d}" threw an error:`,l);}}}}}function st(v={}){let{delayMs:i=1e3,maxRetries:j=3,backoffMultiplier:S=2,maxDelayMs:I=3e4}=v,m=new Map;function h(_){let O=i*S**(_-1);return Math.min(O,I)}return {scheduleRetry(_,O,b,B,A){if(B>j)return null;let U=h(B),T={source:_,sourceId:O,context:b,attempt:B,nextRetryTime:Date.now()+U,callback:A};return m.set(O,T),T},getPendingRetries(){return Array.from(m.values())},processDueRetries(){let _=Date.now(),O=[];for(let[b,B]of m)B.nextRetryTime<=_&&(O.push(B),m.delete(b));return O},cancelRetry(_){m.delete(_);},clearAll(){m.clear();}}}var ot={constraint:"skip",resolver:"skip",effect:"skip",derivation:"skip",system:"throw"};function Be(v={}){let{config:i={},onError:j,onRecovery:S}=v,I=[],m=100,h=st(i.retryLater),_=new Map,O=1e3;function b(x,k,H,W){if(H instanceof we)return H;let te=H instanceof Error?H.message:String(H),Q=x!=="system";return new we(te,x,k,W,Q)}function B(x,k,H){let W=(()=>{switch(x){case "constraint":return i.onConstraintError;case "resolver":return i.onResolverError;case "effect":return i.onEffectError;case "derivation":return i.onDerivationError;default:return}})();if(typeof W=="function"){try{let te=W(H,k);if(typeof te=="string")return te}catch(te){console.error("[Directive] Error in error handler callback:",te);}return "skip"}return typeof W=="string"?W:ot[x]}function A(x){I.push(x),I.length>m&&I.shift();try{j?.(x);}catch(k){console.error("[Directive] Error in onError callback:",k);}try{i.onError?.(x);}catch(k){console.error("[Directive] Error in config.onError callback:",k);}}function U(x,k,H){let W=(_.get(k)??0)+1;if(_.set(k,W),_.size>O){let Q=_.keys().next().value;Q!==void 0&&_.delete(Q);}return h.scheduleRetry(x,k,H,W)?"retry-later":(_.delete(k),typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[Directive] ${x} "${k}" exceeded max retry-later attempts. Skipping.`),"skip")}return {handleError(x,k,H,W){let te=b(x,k,H,W);A(te);let Q=B(x,k,H instanceof Error?H:new Error(String(H)));Q==="retry-later"&&(Q=U(x,k,W));try{S?.(te,Q);}catch(L){console.error("[Directive] Error in onRecovery callback:",L);}if(Q==="throw")throw te;return Q},getLastError(){return I[I.length-1]??null},getAllErrors(){return [...I]},clearErrors(){I.length=0;},getRetryLaterManager(){return h},processDueRetries(){return h.processDueRetries()},clearRetryAttempts(x){_.delete(x),h.cancelRetry(x);}}}function at(v,i=100){try{return JSON.stringify(v)?.slice(0,i)??String(v)}catch{return "[circular or non-serializable]"}}function ct(v){let{schema:i,onChange:j,onBatch:S}=v,m=Object.keys(i).length===0,h=v.validate??f,_=v.strictKeys??(f&&!m),O=v.redactErrors??false,b=new Map,B=new Set,A=new Map,U=new Set,T=0,x=[],k$1=new Set,H=false,W=[],te=100;function Q(r){return r!==null&&typeof r=="object"&&"safeParse"in r&&typeof r.safeParse=="function"&&"_def"in r&&"parse"in r&&typeof r.parse=="function"}function L(r){let D=r;if(D._typeName)return D._typeName;if(Q(r)){let z=r._def;if(z?.typeName)return z.typeName.replace(/^Zod/,"").toLowerCase()}return "unknown"}function V(r){return O?"[redacted]":at(r)}function Y(r){return r===null?"null":Array.isArray(r)?"array":typeof r}function d(r,D,z){let ee=z.safeParse(D);if(ee.success)return;let ye=Y(D),ve=V(D),he=ee.error?.message??ee.error?.issues?.[0]?.message??"Validation failed",Se=L(z);throw new Error(`[Directive] Validation failed for "${r}": expected ${Se}, got ${ye} ${ve}. ${he}`)}function f$1(r){if(typeof r._lastFailedIndex=="number"&&r._lastFailedIndex>=0){let D=` (element at index ${r._lastFailedIndex} failed)`;return r._lastFailedIndex=-1,D}return ""}function o(r,D,z){let ee=z._validators;if(!ee||!Array.isArray(ee)||ee.length===0)return;let ye=z._typeName??"unknown";for(let ve=0;ve<ee.length;ve++){let he=ee[ve];if(typeof he!="function"||he(D))continue;let Se=Y(D),Re=V(D),K=f$1(z),re=ve===0?"":` (validator ${ve+1} failed)`;throw new Error(`[Directive] Validation failed for "${r}": expected ${ye}, got ${Se} ${Re}${re}${K}`)}}function l$1(r){if(_)throw new Error(`[Directive] Unknown fact key: "${r}". Key not defined in schema.`);console.warn(`[Directive] Unknown fact key: "${r}"`);}function y(r,D){if(!h)return;let z=i[r];if(!z){l$1(r);return}if(Q(z)){d(r,D,z);return}o(r,D,z);}function P(r){A.get(r)?.forEach(D=>D());}function J(){U.forEach(r=>r());}function oe(r,D,z){if(H){W.push({key:r,value:D,prev:z});return}H=true;try{j?.(r,D,z),P(r),J(),pe(". A listener is repeatedly mutating facts that re-trigger notifications");}finally{H=false;}}function pe(r){let D=0;for(;W.length>0;){if(++D>te)throw W.length=0,new Error(`[Directive] Infinite notification loop detected after ${te} iterations${r}.`);let z=[...W];W.length=0;for(let ee of z)j?.(ee.key,ee.value,ee.prev),P(ee.key);J();}}function g(){if(!(T>0)){if(S&&x.length>0&&S([...x]),k$1.size>0){H=true;try{for(let r of k$1)P(r);J(),pe(" during flush");}finally{H=false;}}x.length=0,k$1.clear();}}let C={get(r){return k(r),b.get(r)},has(r){return k(r),b.has(r)},set(r,D){f&&y(r,D);let z=b.get(r);Object.is(z,D)||(b.set(r,D),B.add(r),T>0?(x.push({key:r,value:D,prev:z,type:"set"}),k$1.add(r)):oe(r,D,z));},delete(r){let D=b.get(r);b.delete(r),B.delete(r),T>0?(x.push({key:r,value:void 0,prev:D,type:"delete"}),k$1.add(r)):oe(r,void 0,D);},batch(r){T++;try{r();}finally{T--,g();}},subscribe(r,D){for(let z of r){let ee=z;A.has(ee)||A.set(ee,new Set),A.get(ee).add(D);}return ()=>{for(let z of r){let ee=A.get(z);ee&&(ee.delete(D),ee.size===0&&A.delete(z));}}},subscribeAll(r){return U.add(r),()=>U.delete(r)},toObject(){let r={};for(let D of B)b.has(D)&&(r[D]=b.get(D));return r}};return C.destroy=()=>{A.clear(),U.clear();},C.registerKeys=r=>{for(let D of Object.keys(r))l.has(D)||(i[D]=r[D],B.add(D));},C}var Te=new WeakMap;function We(v,i,j=i){return new Proxy(v,{get(S,I){if(typeof I=="string"&&l.has(I))return;let m=Reflect.get(S,I);if(typeof I=="symbol"||typeof m!="object"||m===null)return m;if(Te.has(m))return Te.get(m);let h=We(m,i,`${j}.${String(I)}`);return Te.set(m,h),h},set(S,I,m){return typeof I!="symbol"&&console.warn(`[Directive] Nested mutation on "facts.${j}.${String(I)}" will not trigger reactivity. Use: facts.${i} = { ...facts.${i}, ... }`),Reflect.set(S,I,m)}})}function lt(v,i){let j$1=()=>({get:I=>j(()=>v.get(I)),has:I=>j(()=>v.has(I))});return new Proxy({},{get(I,m){if(typeof m=="symbol"||l.has(m))return;if(m==="$store")return v;if(m==="$snapshot")return j$1;let h=v.get(m);return f&&h!==null&&typeof h=="object"?We(h,m):h},set(I,m,h){return typeof m=="symbol"||m==="$store"||m==="$snapshot"||l.has(m)?false:(v.set(m,h),true)},deleteProperty(I,m){return typeof m=="symbol"||m==="$store"||m==="$snapshot"||l.has(m)?false:(v.delete(m),true)},has(I,m){return m==="$store"||m==="$snapshot"?true:typeof m=="symbol"||l.has(m)?false:v.has(m)},ownKeys(){return Object.keys(i)},getOwnPropertyDescriptor(I,m){return m==="$store"||m==="$snapshot"?{configurable:true,enumerable:false,writable:false}:{configurable:true,enumerable:true,writable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function ze(v){let i=ct(v),j=lt(i,v.schema);return {store:i,facts:j}}function Ne(){let v=[];function i(m){if(m)try{return m()}catch(h){console.error("[Directive] Plugin error:",h);return}}async function j(m){if(m)try{return await m()}catch(h){console.error("[Directive] Plugin error:",h);return}}function S(m){return (...h)=>{for(let _ of v)i(()=>_[m]?.(...h));}}return {register(m){v.some(h=>h.name===m.name)&&(console.warn(`[Directive] Plugin "${m.name}" is already registered, replacing...`),this.unregister(m.name)),v.push(m);},unregister(m){let h=v.findIndex(_=>_.name===m);h!==-1&&v.splice(h,1);},getPlugins(){return [...v]},async emitInit(m){for(let h of v)await j(()=>h.onInit?.(m));},emitStart:S("onStart"),emitStop:S("onStop"),emitDestroy:S("onDestroy"),emitFactSet:S("onFactSet"),emitFactDelete:S("onFactDelete"),emitFactsBatch:S("onFactsBatch"),emitDerivationCompute:S("onDerivationCompute"),emitDerivationInvalidate:S("onDerivationInvalidate"),emitReconcileStart:S("onReconcileStart"),emitReconcileEnd:S("onReconcileEnd"),emitConstraintEvaluate:S("onConstraintEvaluate"),emitConstraintError:S("onConstraintError"),emitRequirementCreated:S("onRequirementCreated"),emitRequirementMet:S("onRequirementMet"),emitRequirementCanceled:S("onRequirementCanceled"),emitResolverStart:S("onResolverStart"),emitResolverComplete:S("onResolverComplete"),emitResolverError:S("onResolverError"),emitResolverRetry:S("onResolverRetry"),emitResolverCancel:S("onResolverCancel"),emitEffectRun:S("onEffectRun"),emitEffectError:S("onEffectError"),emitSnapshot:S("onSnapshot"),emitHistoryNavigate:S("onHistoryNavigate"),emitError:S("onError"),emitErrorRecovery:S("onErrorRecovery"),emitDefinitionRegister:S("onDefinitionRegister"),emitDefinitionAssign:S("onDefinitionAssign"),emitDefinitionUnregister:S("onDefinitionUnregister"),emitDefinitionCall:S("onDefinitionCall"),emitTraceComplete:S("onTraceComplete")}}var He={attempts:1,backoff:"none",initialDelay:100,maxDelay:3e4},Le={enabled:false,windowMs:50};function ut(v,i){let{backoff:j,initialDelay:S=100,maxDelay:I=3e4}=v,m;switch(j){case "none":m=S;break;case "linear":m=S*i;break;case "exponential":m=S*2**(i-1);break;default:m=S;}return Math.max(1,Math.min(m,I))}function ft(v){if(f)for(let[i,j]of Object.entries(v)){if(!j.resolve&&!j.resolveBatch&&!j.resolveBatchWithResults)throw new Error(`[Directive] Resolver "${i}" must define either resolve() or resolveBatch(). Add one of these methods to handle requirements.`);if(!(!j.batch?.enabled||j.resolveBatch||j.resolveBatchWithResults))if(j.resolve)console.warn(`[Directive] Resolver "${i}" has batch.enabled but no resolveBatch(). Falling back to individual resolve() calls. Add resolveBatch() for true bulk operations.`);else throw new Error(`[Directive] Resolver "${i}" has batch.enabled=true but no resolve(), resolveBatch(), or resolveBatchWithResults() method.`)}}function Ve(v){let{definitions:i,facts:j,store:S,onStart:I,onComplete:m,onError:h,onRetry:_,onCancel:O,onResolutionComplete:b}=v;ft(i);let B=new Map,A=new Map,U=1e3,T=new Map,x=new Map,k=1e3;function H(){if(A.size>U){let a=A.size-U,p=A.keys();for(let R=0;R<a;R++){let $=p.next().value;$&&A.delete($);}}}function W(a){return typeof a=="object"&&a!==null&&"requirement"in a&&typeof a.requirement=="string"}function te(a){return typeof a=="object"&&a!==null&&"requirement"in a&&typeof a.requirement=="function"}function Q(a,p){return W(a)?p.type===a.requirement:te(a)?a.requirement(p):false}function L(a,p){let R=x.get(a);if(!R)return null;x.delete(a),x.set(a,R);for(let $ of R){let N=i[$];if(N&&Q(N,p))return $}return null}function V(a,p){if(!x.has(a)){if(x.size>=k){let R=x.keys().next().value;R!==void 0&&x.delete(R);}x.set(a,new Set);}x.get(a).add(p);}function Y(a){let p=a.type,R=L(p,a);if(R)return R;for(let[$,N]of Object.entries(i))if(Q(N,a))return V(p,$),$;return null}function d(a){return {facts:j,signal:a,snapshot:()=>j.$snapshot()}}async function f$1(a,p,R,$){let N=a instanceof Error?a:new Error(String(a));if($.signal.aborted)return {action:"abort",error:N};if(R.shouldRetry&&!R.shouldRetry(N,p))return {action:"break",error:N};if(p<R.attempts){if($.signal.aborted)return {action:"abort",error:N};let X=ut(R,p);if(await new Promise(fe=>{let e=setTimeout(fe,X),n=()=>{clearTimeout(e),fe();};$.signal.addEventListener("abort",n,{once:true});}),$.signal.aborted)return {action:"abort",error:N}}return {action:"continue",error:N}}async function o(a$1,p,R,$){if(!a$1.resolve)return;let N;S.batch(()=>{N=a$1.resolve(R.requirement,d($));});let X=a$1.timeout;if(X&&X>0){await a(N,X,`Resolver "${p}" timed out after ${X}ms`);return}await N;}function l(a,p,R){let $=Date.now()-R;A.set(p.id,{state:"success",requirementId:p.id,completedAt:Date.now(),duration:$}),H(),m?.(a,p,$);}function y(a,p,R,$){A.set(p.id,{state:"error",requirementId:p.id,error:R,failedAt:Date.now(),attempts:$}),H(),h?.(a,p,R);}function P(a,p,R){let $=B.get(a);$&&($.attempt=p,$.status={state:"running",requirementId:a,startedAt:R,attempt:p});}async function J(a,p,R,$,N){let X=await f$1(a,p,R,$);return X.action==="continue"&&p<R.attempts&&N(p+1),{lastError:X.error,shouldContinue:X.action==="continue"}}async function oe(a,p,R){let $=i[a];if(!$)return;let N={...He,...$.retry},X=null,fe=B.get(p.id)?.startedAt??Date.now();for(let e=1;e<=N.attempts;e++){if(R.signal.aborted)return;P(p.id,e,fe);try{await o($,a,p,R.signal),l(a,p,fe);return}catch(n){let c=await J(n,e,N,R,E=>_?.(a,p,E));if(X=c.lastError,!c.shouldContinue)break}}y(a,p,X,N.attempts);}async function pe(a$1,p,R){return p&&p>0?a(a$1,p,R):a$1}async function g(a,p,R,$,N,X,fe,e){let n;S.batch(()=>{n=a.resolveBatchWithResults($,N);});let c=await pe(n,X,`Batch resolver "${p}" timed out after ${X}ms`);if(c.length!==R.length)throw new Error(`[Directive] Batch resolver "${p}" returned ${c.length} results but expected ${R.length}. Results array must match input order.`);let E=false;for(let M=0;M<R.length;M++){let w=R[M],G=c[M];if(G.success){l(p,w,fe);continue}E=true;let se=G.error??new Error("Batch item failed");A.set(w.id,{state:"error",requirementId:w.id,error:se,failedAt:Date.now(),attempts:e}),h?.(p,w,se);}return !E||R.some((M,w)=>c[w]?.success)?"done":"retry"}async function C(a,p,R,$,N,X,fe){let e;S.batch(()=>{e=a.resolveBatch($,N);}),await pe(e,X,`Batch resolver "${p}" timed out after ${X}ms`);for(let n of R)l(p,n,fe);}function r(a,p,R,$){for(let N of p)y(a,N,R,$);}async function D(a,p){await Promise.all(p.map(R=>{let $=new AbortController;return oe(a,R,$)}));}async function z(a,p,R,$,N,X,fe){let e=d($),n=R.map(c=>c.requirement);return a.resolveBatchWithResults?g(a,p,R,n,e,N,X,fe):(await C(a,p,R,n,e,N,X),"done")}function ee(a,p,R){for(let $ of p)_?.(a,$,R);}async function ye(a,p,R,$,N){let X=new AbortController,fe=Date.now(),e=null;for(let n=1;n<=$.attempts;n++){if(X.signal.aborted)return null;try{if(await z(a,p,R,X.signal,N,fe,n)==="done")return null}catch(c){let E=await J(c,n,$,X,M=>ee(p,R,M));if(e=E.lastError,!E.shouldContinue)break}}return e}async function ve(a,p){let R=i[a];if(!R)return;if(!R.resolveBatch&&!R.resolveBatchWithResults){await D(a,p);return}let $={...He,...R.retry},X={...Le,...R.batch}.timeoutMs??R.timeout,fe=await ye(R,a,p,$,X);fe&&r(a,p,fe,$.attempts);}let he=1e4;function Se(a){a.timer&&(clearTimeout(a.timer),a.timer=null);}function Re(a){return T.has(a)||T.set(a,{resolverId:a,requirements:[],timer:null}),T.get(a)}function K(a,p){let R=i[a];if(!R)return;let $={...Le,...R.batch},N=Re(a),X=$.maxSize||he;if(N.requirements.length>=X&&(Se(N),re(a)),N.requirements.push(p),$.maxSize&&N.requirements.length>=$.maxSize){Se(N),re(a);return}Se(N),N.timer=setTimeout(()=>{re(a);},$.windowMs);}function re(a){let p=T.get(a);if(!p||p.requirements.length===0)return;let R=[...p.requirements];p.requirements=[],p.timer=null,ve(a,R).then(()=>{b?.();});}return {resolve(a){if(B.has(a.id))return;let p=Y(a.requirement);if(!p){f&&console.warn(`[Directive] No resolver found for requirement type "${a.requirement.type}" (id: ${a.id})`);return}let R=i[p];if(!R)return;if(R.batch?.enabled){K(p,a);return}let $=new AbortController,N=Date.now(),X={requirementId:a.id,resolverId:p,controller:$,startedAt:N,attempt:1,status:{state:"pending",requirementId:a.id,startedAt:N},originalRequirement:a};B.set(a.id,X),I?.(p,a),oe(p,a,$).finally(()=>{B.delete(a.id)&&b?.();});},cancel(a){let p=B.get(a);if(p){p.controller.abort(),B.delete(a),A.set(a,{state:"canceled",requirementId:a,canceledAt:Date.now()}),H(),O?.(p.resolverId,p.originalRequirement);return}for(let R of T.values()){let $=R.requirements.findIndex(N=>N.id===a);if($!==-1){let[N]=R.requirements.splice($,1);A.set(a,{state:"canceled",requirementId:a,canceledAt:Date.now()}),H(),N&&O?.(R.resolverId,N);return}}},cancelAll(){let a=[...B.keys()];for(let p of a)this.cancel(p);for(let p of T.values()){p.timer&&clearTimeout(p.timer);for(let R of p.requirements)A.set(R.id,{state:"canceled",requirementId:R.id,canceledAt:Date.now()}),O?.(p.resolverId,R);}T.clear(),H();},getStatus(a){let p=B.get(a);if(p)return p.status;let R=A.get(a);return R||{state:"idle"}},getInflight(){return [...B.keys()]},getInflightInfo(){return [...B.values()].map(a=>({id:a.requirementId,resolverId:a.resolverId,startedAt:a.startedAt}))},getInflightCount(){return B.size},isResolving(a){return B.has(a)},processBatches(){for(let a of T.keys())re(a);},hasPendingBatches(){for(let a of T.values())if(a.requirements.length>0)return true;return false},registerDefinitions(a){for(let[p,R]of Object.entries(a))i[p]=R;x.clear();},assignDefinition(a,p){if(!i[a])throw new Error(`[Directive] Cannot assign resolver "${a}" \u2014 it does not exist. Use register() to create it.`);i[a]=p,x.clear();},unregisterDefinition(a){if(!i[a])return;for(let[R,$]of B)$.resolverId===a&&($.controller.abort(),B.delete(R),A.set(R,{state:"canceled",requirementId:R,canceledAt:Date.now()}),O?.(a,$.originalRequirement));let p=T.get(a);if(p){p.timer&&clearTimeout(p.timer);for(let R of p.requirements)A.set(R.id,{state:"canceled",requirementId:R.id,canceledAt:Date.now()}),O?.(a,R);T.delete(a);}delete i[a],x.clear(),H();},async callOne(a,p){let R=i[a];if(!R)throw new Error(`[Directive] Cannot call resolver "${a}" \u2014 it does not exist.`);let $=new AbortController,N=d($.signal);if(R.resolve){let X;S.batch(()=>{X=R.resolve(p,N);}),await X;}},destroy(){this.cancelAll(),A.clear(),x.clear();}}}function Ue(v){let{mergedDerive:i,getDerivation:j,definitions:S}=v,I={register:(m,h)=>S.register("derivation",m,h),assign:(m,h)=>S.assign("derivation",m,h),unregister:m=>S.unregister("derivation",m),call:m=>S.call("derivation",m),isDynamic:m=>S.isDynamic("derivation",m),listDynamic:()=>S.listDynamic("derivation")};return new Proxy({},{get(m,h){if(typeof h!="symbol"&&!l.has(h)){if(h in I)return I[h];if(h in i)return j(h)}},has(m,h){return typeof h=="symbol"||l.has(h)?false:h in i||h in I},ownKeys(){return Object.keys(i)},getOwnPropertyDescriptor(m,h){if(typeof h!="symbol"&&!l.has(h)&&(h in i||h in I))return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function Xe(v){let{mergedEvents:i,dispatchEvent:j}=v;return new Proxy({},{get(S,I){if(typeof I!="symbol"&&!l.has(I))return m=>{j(I,m);}},has(S,I){return typeof I=="symbol"||l.has(I)?false:I in i},ownKeys(){return Object.keys(i)},getOwnPropertyDescriptor(S,I){if(typeof I!="symbol"&&!l.has(I)&&I in i)return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}var dt=new Set(["register","assign","unregister","call","isDynamic","listDynamic"]);function Je(v){let{mergedConstraints:i,mergedResolvers:j,mergedDerive:S,mergedEffects:I,constraintsManager:m,resolversManager:h,derivationsManager:_,effectsManager:O,pluginManager:b,getState:B,scheduleReconcile:A,maxDeferredRegistrations:U}=v,T={constraints:new Set,resolvers:new Set,derivations:new Set,effects:new Set},x={constraints:new Map,resolvers:new Map,derivations:new Map,effects:new Map},k=[];function H(f){if(dt.has(f))throw new Error(`[Directive] Derivation ID "${f}" conflicts with a reserved derive method name.`)}let W={constraint:{label:"Constraint",mergedMap:i,manager:m,dynamicSet:T.constraints,originalsMap:x.constraints,reconciles:true},resolver:{label:"Resolver",mergedMap:j,manager:h,dynamicSet:T.resolvers,originalsMap:x.resolvers,reconciles:true},derivation:{label:"Derivation",mergedMap:S,manager:_,dynamicSet:T.derivations,originalsMap:x.derivations,reconciles:false,validateId:H},effect:{label:"Effect",mergedMap:I,manager:O,dynamicSet:T.effects,originalsMap:x.effects,reconciles:false}};function te(f){if(typeof f!="string"||f.length===0)throw new Error(`[Directive] Definition ID must be a non-empty string. Received: ${String(f)}`);if(l.has(f))throw new Error(`[Directive] Security: Definition ID "${f}" is a blocked property.`);if(f.includes("::"))throw new Error(`[Directive] Definition ID "${f}" cannot contain "::". This separator is reserved for namespacing.`)}function Q(f,o,l){let y=W[f];if(y.validateId?.(o),o in y.mergedMap)throw new Error(`[Directive] ${y.label} "${o}" already exists. Use assign() to override.`);if(f!=="derivation"){let P=l;P.meta&&(P.meta=me(P.meta));}y.mergedMap[o]=l,y.manager.registerDefinitions({[o]:l}),y.dynamicSet.add(o),b.emitDefinitionRegister(f,o,l),y.reconciles&&A();}function L(f,o,l){let y=W[f];if(y.validateId?.(o),!(o in y.mergedMap))throw new Error(`[Directive] ${y.label} "${o}" does not exist. Use register() to create it.`);if(f!=="derivation"){let J=l;J.meta&&(J.meta=me(J.meta));}let P=y.mergedMap[o];y.manager.assignDefinition(o,l),y.originalsMap.set(o,P),y.mergedMap[o]=l,b.emitDefinitionAssign(f,o,l,P),y.reconciles&&A();}function V(f$1,o){let l=W[f$1];if(!l.dynamicSet.has(o)){f&&console.warn(`[Directive] Cannot unregister static ${f$1} "${o}". Only dynamically registered ${f$1}s can be removed.`);return}l.manager.unregisterDefinition(o),delete l.mergedMap[o],l.dynamicSet.delete(o),l.originalsMap.delete(o),b.emitDefinitionUnregister(f$1,o),l.reconciles&&A();}function Y(){if(k.length===0)return;let f$1=k.splice(0);for(let o of f$1)try{switch(o.op){case "register":Q(o.type,o.id,o.def);break;case "assign":L(o.type,o.id,o.def);break;case "unregister":V(o.type,o.id);break}}catch(l){f&&console.error(`[Directive] Error in deferred ${o.op} for ${o.type} "${o.id}":`,l);}}function d(f,o,l,y){let{isDestroyed:P,isReconciling:J}=B();if(P)throw new Error(`[Directive] Cannot ${f} ${o} "${l}" on a destroyed system.`);if(te(l),J){if(k.length>=U)throw new Error(`[Directive] Too many deferred registrations (max ${U}). Avoid calling register/assign/unregister in resolver or effect callbacks during reconciliation.`);f==="unregister"?k.push({op:f,type:o,id:l}):k.push({op:f,type:o,id:l,def:y});return}switch(f){case "register":Q(o,l,y);break;case "assign":L(o,l,y);break;case "unregister":V(o,l);break}}return {register(f,o,l){d("register",f,o,l);},assign(f,o,l){d("assign",f,o,l);},unregister(f,o){d("unregister",f,o);},call(f,o,l){let{isDestroyed:y}=B();if(y)throw new Error(`[Directive] Cannot call ${f} "${o}" on a destroyed system.`);switch(te(o),b.emitDefinitionCall(f,o,l),f){case "constraint":return m.callOne(o,l);case "resolver":return h.callOne(o,l);case "derivation":return _.callOne(o);case "effect":return O.callOne(o)}},isDynamic(f,o){switch(f){case "constraint":return T.constraints.has(o);case "resolver":return T.resolvers.has(o);case "derivation":return T.derivations.has(o);case "effect":return T.effects.has(o)}},listDynamic(f){switch(f){case "constraint":return [...T.constraints];case "resolver":return [...T.resolvers];case "derivation":return [...T.derivations];case "effect":return [...T.effects]}},flushDeferred:Y,getOriginal(f,o){let y={constraint:x.constraints,resolver:x.resolvers,derivation:x.derivations,effect:x.effects}[f];if(y)return y.get(o)},restoreOriginal(f,o){let y={constraint:x.constraints,resolver:x.resolvers,derivation:x.derivations,effect:x.effects}[f];if(!y||!y.has(o))return false;let P=y.get(o);return d("assign",f,o,P),y.delete(o),true},destroy(){k.length=0,T.constraints.clear(),T.resolvers.clear(),T.derivations.clear(),T.effects.clear(),x.constraints.clear(),x.resolvers.clear(),x.derivations.clear(),x.effects.clear();}}}function Ge(v){let{traceConfig:i,pluginManager:j,resolverMetaLookup:S}=v;if(!(i===true||typeof i=="object"&&i!==null))return {enabled:false,recordFactChange(){},startRun(){return 0},currentTrace:null,getEntries(){return null},attributeResolverStart(){},recordResolverComplete(){},recordResolverError(){},decrementInflight(){},finalizeCurrentRun(){},drainPendingChanges(){},destroy(){}};let m=(typeof i=="object"&&i!==null?i.maxRuns:void 0)??100,h=[],_=new Map,O=0,b=null,B=[],A=new Map,U=new Map,T=new Map,x=null,k=0,H=0,W={count:0,totalDuration:0,avgDuration:0,maxDuration:0,avgResolverCount:0,totalResolverCount:0,avgFactChangeCount:0,totalFactChangeCount:0};function te(l){let y=_.get(l);if(y&&y.status==="pending"){y.status="settled";let P=T.get(l);y.duration=P!==void 0?performance.now()-P:Date.now()-y.timestamp,T.delete(l),U.delete(l),y.causalChain=V(y),Y(y),H++,j.emitTraceComplete(y);}}function Q(l){let y=A.get(l);if(A.delete(l),y!==void 0){let P=(U.get(y)??1)-1;P<=0?te(y):U.set(y,P);}}function L(){let l=h.shift();if(l&&(_.delete(l.id),T.delete(l.id),l.status==="pending")){U.delete(l.id);for(let[y,P]of A)P===l.id&&A.delete(y);}}function V(l){let y=[];for(let P of l.factChanges)y.push(`${P.key} changed`);for(let P of l.derivationsRecomputed)y.push(`${P.id} recomputed`);for(let P of l.constraintsHit)y.push(`${P.id} constraint hit`);for(let P of l.requirementsAdded)y.push(`${P.type} requirement added`);for(let P of l.resolversCompleted)y.push(`${P.resolver} resolved (${P.duration.toFixed(0)}ms)`);for(let P of l.resolversErrored)y.push(`${P.resolver} errored`);for(let P of l.effectsRun)y.push(`${P.id} effect ran`);return y.join(" \u2192 ")}function Y(l){W.count++,W.totalDuration+=l.duration,W.avgDuration=W.totalDuration/W.count,l.duration>W.maxDuration&&(W.maxDuration=l.duration);let y=l.resolversStarted.length;W.totalResolverCount+=y,W.avgResolverCount=W.totalResolverCount/W.count;let P=l.factChanges.length;W.totalFactChangeCount+=P,W.avgFactChangeCount=W.totalFactChangeCount/W.count;let J=[];W.count>3&&l.duration>W.avgDuration*5&&J.push(`Duration ${l.duration.toFixed(0)}ms is 5x+ above average (${W.avgDuration.toFixed(0)}ms)`),l.resolversErrored.length>0&&J.push(`${l.resolversErrored.length} resolver(s) errored`),J.length>0&&(l.anomalies=J);}function d(l){h.push(l),_.set(l.id,l),h.length>m&&L(),H++;}function f(l){return l.factChanges.length>0||l.constraintsHit.length>0||l.requirementsAdded.length>0||l.effectsRun.length>0}return {enabled:true,get currentTrace(){return b},set currentTrace(l){b=l;},recordFactChange(l,y,P){B.push({key:l,oldValue:y,newValue:P});},startRun(){let l=performance.now(),y=++O;return T.set(y,l),b={id:y,timestamp:Date.now(),duration:0,status:"pending",factChanges:B.splice(0),derivationsRecomputed:[],constraintsHit:[],requirementsAdded:[],requirementsRemoved:[],resolversStarted:[],resolversCompleted:[],resolversErrored:[],effectsRun:[],effectErrors:[]},l},getEntries(){return (!x||k!==H)&&(x=[...h],k=H),x},attributeResolverStart(l){b&&A.set(l,b.id);},recordResolverComplete(l,y,P){let J=A.get(l);if(J!==void 0){let oe=_.get(J);oe&&oe.resolversCompleted.push({resolver:y,requirementId:l,duration:P,meta:S?.(y)});}},recordResolverError(l,y,P){let J=A.get(l);if(J!==void 0){let oe=_.get(J);oe&&oe.resolversErrored.push({resolver:y,requirementId:l,error:P,meta:S?.(y)});}},decrementInflight(l){Q(l);},finalizeCurrentRun(l){if(!b)return;if(b.duration=performance.now()-l,!f(b)){T.delete(b.id),b=null;return}let y=b.resolversStarted.length;y===0?(b.status="settled",b.causalChain=V(b),Y(b),d(b),j.emitTraceComplete(b)):(b.status="pending",d(b),U.set(b.id,y)),b=null;},drainPendingChanges(){B.length=0;},destroy(){h.length=0,_.clear(),A.clear(),U.clear(),T.clear(),B.length=0,b=null,x=null;}}}function hn(v){let i=Object.create(null),j=Object.create(null),S=Object.create(null),I=Object.create(null),m=Object.create(null),h=Object.create(null),_=new Map,O=new Map,b=new Map,B=new Map;for(let e of v.modules){let n=(E,M)=>{if(E)for(let w of Object.keys(E)){if(l.has(w))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${w}" in ${M}. This could indicate a prototype pollution attempt.`);if(M==="schema"&&w.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${w}" starting with "$". Keys starting with $ are reserved for internal accessors ($store, $snapshot).`)}};n(e.schema,"schema"),n(e.events,"events"),n(e.derive,"derive"),n(e.effects,"effects"),n(e.constraints,"constraints"),n(e.resolvers,"resolvers");for(let E of Object.keys(e.schema)){let M=b.get(E);if(M)throw new Error(`[Directive] Schema collision: Fact "${E}" is defined in both module "${M}" and "${e.id}". Use namespacing (e.g., "${e.id}::${E}") or merge into one module.`);b.set(E,e.id);}let c=(E,M)=>{if(E)for(let w of Object.keys(E)){let G=B.get(w);if(G&&G!==e.id)throw new Error(`[Directive] Definition collision: ${M} "${w}" is defined in both module "${G}" and "${e.id}". Use namespacing or rename to avoid conflicts.`);B.set(w,e.id);}};if(c(e.derive,"derivation"),c(e.effects,"effect"),c(e.constraints,"constraint"),c(e.resolvers,"resolver"),c(e.events,"event"),Object.assign(i,e.schema),e.events){for(let[E,M]of Object.entries(e.events))if(typeof M=="object"&&M!==null&&Object.hasOwn(M,"handler")){let w=M;if(e.events[E]=w.handler,w.meta){let G=me(w.meta);G&&O.set(E,G);}}Object.assign(j,e.events);}if(e.derive&&Object.assign(S,e.derive),e.effects&&Object.assign(I,e.effects),e.constraints&&Object.assign(m,e.constraints),e.resolvers&&Object.assign(h,e.resolvers),e.meta){let E=me(e.meta);E&&_.set(e.id,E);}}for(let e of Object.values(m))e.meta&&(e.meta=me(e.meta));for(let e of Object.values(h))e.meta&&(e.meta=me(e.meta));for(let e of Object.values(I)){let n=e;n.meta&&(n.meta=me(n.meta));}for(let e of Object.values(i)){let n=e;n._meta&&(n._meta=me(n._meta));}let A=null;if(v.modules.some(e=>e.history?.snapshotEvents)){A=new Set;for(let e of v.modules){let n=e;if(n.history?.snapshotEvents)for(let c of n.history.snapshotEvents)A.add(c);else if(n.events)for(let c of Object.keys(n.events))A.add(c);}}let T=0,x=false;if(f){let e=new Set(Object.keys(S));for(let n of Object.keys(i))e.has(n)&&console.warn(`[Directive] "${n}" exists as both a fact and a derivation. This may cause unexpected dependency tracking behavior.`);}let k=Ne();for(let e of v.plugins??[])k.register(e);let H=k.getPlugins().length>0,W=k.register.bind(k),te=k.unregister.bind(k);k.register=e=>{W(e),H=true;},k.unregister=e=>{te(e),H=k.getPlugins().length>0;};let Q=()=>H,L=Be({config:v.errorBoundary,onError:e=>k.emitError(e),onRecovery:(e,n)=>k.emitErrorRecovery(e,n)}),V=null,Y=()=>{},d=()=>{},f$1=null,o=Ge({traceConfig:v.trace,pluginManager:k,resolverMetaLookup:e=>h[e]?.meta}),l$1=o.enabled,{store:y,facts:P}=ze({schema:i,onChange:(e,n,c)=>{k.emitFactSet(e,n,c),Y(e),l$1&&o.recordFactChange(String(e),c,n),!f$1?.isRestoring&&(T===0&&(x=true),K.changedKeys.add(e),ue());},onBatch:e=>{k.emitFactsBatch(e);let n=[];for(let c of e)n.push(c.key);if(l$1)for(let c of e)o.recordFactChange(c.key,c.prev,c.type==="delete"?void 0:c.value);if(d(n),!f$1?.isRestoring){T===0&&(x=true);for(let c of e)K.changedKeys.add(c.key);ue();}}}),J=Ke({definitions:S,facts:P,onCompute:(e,n,c,E)=>{Q()&&k.emitDerivationCompute(e,n,E),o.currentTrace&&o.currentTrace.derivationsRecomputed.push({id:e,deps:E?[...E]:[],oldValue:c,newValue:n,meta:J.getMeta(e)});},onInvalidate:e=>{Q()&&k.emitDerivationInvalidate(e);},onError:(e,n)=>{L.handleError("derivation",e,n)==="retry"&&J.invalidate(e);}});Y=e=>J.invalidate(e),d=e=>J.invalidateMany(e);let oe=_e({definitions:I,facts:P,store:y,onRun:(e,n)=>{Q()&&k.emitEffectRun(e),o.currentTrace&&o.currentTrace.effectsRun.push({id:e,triggeredBy:n,meta:I[e]?.meta});},onError:(e,n)=>{let c=L.handleError("effect",e,n);Q()&&k.emitEffectError(e,n),o.currentTrace&&o.currentTrace.effectErrors.push({id:e,error:String(n),meta:I[e]?.meta}),c==="disable"&&oe.disable(e),c==="retry"&&(K.changedKeys.add("*"),ue());}}),pe=Object.create(null);for(let e of Object.values(h))e.key&&typeof e.requirement=="string"&&(pe[e.requirement]=e.key);let g=Fe({definitions:m,facts:P,requirementKeys:pe,onEvaluate:(e,n)=>{Q()&&k.emitConstraintEvaluate(e,n);},onError:(e,n)=>{let c=L.handleError("constraint",e,n);Q()&&k.emitConstraintError(e,n),c==="disable"&&g.disable(e);}});function C(e){for(let n of Object.values(e))n.key&&typeof n.requirement=="string"&&g.setRequirementKey(n.requirement,n.key);}let r=Ve({definitions:h,facts:P,store:y,onStart:(e,n)=>{Q()&&k.emitResolverStart(e,n);},onComplete:(e,n,c)=>{L.clearRetryAttempts(e),Q()&&(k.emitResolverComplete(e,n,c),k.emitRequirementMet(n,e)),g.markResolved(n.fromConstraint),l$1&&(o.recordResolverComplete(n.id,e,c),o.decrementInflight(n.id));},onError:(e,n,c)=>{let E=L.handleError("resolver",e,c,n);if(Q()&&k.emitResolverError(e,n,c),E==="disable"&&g.disable(n.fromConstraint),E==="retry"&&(K.previousRequirements.remove(n.id),ue()),E==="retry-later"){let w=L.getRetryLaterManager().getPendingRetries().find(G=>G.sourceId===e);w&&!w.callback&&(w.callback=()=>{ue();});}l$1&&(o.recordResolverError(n.id,e,String(c)),o.decrementInflight(n.id));},onRetry:(e,n,c)=>k.emitResolverRetry(e,n,c),onCancel:(e,n)=>{k.emitResolverCancel(e,n),k.emitRequirementCanceled(n),l$1&&o.decrementInflight(n.id);},onResolutionComplete:()=>{ve(),ue();}}),D=new Set;function z(){for(let e of D)e();}let ee=v.history?Ae({historyOption:v.history,facts:P,store:y,onSnapshot:e=>{k.emitSnapshot(e),z();},onHistoryChange:(e,n)=>{k.emitHistoryNavigate(e,n),z();}}):je();f$1=ee;let ye=new Set;function ve(){for(let e of ye)e();}let he=50,Se=100,Re=0,K={isRunning:false,isReconciling:false,reconcileScheduled:false,isInitializing:false,isInitialized:false,isReady:false,isDestroyed:false,changedKeys:new Set,previousRequirements:new be,readyPromise:null,readyResolve:null},re=Je({mergedConstraints:m,mergedResolvers:h,mergedDerive:S,mergedEffects:I,constraintsManager:g,resolversManager:r,derivationsManager:J,effectsManager:oe,pluginManager:k,getState:()=>K,scheduleReconcile:ue,maxDeferredRegistrations:Se});function ue(){!K.isRunning||K.reconcileScheduled||K.isInitializing||(K.reconcileScheduled=true,ve(),queueMicrotask(()=>{K.reconcileScheduled=false,K.isRunning&&!K.isInitializing&&a().catch(e=>{f&&console.error("[Directive] Unexpected error in reconcile:",e);});}));}async function a(){if(K.isReconciling)return;if(Re++,Re>he){f&&console.warn(`[Directive] Reconcile loop exceeded ${he} iterations. This usually means resolvers are creating circular requirement chains. Check that resolvers aren't mutating facts that re-trigger their own constraints.`),l$1&&o.drainPendingChanges(),K.previousRequirements=new be,Re=0;return}K.isReconciling=true,ve();let e=l$1?o.startRun():0,n=o.currentTrace;if(n)for(let c of n.factChanges){let E=i[c.key];c.meta=E?._meta;}try{if(K.changedKeys.size>0){if(A===null||x){let Z=K.changedKeys,ce=Z.size<=5?`facts-changed:${[...Z].join(",")}`:`facts-changed:${[...Z].slice(0,5).join(",")}+${Z.size-5}more`;ee.takeSnapshot(ce);}x=!1;}let c=P.$snapshot();k.emitReconcileStart(c),await oe.runEffects(K.changedKeys);let E=new Set(K.changedKeys);K.changedKeys.clear();let M=await g.evaluate(E),w=new be;for(let Z of M)w.add(Z),k.emitRequirementCreated(Z);if(n){let Z=new Set(M.map(ce=>ce.fromConstraint));for(let ce of Z){let t=g.getState(ce);if(t){let s=g.getDependencies(ce);n.constraintsHit.push({id:ce,priority:t.priority,deps:s?[...s]:[],meta:m[ce]?.meta});}}}let{added:G,removed:se}=w.diff(K.previousRequirements);if(n){for(let Z of G)n.requirementsAdded.push({id:Z.id,type:Z.requirement.type,fromConstraint:Z.fromConstraint});for(let Z of se)n.requirementsRemoved.push({id:Z.id,type:Z.requirement.type,fromConstraint:Z.fromConstraint});}for(let Z of se)r.cancel(Z.id);for(let Z of G)r.resolve(Z);if(n){let Z=r.getInflightInfo(),ce=new Map(Z.map(t=>[t.id,t]));for(let t of G){let u=ce.get(t.id)?.resolverId??"unknown";n.resolversStarted.push({resolver:u,requirementId:t.id,meta:h[u]?.meta}),o.attributeResolverStart(t.id);}}K.previousRequirements=w;let ae=r.getInflightInfo();if(v.plugins&&v.plugins.length>0){let Z=se.length>0?new Map(ae.map(t=>[t.id,t.resolverId])):void 0,ce={unmet:M.filter(t=>!r.isResolving(t.id)),inflight:ae,completed:[],canceled:se.map(t=>({id:t.id,resolverId:Z?.get(t.id)??"unknown"}))};k.emitReconcileEnd(ce);}K.isReady||(K.isReady=!0,K.readyResolve&&(K.readyResolve(),K.readyResolve=null));}finally{l$1&&o.finalizeCurrentRun(e),K.isReconciling=false,re.flushDeferred(),Re=0,K.changedKeys.size>0&&ue(),ve();}}function p(e,n){let c=j[e];if(c){T++,(A===null||A.has(e))&&(x=true);try{y.batch(()=>{c(P,{type:e,...n});});}finally{T--;}}else f&&console.warn(`[Directive] Unknown event type "${e}". No handler is registered for this event. Available events: ${Object.keys(j).join(", ")||"(none)"}`);}let R=Ue({mergedDerive:S,getDerivation:e=>J.get(e),definitions:re}),$=Xe({mergedEvents:j,dispatchEvent:p});function N(){let e=[];for(let[n,c]of _)e.push({type:"module",id:n,meta:c});for(let n of Object.keys(i)){let c=i[n]?._meta;c&&e.push({type:"fact",id:n,meta:c});}for(let[n,c]of O)e.push({type:"event",id:n,meta:c});for(let[n,c]of Object.entries(m))c.meta&&e.push({type:"constraint",id:n,meta:c.meta});for(let[n,c]of Object.entries(h))c.meta&&e.push({type:"resolver",id:n,meta:c.meta});for(let[n,c]of Object.entries(I)){let E=c.meta;E&&e.push({type:"effect",id:n,meta:E});}for(let n of Object.keys(S)){let c=J.getMeta(n);c&&e.push({type:"derivation",id:n,meta:c});}return e}let X={facts:P,history:ee.isEnabled?ee:null,derive:R,events:$,constraints:{disable:e=>g.disable(e),enable:e=>g.enable(e),isDisabled:e=>g.isDisabled(e),register:(e,n)=>{re.register("constraint",e,n);},assign:(e,n)=>{re.assign("constraint",e,n);},unregister:e=>{re.unregister("constraint",e);},call:(e,n)=>re.call("constraint",e,n),isDynamic:e=>re.isDynamic("constraint",e),listDynamic:()=>re.listDynamic("constraint")},effects:{disable:e=>oe.disable(e),enable:e=>oe.enable(e),isEnabled:e=>oe.isEnabled(e),register:(e,n)=>{re.register("effect",e,n);},assign:(e,n)=>{re.assign("effect",e,n);},unregister:e=>{re.unregister("effect",e);},call:e=>re.call("effect",e),isDynamic:e=>re.isDynamic("effect",e),listDynamic:()=>re.listDynamic("effect")},resolvers:{register:(e,n)=>{re.register("resolver",e,n),C({[e]:n});},assign:(e,n)=>{re.assign("resolver",e,n),C({[e]:n});},unregister:e=>{let n=h[e];n?.key&&typeof n.requirement=="string"&&g.removeRequirementKey(n.requirement),re.unregister("resolver",e);},call:(e,n)=>re.call("resolver",e,n),isDynamic:e=>re.isDynamic("resolver",e),listDynamic:()=>re.listDynamic("resolver")},get trace(){return o.getEntries()},meta:{module(e){return _.get(e)},fact(e){return i[e]?._meta},event(e){return O.get(e)},constraint(e){return m[e]?.meta},resolver(e){return h[e]?.meta},effect(e){return I[e]?.meta},derivation(e){return J.getMeta(e)},byCategory(e){return N().filter(n=>n.meta.category===e)},byTag(e){return N().filter(n=>n.meta.tags?.includes(e))}},observe(e){if(k.getPlugins().filter(M=>M.name.startsWith("__observer_")).length>=100)return f&&console.warn("[Directive] Maximum observer limit (100) reached. Call the unsubscribe function returned by observe() to clean up."),()=>{};let c=`__observer_${Date.now()}_${Math.random().toString(36).slice(2)}`,E={name:c,onInit:()=>e({type:"system.init"}),onStart:()=>e({type:"system.start"}),onStop:()=>e({type:"system.stop"}),onDestroy:()=>e({type:"system.destroy"}),onFactSet:(M,w,G)=>e({type:"fact.change",key:M,prev:G,next:w}),onConstraintEvaluate:(M,w)=>e({type:"constraint.evaluate",id:M,active:w}),onConstraintError:(M,w)=>e({type:"constraint.error",id:M,error:w}),onRequirementCreated:M=>e({type:"requirement.created",id:M.id,requirementType:M.requirement.type}),onRequirementMet:(M,w)=>e({type:"requirement.met",id:M.id,byResolver:w}),onRequirementCanceled:M=>e({type:"requirement.canceled",id:M.id}),onResolverStart:(M,w)=>e({type:"resolver.start",resolver:M,requirementId:w.id}),onResolverComplete:(M,w,G)=>e({type:"resolver.complete",resolver:M,requirementId:w.id,duration:G}),onResolverError:(M,w,G)=>e({type:"resolver.error",resolver:M,requirementId:w.id,error:G}),onEffectRun:M=>e({type:"effect.run",id:M}),onEffectError:(M,w)=>e({type:"effect.error",id:M,error:w}),onDerivationCompute:(M,w)=>e({type:"derivation.compute",id:M,value:w}),onReconcileStart:()=>e({type:"reconcile.start"}),onReconcileEnd:M=>{let w=M;e({type:"reconcile.end",resolversCompleted:Array.isArray(w.completed)?w.completed.length:0,resolversCanceled:Array.isArray(w.canceled)?w.canceled.length:0});}};return k.register(E),()=>k.unregister(c)},initialize(){if(!K.isInitialized){K.isInitializing=true;for(let e of v.modules)e.init&&y.batch(()=>{e.init(P);});v.onAfterModuleInit&&y.batch(()=>{v.onAfterModuleInit();}),K.isInitializing=false,K.isInitialized=true;for(let e of Object.keys(S))J.get(e);}},start(){if(!K.isRunning){K.isInitialized||this.initialize(),K.isRunning=true;for(let e of v.modules)e.hooks?.onStart?.(X);if(k.emitStart(X),v.errorBoundary?.retryLater&&!V){let e=Math.max(v.errorBoundary.retryLater.delayMs??1e3,250);V=setInterval(()=>{let n=L.processDueRetries();for(let c of n)c.callback?c.callback():ue();},Math.min(e,500));}ue();}},stop(){if(K.isRunning){K.isRunning=false,V!==null&&(clearInterval(V),V=null),L.getRetryLaterManager().clearAll(),r.cancelAll(),oe.cleanupAll();for(let e of v.modules)e.hooks?.onStop?.(X);k.emitStop(X);}},destroy(){K.isDestroyed||(this.stop(),K.isDestroyed=true,y.destroy?.(),r.destroy(),L.clearErrors(),ye.clear(),D.clear(),o.destroy(),re.destroy(),_.clear(),O.clear(),k.emitDestroy(X));},dispatch(e){l.has(e.type)||p(e.type,e);},read(e){return J.get(e)},subscribe(e,n){let c=[],E=[];for(let w of e)w in S?c.push(w):w in i?E.push(w):f&&console.warn(`[Directive] subscribe: unknown key "${w}"`);let M=[];return c.length>0&&M.push(J.subscribe(c,n)),E.length>0&&M.push(y.subscribe(E,n)),()=>{for(let w of M)w();}},watch(e,n,c){let E=c?.equalityFn?(w,G)=>c.equalityFn(w,G):(w,G)=>Object.is(w,G);if(e in S){let w=J.get(e);return J.subscribe([e],()=>{let G=J.get(e);if(!E(G,w)){let se=w;w=G,n(G,se);}})}f&&(e in i||console.warn(`[Directive] watch: unknown key "${e}"`));let M=y.get(e);return y.subscribe([e],()=>{let w=y.get(e);if(!E(w,M)){let G=M;M=w,n(w,G);}})},when(e,n){return new Promise((c,E)=>{let M=y.toObject();if(e(M)){c();return}let w,G,se=()=>{w?.(),G!==void 0&&clearTimeout(G);};w=y.subscribeAll(()=>{let ae=y.toObject();e(ae)&&(se(),c());}),n?.timeout!==void 0&&n.timeout>0&&(G=setTimeout(()=>{se(),E(new Error(`[Directive] when: timed out after ${n.timeout}ms`));},n.timeout));})},inspect(){return {unmet:K.previousRequirements.all(),inflight:r.getInflightInfo(),facts:Object.keys(i).map(e=>({key:e,meta:i[e]?._meta})),events:Object.keys(j).map(e=>({name:e,meta:O.get(e)})),constraints:g.getAllStates().map(e=>({id:e.id,active:e.lastResult??false,disabled:g.isDisabled(e.id),priority:e.priority,hitCount:e.hitCount,lastActiveAt:e.lastActiveAt,meta:m[e.id]?.meta})),resolvers:Object.fromEntries(r.getInflight().map(e=>[e,r.getStatus(e)])),resolverDefs:Object.entries(h).map(([e,n])=>({id:e,requirement:typeof n.requirement=="string"?n.requirement:"(predicate)",meta:n.meta})),effects:Object.entries(I).map(([e,n])=>({id:e,meta:n.meta})),derivations:Object.keys(S).map(e=>({id:e,meta:J.getMeta(e)})),modules:v.modules.map(e=>({id:e.id,meta:_.get(e.id)})),traceEnabled:l$1,...l$1?{trace:structuredClone(o.getEntries()??[])}:{}}},explain(e){let c=K.previousRequirements.all().find(s=>s.id===e);if(!c)return null;let E=g.getState(c.fromConstraint),M=r.getStatus(e),w={},G=g.getDependencies(c.fromConstraint);if(G)for(let s of G)w[s]=y.get(s);else for(let[s,u]of Object.entries(y.toObject()))w[s]=u;let se=m[c.fromConstraint],ae=se?.meta?.label??c.fromConstraint,Z=[`Requirement "${c.requirement.type}" (id: ${c.id})`,`\u251C\u2500 Produced by constraint: ${ae}`,`\u251C\u2500 Constraint priority: ${E?.priority??0}`,`\u251C\u2500 Constraint active: ${E?.lastResult??"unknown"}`,`\u251C\u2500 Resolver status: ${M.state}`];se?.meta?.description&&Z.push(`\u251C\u2500 Description: ${se.meta.description}`);let ce=Object.entries(c.requirement).filter(([s])=>s!=="type").map(([s,u])=>`${s}=${JSON.stringify(u)}`).join(", ");ce&&Z.push(`\u251C\u2500 Requirement payload: { ${ce} }`);let t=Object.entries(w).slice(0,10);return t.length>0&&(Z.push("\u2514\u2500 Relevant facts:"),t.forEach(([s,u],q)=>{let F=q===t.length-1?" \u2514\u2500":" \u251C\u2500",ne=typeof u=="object"?JSON.stringify(u):String(u);Z.push(`${F} ${s} = ${ne.slice(0,50)}${ne.length>50?"...":""}`);})),Z.join(`
2
- `)},getOriginal(e,n){return re.getOriginal(e,n)},restoreOriginal(e,n){return re.restoreOriginal(e,n)},async settle(e=5e3){let n=()=>r.getInflightCount()===0&&!K.isReconciling&&!K.reconcileScheduled&&!r.hasPendingBatches();if(r.hasPendingBatches()&&r.processBatches(),await new Promise(c=>queueMicrotask(c)),!n())return new Promise((c,E)=>{let M=false,w=()=>{M||(M=true,clearTimeout(G),se());},G=setTimeout(()=>{w();let ae=[],Z=r.getInflightInfo();Z.length>0&&ae.push(`${Z.length} resolvers inflight: ${Z.map(t=>t.resolverId).join(", ")}`),K.isReconciling&&ae.push("reconciliation in progress"),K.reconcileScheduled&&ae.push("reconcile scheduled");let ce=K.previousRequirements.all();ce.length>0&&ae.push(`${ce.length} unmet requirements: ${ce.map(t=>t.requirement.type).join(", ")}`),E(new Error(`[Directive] settle() timed out after ${e}ms. ${ae.join("; ")}`));},e),se=this.onSettledChange(()=>{r.hasPendingBatches()&&r.processBatches(),queueMicrotask(()=>{!M&&n()&&(w(),c());});});})},getSnapshot(){return {facts:y.toObject(),version:1}},getDistributableSnapshot(e$1={}){let{includeDerivations:n,excludeDerivations:c,includeFacts:E,ttlSeconds:M,metadata:w,includeVersion:G}=e$1,se={},ae=Object.keys(S),Z=new Set(ae),ce;if(n){if(ce=n.filter(u=>Z.has(u)),f){let u=n.filter(q=>!Z.has(q));u.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown derivation keys ignored: ${u.join(", ")}. Available: ${ae.join(", ")||"(none)"}`);}}else ce=ae;if(c){let u=new Set(c);ce=ce.filter(q=>!u.has(q));}for(let u of ce)try{se[u]=J.get(u);}catch(q){f&&console.warn(`[Directive] getDistributableSnapshot: Skipping derivation "${u}" due to error:`,q);}if(E&&E.length>0){let u=y.toObject(),q=Object.keys(u);if(f){let F=E.filter(ne=>!(ne in u));F.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown fact keys ignored: ${F.join(", ")}. Available: ${q.join(", ")||"(none)"}`);}for(let F of E)F in u&&(se[F]=u[F]);}let t=Date.now(),s={data:se,createdAt:t};return M!==void 0&&M>0&&(s.expiresAt=t+M*1e3),G&&(s.version=e(se)),w&&(s.metadata=w),s},watchDistributableSnapshot(e,n){let{includeDerivations:c,excludeDerivations:E}=e,M=Object.keys(S),w;if(c?w=c.filter(ae=>M.includes(ae)):w=M,E){let ae=new Set(E);w=w.filter(Z=>!ae.has(Z));}if(w.length===0)return f&&console.warn("[Directive] watchDistributableSnapshot: No derivations to watch. Callback will never be called."),()=>{};let se=this.getDistributableSnapshot({...e,includeVersion:true}).version;return J.subscribe(w,()=>{let ae=this.getDistributableSnapshot({...e,includeVersion:true});ae.version!==se&&(se=ae.version,n(ae));})},restore(e){if(!e||typeof e!="object")throw new Error("[Directive] restore() requires a valid snapshot object");if(!e.facts||typeof e.facts!="object")throw new Error("[Directive] restore() snapshot must have a facts object");if(!c(e))throw new Error("[Directive] restore() rejected: snapshot contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");y.batch(()=>{for(let[n,c]of Object.entries(e.facts))l.has(n)||y.set(n,c);});},onSettledChange(e){return ye.add(e),()=>{ye.delete(e);}},onHistoryChange(e){return D.add(e),()=>{D.delete(e);}},batch(e){y.batch(e);},get isSettled(){return r.getInflightCount()===0&&!r.hasPendingBatches()&&!K.isReconciling&&!K.reconcileScheduled},get isRunning(){return K.isRunning},get isInitialized(){return K.isInitialized},get isReady(){return K.isReady},whenReady(){return K.isReady?Promise.resolve():K.isRunning?(K.readyPromise||(K.readyPromise=new Promise(e=>{K.readyResolve=e;})),K.readyPromise):Promise.reject(new Error("[Directive] whenReady() called before start(). Call system.start() first, then await system.whenReady()."))}};function fe(e){if(K.isReconciling)throw new Error(`[Directive] Cannot register module "${e.id}" during reconciliation. Wait for the current reconciliation cycle to complete.`);if(K.isDestroyed)throw new Error(`[Directive] Cannot register module "${e.id}" on a destroyed system.`);let n=(c,E)=>{if(c)for(let M of Object.keys(c)){if(l.has(M))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${M}" in ${E}.`);if(E==="schema"&&M.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${M}" starting with "$". Keys starting with $ are reserved for internal accessors ($store, $snapshot).`)}};n(e.schema,"schema"),n(e.events,"events"),n(e.derive,"derive"),n(e.effects,"effects"),n(e.constraints,"constraints"),n(e.resolvers,"resolvers");for(let c of Object.keys(e.schema))if(c in i)throw new Error(`[Directive] Schema collision: Fact "${c}" already exists. Cannot register module "${e.id}".`);if(f&&e.derive){let c=new Set(Object.keys(i));for(let E of Object.keys(e.derive))c.has(E)&&console.warn(`[Directive] "${E}" exists as both a fact and a derivation after registering module "${e.id}".`);}if(e.history?.snapshotEvents){A===null&&(A=new Set(Object.keys(j)));for(let c of e.history.snapshotEvents)A.add(c);}else if(A!==null&&e.events)for(let c of Object.keys(e.events))A.add(c);Object.assign(i,e.schema);for(let c of Object.values(e.schema)){let E=c;E._meta&&(E._meta=me(E._meta));}if(e.events){for(let[c,E]of Object.entries(e.events))if(typeof E=="object"&&E!==null&&Object.hasOwn(E,"handler")){let M=E;if(e.events[c]=M.handler,M.meta){let w=me(M.meta);w&&O.set(c,w);}}Object.assign(j,e.events);}if(e.derive&&(Object.assign(S,e.derive),J.registerDefinitions(e.derive)),e.effects){for(let c of Object.values(e.effects)){let E=c;E.meta&&(E.meta=me(E.meta));}Object.assign(I,e.effects),oe.registerDefinitions(e.effects);}if(e.constraints){for(let c of Object.values(e.constraints)){let E=c;E.meta&&(E.meta=me(E.meta));}Object.assign(m,e.constraints),g.registerDefinitions(e.constraints);}if(e.resolvers){for(let c of Object.values(e.resolvers)){let E=c;E.meta&&(E.meta=me(E.meta));}Object.assign(h,e.resolvers),r.registerDefinitions(e.resolvers),C(e.resolvers);}if(y.registerKeys(e.schema),e.meta){let c=me(e.meta);c&&_.set(e.id,c);}v.modules.push(e),e.init&&y.batch(()=>{e.init(P);}),e.hooks?.onInit?.(X),K.isRunning&&(e.hooks?.onStart?.(X),ue());}X.registerModule=fe,k.emitInit(X);for(let e of v.modules)e.hooks?.onInit?.(X);return X}export{xe as a,we as b,Ze as c,Ye as d,Qe as e,et as f,vt as g,yt as h,Ae as i,je as j,nt as k,Et as l,Mt as m,Ct as n,be as o,Fe as p,Ke as q,_e as r,st as s,Be as t,ct as u,lt as v,ze as w,Ne as x,Ve as y,hn as z};//# sourceMappingURL=chunk-EUWV4Y5C.js.map
3
- //# sourceMappingURL=chunk-EUWV4Y5C.js.map