@directive-run/core 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-utils.cjs +1 -1
- package/dist/adapter-utils.cjs.map +1 -1
- package/dist/adapter-utils.js +1 -1
- package/dist/adapter-utils.js.map +1 -1
- package/dist/chunk-2HKKISIL.js +3 -0
- package/dist/chunk-2HKKISIL.js.map +1 -0
- package/dist/chunk-4KFEHIIX.cjs +3 -0
- package/dist/chunk-4KFEHIIX.cjs.map +1 -0
- package/dist/chunk-KKHSUZA5.cjs +2 -0
- package/dist/chunk-KKHSUZA5.cjs.map +1 -0
- package/dist/chunk-L76IJROE.cjs +16 -0
- package/dist/chunk-L76IJROE.cjs.map +1 -0
- package/dist/chunk-LN4YQDLL.js +2 -0
- package/dist/chunk-LN4YQDLL.js.map +1 -0
- package/dist/chunk-WIMO6TQ3.js +16 -0
- package/dist/chunk-WIMO6TQ3.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +1 -1
- package/dist/internals.d.cts +1 -1
- package/dist/internals.d.ts +1 -1
- package/dist/internals.js +1 -1
- package/dist/system-4J3B25OD.cjs +2 -0
- package/dist/{system-6JXMY66X.cjs.map → system-4J3B25OD.cjs.map} +1 -1
- package/dist/system-5OAYXJIG.js +2 -0
- package/dist/{system-I534ZO6E.js.map → system-5OAYXJIG.js.map} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +4 -0
- package/dist/testing.d.ts +4 -0
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.js +1 -1
- package/package.json +7 -1
- package/dist/chunk-B2LVGKNZ.js +0 -3
- package/dist/chunk-B2LVGKNZ.js.map +0 -1
- package/dist/chunk-DB5Z7EOG.js +0 -16
- package/dist/chunk-DB5Z7EOG.js.map +0 -1
- package/dist/chunk-GSXCAMNZ.js +0 -2
- package/dist/chunk-GSXCAMNZ.js.map +0 -1
- package/dist/chunk-NZ6EK6W5.cjs +0 -3
- package/dist/chunk-NZ6EK6W5.cjs.map +0 -1
- package/dist/chunk-UBI6S2N3.cjs +0 -16
- package/dist/chunk-UBI6S2N3.cjs.map +0 -1
- package/dist/chunk-WFIJ6OST.cjs +0 -2
- package/dist/chunk-WFIJ6OST.cjs.map +0 -1
- package/dist/system-6JXMY66X.cjs +0 -2
- package/dist/system-I534ZO6E.js +0 -2
package/dist/chunk-DB5Z7EOG.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import {z as z$1,a}from'./chunk-B2LVGKNZ.js';import {k}from'./chunk-GSXCAMNZ.js';import {c}from'./chunk-4CMO5OVZ.js';var y="::";function S(n){return new Proxy({},{get(e,t){if(typeof t!="symbol"&&!k.has(t))return n.get(t)},set(e,t,o){return typeof t=="symbol"||k.has(t)?false:n.set?n.set(t,o):false},has(e,t){return typeof t=="symbol"||k.has(t)?false:n.has?n.has(t):false},deleteProperty(e,t){return typeof t=="symbol"||k.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 I=new WeakMap,H=new WeakMap,V=new WeakMap,W=new WeakMap,z=new WeakMap,U=new WeakMap;function D(n,e){let t=I.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,I.set(n,t);let o=S({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 G(n,e,t){let o=H.get(n);if(o)return o;let r=S({get:a=>{if(Object.hasOwn(e,a))return D(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return H.set(n,r),r}function L(n,e,t){let o=`${e}|${t.join(",")}`,r=z.get(n);if(r){let i=r.get(o);if(i)return i}else r=new Map,z.set(n,r);let a=new Set(t),u=["self",...t],f=S({get:i=>{if(i==="self")return D(n,e);if(a.has(i))return D(n,i);process.env.NODE_ENV!=="production"&&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),f}function F(n,e){let t=W.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,W.set(n,t);let o=S({get:r=>n[`${e}${y}${r}`],has:r=>`${e}${y}${r}`in n});return t.set(e,o),o}function Z(n,e,t){let o=V.get(n);if(o)return o;let r=S({get:a=>{if(Object.hasOwn(e,a))return F(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return V.set(n,r),r}function J(n,e,t){let o=U.get(n);return o||(o=new Map,U.set(n,o)),S({get:r=>{if(!Object.hasOwn(e,r))return;let a=o.get(r);if(a)return a;let u=S({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 v(n){if(n.includes(".")){let[e,...t]=n.split(".");return `${e}${y}${t.join(y)}`}return n}function A(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?L(n,e,o):D(n,e)}function b(n,e){return `${n}${y}${e}`}function $(n){return Object.keys(n).length>0?n:void 0}function re(n,e){let t={};for(let[o,r]of Object.entries(n.schema.facts))t[b(e,o)]=r;return t}function se(n,e){if(n.init)return t=>{let o=D(t,e);n.init(o);}}function oe(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 M=O(d,e,t,o),h=F(m,e);return i(M,h)};r[b(e,a$1)]=w?{compute:g,meta:w}:g;}return $(r)}function ie(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[b(e,o)]=f?{handler:i,meta:f}:i;}return $(t)}function ae(n,e,t,o){if(!n.constraints)return;let r={};for(let[a,u]of Object.entries(n.constraints)){let f=u;r[b(e,a)]={...f,deps:f.deps?.map(i=>b(e,i)),after:f.after?.map(i=>i.includes(y)?i:b(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 $(r)}function ce(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[b(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 $(r)}function ue(n,e,t,o){if(!n.effects)return;let r={};for(let[a,u]of Object.entries(n.effects)){let f=u;r[b(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=>b(e,i))};}return $(r)}function de(n,e,t){return {snapshotEvents:t&&!t.has(e)?[]:n.history?.snapshotEvents?.map(o=>b(e,o))}}function T(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:re(e,t),requirements:e.schema.requirements??{},init:se(e,t),derive:oe(e,t,r,a),events:ie(e,t),effects:ue(e,t,r,a),constraints:ae(e,t,r,a),resolvers:ce(e,t,r,a),hooks:e.hooks,meta:e.meta,history:de(e,t,o)}}function le(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 Q(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 Se(n){if("module"in n){if(!n.module)throw new Error("[Directive] createSystem requires a module. Got: "+typeof n.module);return ye(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 fe(e)}function fe(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(process.env.NODE_ENV!=="production"){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(process.env.NODE_ENV!=="production"&&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=le(e);let{history:f,trace:i,errorBoundary:w}=X(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?T({mod:c,namespace:s,snapshotModulesSet:r}):null}).filter(s=>s!==null);process.env.NODE_ENV!=="production"&&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 M=null,h=null;function _(s){for(let[c$1,l]of Object.entries(s)){if(k.has(c$1)){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] initialFacts/hydrate contains blocked namespace "${c$1}". Skipping.`);continue}if(!t.has(c$1)){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] initialFacts/hydrate contains unknown namespace "${c$1}". Available modules: ${[...t].join(", ")}`);continue}if(l&&typeof l=="object"&&!c(l))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[p,R]of Object.entries(l))k.has(p)||(h.facts[`${c$1}${y}${p}`]=R);}}h=z$1({modules:m,plugins:n.plugins,history:f,trace:i,errorBoundary:w,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{n.initialFacts&&_(n.initialFacts),M&&(_(M),M=null);}});let x=new Map;for(let s of Object.keys(e)){let c=e[s];c&&x.set(s,Q(s,c));}let B=G(h.facts,e,d),ne=Z(h.derive,e,d),te=J(h,e,d),E=null,j=n.tickMs,N={_mode:"namespaced",facts:B,history:h.history,derive:ne,events:te,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"&&(M=c);},initialize(){h.initialize();},start(){if(h.start(),j&&j>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;E=setInterval(()=>{h.dispatch({type:c});},j);}}},stop(){E&&(clearInterval(E),E=null),h.stop();},destroy(){this.stop(),h.destroy();},dispatch(s){h.dispatch(s);},read(s){return h.read(v(s))},subscribe(s,c){let l=[];for(let p of s)if(p.endsWith(".*")){let R=p.slice(0,-2),K=x.get(R);K?l.push(...K):process.env.NODE_ENV!=="production"&&console.warn(`[Directive] subscribe wildcard "${p}" \u2014 namespace "${R}" not found.`);}else l.push(v(p));return h.subscribe(l,c)},subscribeModule(s,c){let l=x.get(s);return !l||l.length===0?(process.env.NODE_ENV!=="production"&&console.warn(`[Directive] subscribeModule("${s}") \u2014 namespace not found. Available: ${[...x.keys()].join(", ")}`),()=>{}):h.subscribe(l,c)},watch(s,c,l){return h.watch(v(s),c,l)},when(s,c){return h.when(()=>s(B),c)},getDistributableSnapshot(s){let c={...s,includeDerivations:s?.includeDerivations?.map(v),excludeDerivations:s?.excludeDerivations?.map(v),includeFacts:s?.includeFacts?.map(v)},l=h.getDistributableSnapshot(c);return {...l,data:A(l.data)}},watchDistributableSnapshot(s,c){let l={...s,includeDerivations:s?.includeDerivations?.map(v),excludeDerivations:s?.excludeDerivations?.map(v),includeFacts:s?.includeFacts?.map(v)};return h.watchDistributableSnapshot(l,p=>{c({...p,data:A(p.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(k.has(s))throw new Error(`[Directive] Module name "${s}" is a blocked property.`);for(let R of Object.keys(c.schema.facts))if(R.includes(y))throw new Error(`[Directive] Schema key "${R}" in module "${s}" contains the reserved separator "${y}".`);let l=c,p=T({mod:l,namespace:s,snapshotModulesSet:r});t.add(s),e[s]=l,g.names=null,x.set(s,Q(s,l)),h.registerModule(p);}};return Y(N,h),ee(N),N}function X(n){let e=n.history,t=n.trace,o=n.errorBoundary;if(n.zeroConfig){let r=process.env.NODE_ENV!=="production";e=e??r,o={onConstraintError:"skip",onResolverError:"skip",onEffectError:"skip",onDerivationError:"skip",...n.errorBoundary};}return {history:e,trace:t,errorBoundary:o}}function Y(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 ee(n){process.env.NODE_ENV!=="production"&&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 ye(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.");process.env.NODE_ENV!=="production"&&(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}=X(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))k.has(d)||(u.facts[d]=m);if(a){if(!c(a))process.env.NODE_ENV!=="production"&&console.warn("[Directive] hydrate() data contains potentially dangerous keys. Skipping.");else for(let[d,m]of Object.entries(a))k.has(d)||(u.facts[d]=m);a=null;}}});let f=new Proxy({},{get(d,m){if(typeof m!="symbol"&&!k.has(m))return M=>{u.dispatch({type:m,...M});}},has(d,m){return typeof m=="symbol"||k.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"&&!k.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,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 Y(g,u),ee(g),g}export{Se as a};//# sourceMappingURL=chunk-DB5Z7EOG.js.map
|
|
16
|
-
//# sourceMappingURL=chunk-DB5Z7EOG.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","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","isDev","overridableMethods","method","eventsProxy"],"mappings":"qHAkBO,IAAMA,CAAAA,CAAY,KAoCzB,SAASC,CAAAA,CAAsCC,EAAgC,CAC7E,OAAO,IAAI,KAAA,CAAM,EAAC,CAAQ,CACxB,GAAA,CAAIC,CAAAA,CAAGC,EAAuB,CAC5B,GAAI,OAAOA,CAAAA,E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,CAAe,cAAA,CAAe,CAC7B,EAAA,CAAI6G,CAAAA,CAAU,EAAA,CACd,MAAA,CAAQA,CAAAA,CAAU,MAAA,CAAO,MACzB,YAAA,CAAcA,CAAAA,CAAU,MAAA,CAAO,YAAA,CAC/B,IAAA,CAAMA,CAAAA,CAAU,KAChB,MAAA,CAAQA,CAAAA,CAAU,MAAA,CAClB,MAAA,CAAQA,CAAAA,CAAU,MAAA,CAClB,QAASA,CAAAA,CAAU,OAAA,CACnB,WAAA,CAAaA,CAAAA,CAAU,WAAA,CACvB,SAAA,CAAWA,EAAU,SAAA,CACrB,KAAA,CAAOA,CAAAA,CAAU,KAAA,CACjB,OAAA,CAASA,CAAAA,CAAU,OACrB,CAAC,EACH,CAEF,CAAA,CAEA,OAAAE,CAAAA,CAAuBd,CAAAA,CAAQjG,CAAM,CAAA,CACrCgH,EAAAA,CAAiBf,CAAM,CAAA,CAEhBA,CACT","file":"chunk-DB5Z7EOG.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 { 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 (process.env.NODE_ENV !== \"production\") {\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 { 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 (process.env.NODE_ENV !== \"production\") {\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 (process.env.NODE_ENV !== \"production\" && 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 process.env.NODE_ENV !== \"production\" &&\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 (process.env.NODE_ENV !== \"production\") {\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 (process.env.NODE_ENV !== \"production\") {\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 (process.env.NODE_ENV !== \"production\") {\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 (process.env.NODE_ENV !== \"production\") {\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 = process.env.NODE_ENV !== \"production\";\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 process.env.NODE_ENV !== \"production\" &&\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 (process.env.NODE_ENV !== \"production\") {\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 (process.env.NODE_ENV !== \"production\") {\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"]}
|
package/dist/chunk-GSXCAMNZ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function o(t,e,r){t[e]=r;}function i(t,e){return t[e]}function s(t,e){return {name:t,onRequirementCreated:e.onRequirementCreated?r=>e.onRequirementCreated(r.requirement):void 0,onRequirementMet:e.onRequirementResolved?r=>e.onRequirementResolved(r.requirement):void 0,onError:e.onError}}function a(t){return e=>e.type===t}function u(t){let e=new Set(t);return r=>e.has(r.type)}var n=[];function d(){let t=n.length;return t===0?null:n[t-1]}function R(){return n.length>0}function m(t){let e=new Set;n.push(e);try{return {value:t(),deps:e}}finally{n.pop();}}function p(t){let e=n.splice(0,n.length);try{return t()}finally{for(let r of e)n.push(r);}}function l(t){let e=n.length;e!==0&&n[e-1].add(t);}var q=Object.freeze(new Set(["__proto__","constructor","prototype"]));export{o as a,i as b,s as c,a as d,u as e,d as f,R as g,m as h,p as i,l as j,q as k};//# sourceMappingURL=chunk-GSXCAMNZ.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-GSXCAMNZ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/types/adapter-utils.ts","../src/core/tracking.ts"],"names":["setBridgeFact","facts","key","value","getBridgeFact","createCallbackPlugin","name","callbacks","req","requirementGuard","type","requirementGuardMultiple","types","typeSet","depStack","getCurrentDeps","len","isTracking","withTracking","fn","deps","withoutTracking","saved","ctx","trackAccess","BLOCKED_PROPS"],"mappings":"AA8FO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACM,CACLF,CAAAA,CAAkCC,CAAG,EAAIC,EAC5C,CAWO,SAASC,CAAAA,CAAiBH,CAAAA,CAAsBC,EAAgB,CACrE,OAAQD,EAAkCC,CAAG,CAC/C,CAyJO,SAASG,CAAAA,CACdC,CAAAA,CACAC,EACa,CACb,OAAO,CACL,IAAA,CAAAD,CAAAA,CACA,qBAAsBC,CAAAA,CAAU,oBAAA,CAC3BC,GAAQD,CAAAA,CAAU,o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c,CAAAA,CAAMF,EAAS,MAAA,CACjBE,CAAAA,GAAQ,GAGZF,CAAAA,CAASE,CAAAA,CAAM,CAAC,CAAA,CAAG,GAAA,CAAId,CAAG,EAC5B,KAYauB,CAAAA,CAAqC,MAAA,CAAO,OACvD,IAAI,GAAA,CAAI,CAAC,WAAA,CAAa,aAAA,CAAe,WAAW,CAAC,CACnD","file":"chunk-GSXCAMNZ.js","sourcesContent":["/**\n * Adapter Type Utilities - Shared types and helpers for framework adapters\n *\n * These utilities reduce type assertions in adapters by providing:\n * - Schema composition types\n * - Constraint/resolver converters\n * - Plugin factory helpers\n */\n\nimport type { Facts } from \"./facts.js\";\nimport type { Plugin } from \"./plugins.js\";\nimport type { ConstraintDef, Requirement } from \"./requirements.js\";\nimport type { ResolverContext, ResolverDef } from \"./resolvers.js\";\nimport type { InferSchema, Schema } from \"./schema.js\";\n\n// ============================================================================\n// Schema Composition Types\n// ============================================================================\n\n/**\n * Merge two schemas into one.\n * Useful for adapters that add bridge-specific facts to user schemas.\n *\n * @example\n * ```typescript\n * type BridgeFields = { __state: SchemaType<Record<string, unknown>> };\n * type Combined = MergedSchema<UserSchema, BridgeFields>;\n * ```\n */\nexport type MergedSchema<Base extends Schema, Extra extends Schema> = Base &\n Extra;\n\n/**\n * Create a schema type from a fields definition.\n * Helper for defining adapter bridge schemas.\n *\n * @example\n * ```typescript\n * type AdapterBridgeSchema = BridgeSchema<{\n * __adapterState: SchemaType<Record<string, unknown>>;\n * }>;\n * ```\n */\nexport type BridgeSchema<Fields extends Schema> = Fields;\n\n// ============================================================================\n// Bridge Schema Helper\n// ============================================================================\n\n/**\n * Create a bridge schema definition for adapters.\n * Returns a schema object compatible with createModule().\n *\n * @example\n * ```typescript\n * const bridgeSchema = createBridgeSchema({\n * __state: t.object<Record<string, unknown>>(),\n * });\n * ```\n */\nexport function createBridgeSchema<S extends Schema>(schema: S): S {\n return schema;\n}\n\n// ============================================================================\n// Type-Safe Fact Mutation\n// ============================================================================\n\n/**\n * Type-safe fact setter for known schema keys.\n * Use when you have a typed schema and want to set a specific fact.\n *\n * @example\n * ```typescript\n * setFact(facts, \"count\", 10); // Type-checked\n * ```\n */\nexport function setFact<S extends Schema, K extends keyof InferSchema<S>>(\n facts: Facts<S>,\n key: K,\n value: InferSchema<S>[K],\n): void {\n (facts as Record<string, unknown>)[key as string] = value;\n}\n\n/**\n * Set a bridge fact without strict typing.\n * Use for adapter-internal bridge fields like `__adapterState`.\n *\n * @example\n * ```typescript\n * setBridgeFact(facts, \"__adapterState\", currentState);\n * ```\n */\nexport function setBridgeFact<V>(\n facts: Facts<Schema>,\n key: string,\n value: V,\n): void {\n (facts as Record<string, unknown>)[key] = value;\n}\n\n/**\n * Get a bridge fact without strict typing.\n * Use for adapter-internal bridge fields.\n *\n * @example\n * ```typescript\n * const state = getBridgeFact<MyState>(facts, \"__adapterState\");\n * ```\n */\nexport function getBridgeFact<V>(facts: Facts<Schema>, key: string): V {\n return (facts as Record<string, unknown>)[key] as V;\n}\n\n// ============================================================================\n// Constraint Converters\n// ============================================================================\n\n/**\n * Adapter constraint definition (generic form used by adapters).\n */\nexport interface AdapterConstraint<TState> {\n when: (state: TState) => boolean | Promise<boolean>;\n require: Requirement | ((state: TState) => Requirement | null);\n priority?: number;\n}\n\n/**\n * Convert adapter-style constraints to Directive format.\n * Maps adapter constraints that work with external state (TState) to\n * Directive constraints that work with Facts<Schema>.\n *\n * @param constraints - Adapter constraints keyed by name\n * @param extractState - Function to extract adapter state from facts\n *\n * @example\n * ```typescript\n * const directiveConstraints = convertConstraints<MyState, BridgeSchema>(\n * adapterConstraints,\n * (facts) => getBridgeFact<MyState>(facts, \"__state\"),\n * );\n * ```\n */\nexport function convertConstraints<TState, S extends Schema>(\n constraints: Record<string, AdapterConstraint<TState>>,\n extractState: (facts: Facts<S>) => TState,\n): Record<string, ConstraintDef<S, Requirement>> {\n const result: Record<string, ConstraintDef<S, Requirement>> = {};\n\n for (const [id, constraint] of Object.entries(constraints)) {\n result[id] = {\n priority: constraint.priority ?? 0,\n when: (facts) => constraint.when(extractState(facts)),\n require: (facts) => {\n const req =\n typeof constraint.require === \"function\"\n ? constraint.require(extractState(facts))\n : constraint.require;\n return req;\n },\n };\n }\n\n return result;\n}\n\n// ============================================================================\n// Resolver Converters\n// ============================================================================\n\n/**\n * Adapter resolver context (generic form used by adapters).\n */\nexport interface AdapterResolverContext<TContext> {\n context: TContext;\n signal: AbortSignal;\n}\n\n/**\n * Adapter resolver definition (generic form used by adapters).\n */\nexport interface AdapterResolver<\n TContext,\n R extends Requirement = Requirement,\n> {\n requirement: (req: Requirement) => req is R;\n key?: (req: R) => string;\n resolve: (\n req: R,\n ctx: AdapterResolverContext<TContext>,\n ) => void | Promise<void>;\n}\n\n/**\n * Convert adapter-style resolvers to Directive format.\n * Maps adapter resolvers that work with external context (TContext) to\n * Directive resolvers that work with ResolverContext<Schema>.\n *\n * @param resolvers - Adapter resolvers keyed by name\n * @param createContext - Function to create adapter context from Directive context\n *\n * @example\n * ```typescript\n * const directiveResolvers = convertResolvers<MyContext, BridgeSchema>(\n * adapterResolvers,\n * (ctx) => ({\n * getState: () => getBridgeFact<MyState>(ctx.facts, \"__state\"),\n * setState: (update) => setBridgeFact(ctx.facts, \"__state\", update),\n * signal: ctx.signal,\n * }),\n * );\n * ```\n */\nexport function convertResolvers<TContext, S extends Schema>(\n resolvers: Record<string, AdapterResolver<TContext, Requirement>>,\n createContext: (ctx: ResolverContext<S>) => TContext,\n): Record<string, ResolverDef<S, Requirement>> {\n const result: Record<string, ResolverDef<S, Requirement>> = {};\n\n for (const [id, resolver] of Object.entries(resolvers)) {\n result[id] = {\n requirement: resolver.requirement,\n key: resolver.key,\n resolve: async (req, ctx) => {\n const adapterCtx = createContext(ctx);\n await resolver.resolve(req, {\n context: adapterCtx,\n signal: ctx.signal,\n });\n },\n };\n }\n\n return result;\n}\n\n// ============================================================================\n// Plugin Factory\n// ============================================================================\n\n/**\n * Callback definitions for adapter plugins.\n */\nexport interface AdapterCallbacks {\n onRequirementCreated?: (req: Requirement) => void;\n onRequirementResolved?: (req: Requirement) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Create a callback plugin for adapter events.\n * Wraps adapter callbacks in a Directive plugin.\n *\n * @param name - Plugin name (for debugging)\n * @param callbacks - Callback functions to invoke\n *\n * @example\n * ```typescript\n * const callbackPlugin = createCallbackPlugin(\"adapter-callbacks\", {\n * onRequirementCreated: (req) => console.log(\"Created:\", req),\n * onRequirementResolved: (req) => console.log(\"Resolved:\", req),\n * });\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema type\nexport function createCallbackPlugin(\n name: string,\n callbacks: AdapterCallbacks,\n): Plugin<any> {\n return {\n name,\n onRequirementCreated: callbacks.onRequirementCreated\n ? (req) => callbacks.onRequirementCreated!(req.requirement)\n : undefined,\n onRequirementMet: callbacks.onRequirementResolved\n ? (req) => callbacks.onRequirementResolved!(req.requirement)\n : undefined,\n onError: callbacks.onError,\n };\n}\n\n// ============================================================================\n// Module Config Helpers\n// ============================================================================\n\n/**\n * Cast constraints to the correct type for createModule.\n * Use this when TypeScript can't infer the constraint types correctly.\n */\nexport function asConstraints<S extends Schema>(\n constraints: Record<string, ConstraintDef<S, Requirement>>,\n): Record<string, ConstraintDef<S, Requirement>> {\n return constraints;\n}\n\n/**\n * Cast resolvers to the correct type for createModule.\n * Use this when TypeScript can't infer the resolver types correctly.\n */\nexport function asResolvers<S extends Schema>(\n resolvers: Record<string, ResolverDef<S, Requirement>>,\n): Record<string, ResolverDef<S, Requirement>> {\n return resolvers;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Create a type guard for a specific requirement type.\n * Simplifies the common pattern of checking req.type.\n *\n * @example\n * ```typescript\n * const isResetReq = requirementGuard<ResetReq>(\"RESET\");\n * // Use in resolver:\n * { requirement: isResetReq, resolve: ... }\n * ```\n */\nexport function requirementGuard<R extends Requirement>(\n type: R[\"type\"],\n): (req: Requirement) => req is R {\n return (req): req is R => req.type === type;\n}\n\n/**\n * Create a type guard that matches multiple requirement types.\n *\n * @example\n * ```typescript\n * const isDataReq = requirementGuardMultiple<FetchReq | RefreshReq>([\"FETCH\", \"REFRESH\"]);\n * ```\n */\nexport function requirementGuardMultiple<R extends Requirement>(\n types: Array<R[\"type\"]>,\n): (req: Requirement) => req is R {\n const typeSet = new Set(types);\n return (req): req is R => typeSet.has(req.type);\n}\n","/**\n * Dependency tracking context for auto-tracking derivations\n *\n * Uses a stack-based approach to handle nested derivation computations.\n * When a derivation accesses a fact, the tracking context records it.\n */\n\n/** Stack of active dependency sets (bare Sets for zero-allocation hot path) */\nconst depStack: Set<string>[] = [];\n\n/**\n * Get the current dependency set, or null if not tracking.\n *\n * @returns The active dependency Set, or `null` if no tracking is active.\n *\n * @internal\n */\nexport function getCurrentDeps(): Set<string> | null {\n const len = depStack.length;\n return len === 0 ? null : depStack[len - 1]!;\n}\n\n/**\n * Check if dependency tracking is currently active.\n *\n * @returns `true` if inside a {@link withTracking} call, `false` otherwise.\n *\n * @internal\n */\nexport function isTracking(): boolean {\n return depStack.length > 0;\n}\n\n/**\n * Run a function with dependency tracking.\n *\n * @remarks\n * Pushes a fresh Set onto the stack, executes `fn`, then pops it.\n * Any fact reads inside `fn` are recorded as dependencies.\n * Nesting is supported — inner calls get their own independent Set.\n *\n * @param fn - The function to execute under tracking.\n * @returns An object with the computed `value` and a `deps` Set of accessed\n * fact keys.\n *\n * @internal\n */\nexport function withTracking<T>(fn: () => T): { value: T; deps: Set<string> } {\n const deps = new Set<string>();\n depStack.push(deps);\n\n try {\n const value = fn();\n return { value, deps };\n } finally {\n depStack.pop();\n }\n}\n\n/**\n * Run a function without tracking.\n *\n * @remarks\n * Temporarily clears the tracking stack so that fact reads inside `fn` do\n * not register as dependencies. The stack is restored after `fn` returns\n * (even on error). Useful for side-effect reads that should not trigger\n * derivation invalidation.\n *\n * @param fn - The function to execute without tracking.\n * @returns The return value of `fn`.\n *\n * @internal\n */\nexport function withoutTracking<T>(fn: () => T): T {\n const saved = depStack.splice(0, depStack.length);\n\n try {\n return fn();\n } finally {\n for (const ctx of saved) {\n depStack.push(ctx);\n }\n }\n}\n\n/**\n * Track a specific key in the current context.\n *\n * @remarks\n * No-op if no tracking context is active.\n *\n * @param key - The fact key to record as a dependency.\n *\n * @internal\n */\nexport function trackAccess(key: string): void {\n const len = depStack.length;\n if (len === 0) {\n return;\n }\n depStack[len - 1]!.add(key);\n}\n\n/**\n * Prototype pollution guard — shared across all proxy handlers.\n *\n * @remarks\n * Contains `__proto__`, `constructor`, and `prototype`. Every proxy `get`\n * and `has` trap checks this set and returns `undefined` / `false` for\n * matching keys, preventing prototype pollution via proxy-based objects.\n *\n * @internal\n */\nexport const BLOCKED_PROPS: ReadonlySet<string> = Object.freeze(\n new Set([\"__proto__\", \"constructor\", \"prototype\"]),\n);\n"]}
|
package/dist/chunk-NZ6EK6W5.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkWFIJ6OST_cjs=require('./chunk-WFIJ6OST.cjs'),chunkBEJ6ICA7_cjs=require('./chunk-BEJ6ICA7.cjs');var be=class extends Error{constructor(A,R,q,g,S=true){super(A);this.source=R;this.sourceId=q;this.context=g;this.recoverable=S;this.name="DirectiveError";}};function Ze(){return {create(m){return m}}}function Ye(){return {create(m){return m}}}function Qe(m){return m}function et(m){return m}function vt(m){return m._mode==="single"}function yt(m){return m._mode==="namespaced"}function ge(m){if(!m)return;let r=Object.assign(Object.create(null),m);return Array.isArray(r.tags)&&Object.freeze(r.tags),Object.freeze(r)}function Ce(m){return typeof m=="object"&&m!==null&&Object.hasOwn(m,"compute")&&typeof m.compute=="function"}function tt(m){return typeof m=="boolean"?{enabled:m,maxSnapshots:100}:{enabled:true,maxSnapshots:m.maxSnapshots??100}}function Pe(m){let{historyOption:r,facts:A,store:R,onSnapshot:q,onHistoryChange:g}=m,{enabled:S,maxSnapshots:_}=tt(r),T=[],b=-1,N=1,O=false,L=false,I=[],M=null,C=-1;function B(){return R.toObject()}function K(){let U=B();try{return structuredClone(U)}catch{try{return JSON.parse(JSON.stringify(U))}catch{return {...U}}}}function Z(U){if(!chunkBEJ6ICA7_cjs.c(U)){console.error("[Directive] Potential prototype pollution detected in snapshot data, skipping restore");return}R.batch(()=>{for(let[H,W]of Object.entries(U)){if(H==="__proto__"||H==="constructor"||H==="prototype"){console.warn(`[Directive] Skipping dangerous key "${H}" during fact restoration`);continue}A[H]=W;}});}return {get isEnabled(){return S},get isRestoring(){return L},get isPaused(){return O},get snapshots(){return [...T]},get currentIndex(){return b},takeSnapshot(U){if(!S||O)return {id:-1,timestamp:Date.now(),facts:{},trigger:U};let H={id:N++,timestamp:Date.now(),facts:K(),trigger:U};for(b<T.length-1&&T.splice(b+1),T.push(H),b=T.length-1;T.length>_;)T.shift(),b--;return q?.(H),H},restore(U){if(S){O=true,L=true;try{Z(U.facts);}finally{O=false,L=false;}}},goBack(U=1){if(!S||T.length===0)return;let H=b,W=b,f=I.find(u=>b>u.startIndex&&b<=u.endIndex);if(f)W=f.startIndex;else if(I.find(c=>b===c.startIndex)){let c=I.find(D=>D.endIndex<b&&b-D.endIndex<=U);W=c?c.startIndex:Math.max(0,b-U);}else W=Math.max(0,b-U);if(H===W)return;b=W;let i=T[b];i&&(this.restore(i),g?.(H,W));},goForward(U=1){if(!S||T.length===0)return;let H=b,W=b,f=I.find(u=>b>=u.startIndex&&b<u.endIndex);if(f?W=f.endIndex:W=Math.min(T.length-1,b+U),H===W)return;b=W;let i=T[b];i&&(this.restore(i),g?.(H,W));},goTo(U){if(!S)return;let H=T.findIndex(i=>i.id===U);if(H===-1){console.warn(`[Directive] Snapshot ${U} not found`);return}let W=b;b=H;let f=T[b];f&&(this.restore(f),g?.(W,H));},replay(){if(!S||T.length===0)return;b=0;let U=T[0];U&&this.restore(U);},export(){return JSON.stringify({version:1,snapshots:T,currentIndex:b})},import(U){if(S)try{let H=JSON.parse(U);if(typeof H!="object"||H===null)throw new Error("[Directive] Invalid history data: expected object");if(H.version!==1)throw new Error(`[Directive] Unsupported history export version: ${H.version}`);if(!Array.isArray(H.snapshots))throw new Error("[Directive] Invalid history data: snapshots must be an array");if(typeof H.currentIndex!="number")throw new Error("Invalid history data: currentIndex must be a number");for(let f of H.snapshots){if(typeof f!="object"||f===null)throw new Error("[Directive] Invalid snapshot: expected object");if(typeof f.id!="number"||typeof f.timestamp!="number"||typeof f.trigger!="string"||typeof f.facts!="object")throw new Error("Invalid snapshot structure");if(!chunkBEJ6ICA7_cjs.c(f.facts))throw new Error("[Directive] Invalid fact data: potential prototype pollution detected in nested objects")}T.length=0,T.push(...H.snapshots),b=H.currentIndex;let W=T[b];W&&this.restore(W);}catch(H){console.error("[Directive] Failed to import history data:",H);}},beginChangeset(U){S&&(M=U,C=b);},endChangeset(){!S||M===null||(b>C&&I.push({label:M,startIndex:C,endIndex:b}),M=null,C=-1);},pause(){O=true;},resume(){O=false;}}}function Ae(){let m={id:-1,timestamp:0,facts:{},trigger:""};return {isEnabled:false,isRestoring:false,isPaused:false,snapshots:[],currentIndex:-1,takeSnapshot:()=>m,restore:()=>{},goBack:()=>{},goForward:()=>{},goTo:()=>{},replay:()=>{},export:()=>"{}",import:()=>{},beginChangeset:()=>{},endChangeset:()=>{},pause:()=>{},resume:()=>{}}}var je=new WeakMap;function nt(m,r){if(r)return r(m);let A=je.get(m);if(A!==void 0)return A;let{type:R,...q}=m,g=chunkBEJ6ICA7_cjs.b(q),S=`${R}:${g}`;return je.set(m,S),S}function qe(m,r,A){return {requirement:m,id:nt(m,A),fromConstraint:r}}function kt(m){return r=>({type:m,...r})}function Mt(m,r){return m.type===r}function Ct(m){return r=>r.type===m}var Re=class m{map=new Map;add(r){this.map.has(r.id)||this.map.set(r.id,r);}remove(r){return this.map.delete(r)}has(r){return this.map.has(r)}get(r){return this.map.get(r)}all(){return [...this.map.values()]}ids(){return [...this.map.keys()]}get size(){return this.map.size}clear(){this.map.clear();}clone(){let r=new m;for(let A of this.map.values())r.add(A);return r}diff(r){let A=[],R=[];for(let q of this.map.values())r.has(q.id)||A.push(q);for(let q of r.map.values())this.map.has(q.id)||R.push(q);return {added:A,removed:R}}};var rt=5e3;function $e(m){let{definitions:r,facts:A,requirementKeys:R={},defaultTimeout:q=rt,onEvaluate:g,onError:S}=m,_=new Map,T=new Set,b=new Set,N=new Map,O=new Map,L=new Set,I=new Map,M=new Map,C=false,B=new Set,K=new Set,Z=new Map,ne=[],U=new Map;function H(t,a){r[t]&&(Z.has(t)||Z.set(t,new Set),Z.get(t).add(a));}function W(){Z.clear();for(let[t,a]of Object.entries(r))if(a.after)for(let v of a.after)H(v,t);}function f(t,a,v,P,V){if(v.has(t))return;if(P.has(t)){let fe=a.indexOf(t),de=[...a.slice(fe),t].join(" \u2192 ");throw new Error(`[Directive] Constraint cycle detected: ${de}. Remove one of the \`after\` dependencies to break the cycle.`)}P.add(t),a.push(t);let oe=r[t];if(oe?.after)for(let fe of oe.after)r[fe]&&f(fe,a,v,P,V);a.pop(),P.delete(t),v.add(t),V.push(t);}function i(){let t=new Set,a=new Set,v=[];for(let P of Object.keys(r))f(P,[],t,a,v);ne=v,U=new Map(ne.map((P,V)=>[P,V]));}i(),W();function u(){for(let[t,a]of Object.entries(r))if(a.after)for(let v of a.after)r[v]||console.warn(`[Directive] Constraint "${t}" references unknown constraint "${v}" in \`after\`. This dependency will be ignored. Check for typos or ensure the constraint exists.`);}process.env.NODE_ENV!=="production"&&u();function c(t,a){return a.async!==void 0?a.async:!!b.has(t)}function D(t){let a=r[t];if(!a)throw new Error(`[Directive] Unknown constraint: ${t}`);let v=c(t,a);v&&b.add(t);let P={id:t,priority:a.priority??0,isAsync:v,lastResult:null,isEvaluating:false,error:null,lastResolvedAt:null,after:a.after??[],hitCount:0,lastActiveAt:null};return _.set(t,P),P}function F(t){return _.get(t)??D(t)}function X(t,a){if(t.size!==a.size||t.size===0)return false;for(let v of a)if(!t.has(v))return false;return true}function ue(t,a){for(let v of a){let P=O.get(v);P&&(P.delete(t),P.size===0&&O.delete(v));}}function re(t,a){for(let v of a)O.has(v)||O.set(v,new Set),O.get(v).add(t);}function h(t){let a=N.get(t);a&&(ue(t,a),N.delete(t));}function k(t){Z.delete(t);for(let a of Z.values())a.delete(t);}function o(t,a){let v=N.get(t)??new Set;X(v,a)||(ue(t,v),re(t,a),N.set(t,a));}function w(t,a){if(a.deps)return I.set(t,new Set(a.deps)),a.when(A);let v=chunkWFIJ6OST_cjs.h(()=>a.when(A));return I.set(t,v.deps),v.value}function z(t,a,v){a.lastResult=v,v&&(a.hitCount++,a.lastActiveAt=Date.now()),a.isEvaluating=false,g?.(t,v);}function Y(t,a,v){a.error=v instanceof Error?v:new Error(String(v)),a.lastResult=false,a.isEvaluating=false,S?.(t,v);}function ye(t,a,v){return b.add(t),a.isAsync=true,process.env.NODE_ENV!=="production"&&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.`),v.then(P=>(z(t,a,P),P)).catch(P=>(Y(t,a,P),false))}function ve(t){let a=r[t];if(!a)return false;let v=F(t);v.isEvaluating=true,v.error=null;try{let P=w(t,a);return P instanceof Promise?ye(t,v,P):(z(t,v,P),P)}catch(P){return Y(t,v,P),false}}async function j(t){let a=r[t];if(!a)return false;let v=F(t),P=a.timeout??q;if(v.isEvaluating=true,v.error=null,a.deps?.length){let V=new Set(a.deps);o(t,V),I.set(t,V);}try{let V=a.when(A),oe=await chunkBEJ6ICA7_cjs.a(V,P,`Constraint "${t}" timed out after ${P}ms`);return v.lastResult=oe,oe&&(v.hitCount++,v.lastActiveAt=Date.now()),v.isEvaluating=!1,g?.(t,oe),oe}catch(V){return v.error=V instanceof Error?V:new Error(String(V)),v.lastResult=false,v.isEvaluating=false,S?.(t,V),false}}let ee=10;function me(t,a){if(t==null)return [];if(Array.isArray(t)){let v=t.filter(P=>P!=null);return process.env.NODE_ENV!=="production"&&v.length>ee&&a&&console.warn(`[Directive] Constraint "${a}" produced ${v.length} requirements. Consider splitting into multiple constraints for better performance.`),v}return [t]}function Se(t){let a=r[t];if(!a)return {requirements:[],deps:new Set};let v=a.require;if(typeof v=="function"){let{value:V,deps:oe}=chunkWFIJ6OST_cjs.h(()=>v(A));return {requirements:me(V,t),deps:oe}}return {requirements:me(v,t),deps:new Set}}function pe(t,a){if(a.size===0)return;let v=N.get(t)??new Set;for(let P of a)v.add(P);re(t,a),N.set(t,v);}let he=null;function s(){return he||(he=Object.keys(r).sort((t,a)=>{let v=F(t),V=F(a).priority-v.priority;if(V!==0)return V;let oe=U.get(t)??0,fe=U.get(a)??0;return oe-fe})),he}for(let t of Object.keys(r))D(t);function y(t){for(let[a,v]of Object.entries(t))v.async&&!v.deps&&console.warn(`[Directive] Async constraint "${a}" has no \`deps\` declared. Auto-tracking cannot work across async boundaries. Add \`deps: ["key1", "key2"]\` to enable dependency tracking.`);}process.env.NODE_ENV!=="production"&&y(r);function p(t){return !r[t]||T.has(t)||K.has(t)?true:B.has(t)}function $(t){let a=_.get(t);if(!a||a.after.length===0)return true;for(let v of a.after)if(!p(v))return false;return true}function e(t){let a=I.get(t);a!==void 0&&o(t,a),K.add(t),M.set(t,[]);}function n(t,a,v){if(a!==void 0){let P=new Set(a);for(let V of v)P.add(V);o(t,P);}else pe(t,v);}function l(t,a,v){if(a.length===0){M.set(t,[]);return}let P=a.map(V=>qe(V,t,R[V.type]));for(let V of P)v.add(V);M.set(t,P);}function d(t,a){for(let v of t)a.add(v);}function E(t,a,v){if(T.has(t))return;if(!a){e(t);return}K.delete(t);let P=I.get(t),V,oe;try{let fe=Se(t);V=fe.requirements,oe=fe.deps;}catch(fe){S?.(t,fe),e(t);return}n(t,P,oe),l(t,V,v);}function x(t,a){let v=[],P=[];for(let V of t){if($(V)){P.push(V);continue}v.push(V);let oe=M.get(V);oe&&d(oe,a);}return {blocked:v,ready:P}}function G(t,a){let v=[];for(let P of t){let V=ve(P);if(V instanceof Promise){v.push({id:P,promise:V});continue}E(P,V,a);}return v}async function Q(t,a){let v=await Promise.all(t.map(async({id:P,promise:V})=>({id:P,active:await V})));for(let{id:P,active:V}of v)E(P,V,a);}async function te(t,a){let{blocked:v,ready:P}=x(t,a);if(P.length===0)return v;let V=[],oe=[];for(let de of P)F(de).isAsync?oe.push(de):V.push(de);let fe=G(V,a);if(fe.length>0&&await Q(fe,a),oe.length>0){let de=oe.map(we=>({id:we,promise:j(we)}));await Q(de,a);}return v}function J(t,a){for(let v of t){let P=O.get(v);if(P)for(let V of P)T.has(V)||a.add(V);}}function ie(t){for(let a of L)T.has(a)||t.add(a);L.clear();}function se(t){let a=new Set;return J(t,a),ie(a),a}function ce(t,a,v){for(let P of t){if(a.has(P))continue;let V=M.get(P);V&&d(V,v);}}return {async evaluate(t){let a=new Re;K.clear();let v=s(),P=T.size===0?v:v.filter(de=>!T.has(de)),V;if(!C||!t||t.size===0)V=P,C=true;else {let de=se(t);V=[...de],ce(P,de,a);}let oe=V,fe=V.length+1;for(;oe.length>0&&fe>0;){let de=oe.length;if(oe=await te(oe,a),oe.length===de)break;fe--;}return a.all()},getState(t){return _.get(t)},getDependencies(t){return N.get(t)},getAllStates(){return [..._.values()]},disable(t){if(!_.has(t)){console.warn(`[Directive] constraints.disable("${t}") \u2014 no such constraint`);return}T.add(t),he=null,M.delete(t),h(t),I.delete(t);},enable(t){if(!_.has(t)){console.warn(`[Directive] constraints.enable("${t}") \u2014 no such constraint`);return}T.delete(t),he=null,L.add(t);},isDisabled(t){return T.has(t)},invalidate(t){let a=O.get(t);if(a)for(let v of a)L.add(v);},markResolved(t){B.add(t);let a=_.get(t);a&&(a.lastResolvedAt=Date.now());let v=Z.get(t);if(v)for(let P of v)L.add(P);},isResolved(t){return B.has(t)},registerDefinitions(t){let a=false;for(let[v,P]of Object.entries(t))r[v]=P,D(v),L.add(v),P.after?.length&&(a=true);he=null,a&&i(),W();},assignDefinition(t,a){if(!r[t])throw new Error(`[Directive] Cannot assign constraint "${t}" \u2014 it does not exist. Use register() to create it.`);r[t]=a,D(t),L.add(t),he=null,i(),W();},unregisterDefinition(t){r[t]&&(delete r[t],_.delete(t),T.delete(t),b.delete(t),L.delete(t),K.delete(t),B.delete(t),M.delete(t),I.delete(t),h(t),k(t),he=null,i(),W());},async callOne(t,a){if(!r[t])throw new Error(`[Directive] Cannot call constraint "${t}" \u2014 it does not exist.`);if(T.has(t))return [];let P=F(t),V;if(P.isAsync)V=await j(t);else {let de=ve(t);V=de instanceof Promise?await de:de;}if(!V)return [];let{requirements:oe}=Se(t);if(oe.length===0)return [];let fe=[];for(let de of oe){let we=a?{...de,...a}:de;fe.push(qe(we,t,R[we.type]));}return fe},setRequirementKey(t,a){R[t]=a;},removeRequirementKey(t){delete R[t];}}}function Fe(m){let{definitions:r,facts:A,onCompute:R,onInvalidate:q,onError:g}=m,S=3,_=new Map;for(let[h,k]of Object.entries(r))if(Ce(k)){r[h]=k.compute;let o=ge(k.meta);o&&_.set(h,o);}let T=new Map,b=new Map,N=new Map,O=new Map,L=0,I=new Set,M=false,C=100,B;function K(h,k){let o=T.has(h)?O:N,w=o.get(h);w?.delete(k),w&&w.size===0&&o.delete(h);}function Z(h,k){let o=r[h]?O:N,w=o.get(h);w||(w=new Set,o.set(h,w)),w.add(k);}function ne(h){let k=T.get(h);if(k)for(let o of k.dependencies)K(o,h);}function U(h){let k=O.get(h);if(k){L++;try{for(let o of k)ue(o);}finally{L--;}O.delete(h);}}function H(h){delete r[h],T.delete(h),b.delete(h),I.delete(h),_.delete(h);}function W(h){if(!r[h])throw new Error(`[Directive] Unknown derivation: ${h}`);let o={id:h,compute:()=>i(h),cachedValue:void 0,dependencies:new Set,isStale:true,isComputing:false,stableRunCount:0,depsStable:false};return T.set(h,o),o}function f(h){return T.get(h)??W(h)}function i(h){let k=f(h),o=r[h];if(!o)throw new Error(`[Directive] Unknown derivation: ${h}`);if(k.isComputing)throw new Error(`[Directive] Circular dependency detected in derivation: ${h}`);k.isComputing=true;try{let w=k.cachedValue,z,Y;if(k.depsStable&&k.dependencies.size>0)z=o(A,B),Y=k.dependencies;else {let ye=chunkWFIJ6OST_cjs.h(()=>o(A,B));z=ye.value,Y=ye.deps,k.dependencies.size>0&&u(Y,k.dependencies)?(k.stableRunCount++,k.stableRunCount>=S&&(k.depsStable=!0)):k.stableRunCount=0;}return k.cachedValue=z,k.isStale=!1,c(h,Y),R&&R(h,z,w,[...Y]),z}catch(w){throw g?.(h,w),w}finally{k.isComputing=false;}}function u(h,k){if(h.size!==k.size)return false;for(let o of k)if(!h.has(o))return false;return true}function c(h,k){let o=f(h),w=o.dependencies;if(!u(w,k)){for(let z of w)K(z,h);for(let z of k)Z(z,h);o.dependencies=k;}}function D(h){for(let k of h){let o=b.get(k);if(o)for(let w of o)w();}}function F(){if(!(L>0||M)){M=true;try{let h=0;for(;I.size>0;){if(++h>C){let o=[...I];throw I.clear(),new Error(`[Directive] Infinite derivation notification loop detected after ${C} iterations. Remaining: ${o.join(", ")}. This usually means a derivation listener is mutating facts that re-trigger the same derivation.`)}let k=[...I];I.clear(),D(k);}}finally{M=false;}}}function X(h,k){let o=O.get(h);if(o)for(let w of o)k.push(w);}function ue(h,k=new Set){let o=[h];for(;o.length>0;){let w=o.pop();if(k.has(w))continue;k.add(w);let z=T.get(w);!z||z.isStale||(z.isStale=true,z.depsStable=false,z.stableRunCount=0,q?.(w),I.add(w),X(w,o));}}return B=new Proxy({},{get(h,k){if(typeof k=="symbol"||chunkWFIJ6OST_cjs.k.has(k)||!r[k])return;chunkWFIJ6OST_cjs.j(k);let o=f(k);return o.isStale&&i(k),o.cachedValue},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),{get(h){let k=f(h);return k.isStale&&i(h),k.cachedValue},isStale(h){return T.get(h)?.isStale??true},invalidate(h){let k=N.get(h);if(!k)return;L++;let o=new Set;try{for(let w of k)ue(w,o);}finally{L--,F();}},invalidateMany(h){L++;let k=new Set;try{for(let o of h){let w=N.get(o);if(w)for(let z of w)ue(z,k);}}finally{L--,F();}},invalidateAll(){L++;try{for(let h of T.values())h.isStale||(h.isStale=!0,h.depsStable=!1,h.stableRunCount=0,I.add(h.id));}finally{L--,F();}},subscribe(h,k){for(let o of h){let w=o;b.has(w)||b.set(w,new Set),b.get(w).add(k);}return ()=>{for(let o of h){let w=o,z=b.get(w);z?.delete(k),z&&z.size===0&&b.delete(w);}}},getProxy(){return B},getDependencies(h){return f(h).dependencies},registerDefinitions(h){for(let[k,o]of Object.entries(h)){if(Ce(o)){r[k]=o.compute;let w=ge(o.meta);w&&_.set(k,w);}else r[k]=o;W(k);}},assignDefinition(h,k){if(!r[h])throw new Error(`[Directive] Cannot assign derivation "${h}" \u2014 it does not exist. Use register() to create it.`);if(Ce(k)){r[h]=k.compute;let w=ge(k.meta);w?_.set(h,w):_.delete(h);}else r[h]=k;let o=T.get(h);o&&(o.isStale=true,o.depsStable=false,o.stableRunCount=0,I.add(h)),F();},unregisterDefinition(h){r[h]&&(ne(h),U(h),H(h),F());},getMeta(h){return _.get(h)},callOne(h){if(!r[h])throw new Error(`[Directive] Cannot call derivation "${h}" \u2014 it does not exist.`);return i(h)}}}var it=3;function Ke(m){let{definitions:r,facts:A,store:R,onRun:q,onError:g}=m,S=new Map,_=null,T=false;function b(f){let i=r[f];if(!i)throw new Error(`[Directive] Unknown effect: ${f}`);let u={id:f,enabled:true,hasExplicitDeps:!!i.deps,dependencies:i.deps?new Set(i.deps):null,cleanup:null,stableRunCount:0,depsStable:false};return S.set(f,u),u}function N(f){return S.get(f)??b(f)}function O(){return R.toObject()}function L(f){f.depsStable=false,f.stableRunCount=0;}function I(f,i){for(let u of f)if(i.has(u))return true;return false}function M(f,i){let u=N(f);return u.enabled?u.dependencies?I(u.dependencies,i)?(u.depsStable&&L(u),true):false:true:false}function C(f){if(f.cleanup){try{f.cleanup();}catch(i){g?.(f.id,i),console.error(`[Directive] Effect "${f.id}" cleanup threw an error:`,i);}f.cleanup=null;}}function B(f,i){if(typeof i=="function")if(T)try{i();}catch(u){g?.(f.id,u),console.error(`[Directive] Effect "${f.id}" cleanup threw an error:`,u);}else f.cleanup=i;}async function K(f,i){let u;if(R.batch(()=>{u=i.run(A,_);}),u instanceof Promise){let c=await u;B(f,c);}else B(f,u);}function Z(f,i){if(f.size!==i.size)return false;for(let u of i)if(!f.has(u))return false;return true}function ne(f,i){if(!(f.dependencies&&Z(f.dependencies,i))){L(f);return}f.stableRunCount++,f.stableRunCount>=it&&(f.depsStable=true);}async function U(f,i){if(f.depsStable&&f.dependencies){await K(f,i);return}let u,c=chunkWFIJ6OST_cjs.h(()=>(R.batch(()=>{u=i.run(A,_);}),u)),D=c.deps,F=c.value;F instanceof Promise&&(F=await F),B(f,F),ne(f,D),f.dependencies=D.size>0?D:null;}async function H(f){let i=N(f),u=r[f];if(!(!i.enabled||!u)){C(i),q?.(f,i.dependencies?[...i.dependencies]:[]);try{i.hasExplicitDeps?await K(i,u):await U(i,u);}catch(c){g?.(f,c),console.error(`[Directive] Effect "${f}" threw an error:`,c),i.hasExplicitDeps||L(i);}}}for(let f of Object.keys(r))b(f);return {async runEffects(f){let i=[];for(let u of Object.keys(r))M(u,f)&&i.push(u);await Promise.all(i.map(H)),_=O();},async runAll(){let f=Object.keys(r);await Promise.all(f.map(i=>{let u=N(i);return u.enabled?(L(u),H(i)):Promise.resolve()})),_=O();},disable(f){let i=N(f);i.enabled=false;},enable(f){let i=N(f);i.enabled=true;},isEnabled(f){return N(f).enabled},cleanupAll(){T=true;for(let f of S.values())C(f);},registerDefinitions(f){for(let[i,u]of Object.entries(f))r[i]=u,b(i);},assignDefinition(f,i){if(!r[f])throw new Error(`[Directive] Cannot assign effect "${f}" \u2014 it does not exist. Use register() to create it.`);let u=S.get(f);u&&C(u),r[f]=i,b(f);},unregisterDefinition(f){if(!r[f])return;let i=S.get(f);i&&C(i),delete r[f],S.delete(f);},async callOne(f){let i=r[f];if(!i)throw new Error(`[Directive] Cannot call effect "${f}" \u2014 it does not exist.`);let u=N(f);if(u.enabled){C(u),q?.(f,u.dependencies?[...u.dependencies]:[]);try{let c;if(R.batch(()=>{c=i.run(A,_);}),c instanceof Promise){let D=await c;B(u,D);}else B(u,c);}catch(c){g?.(f,c),console.error(`[Directive] Effect "${f}" threw an error:`,c);}}}}}function st(m={}){let{delayMs:r=1e3,maxRetries:A=3,backoffMultiplier:R=2,maxDelayMs:q=3e4}=m,g=new Map;function S(_){let T=r*R**(_-1);return Math.min(T,q)}return {scheduleRetry(_,T,b,N,O){if(N>A)return null;let L=S(N),I={source:_,sourceId:T,context:b,attempt:N,nextRetryTime:Date.now()+L,callback:O};return g.set(T,I),I},getPendingRetries(){return Array.from(g.values())},processDueRetries(){let _=Date.now(),T=[];for(let[b,N]of g)N.nextRetryTime<=_&&(T.push(N),g.delete(b));return T},cancelRetry(_){g.delete(_);},clearAll(){g.clear();}}}var ot={constraint:"skip",resolver:"skip",effect:"skip",derivation:"skip",system:"throw"};function _e(m={}){let{config:r={},onError:A,onRecovery:R}=m,q=[],g=100,S=st(r.retryLater),_=new Map,T=1e3;function b(M,C,B,K){if(B instanceof be)return B;let Z=B instanceof Error?B.message:String(B),ne=M!=="system";return new be(Z,M,C,K,ne)}function N(M,C,B){let K=(()=>{switch(M){case "constraint":return r.onConstraintError;case "resolver":return r.onResolverError;case "effect":return r.onEffectError;case "derivation":return r.onDerivationError;default:return}})();if(typeof K=="function"){try{let Z=K(B,C);if(typeof Z=="string")return Z}catch(Z){console.error("[Directive] Error in error handler callback:",Z);}return "skip"}return typeof K=="string"?K:ot[M]}function O(M){q.push(M),q.length>g&&q.shift();try{A?.(M);}catch(C){console.error("[Directive] Error in onError callback:",C);}try{r.onError?.(M);}catch(C){console.error("[Directive] Error in config.onError callback:",C);}}function L(M,C,B){let K=(_.get(C)??0)+1;if(_.set(C,K),_.size>T){let ne=_.keys().next().value;ne!==void 0&&_.delete(ne);}return S.scheduleRetry(M,C,B,K)?"retry-later":(_.delete(C),typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[Directive] ${M} "${C}" exceeded max retry-later attempts. Skipping.`),"skip")}return {handleError(M,C,B,K){let Z=b(M,C,B,K);O(Z);let ne=N(M,C,B instanceof Error?B:new Error(String(B)));ne==="retry-later"&&(ne=L(M,C,K));try{R?.(Z,ne);}catch(U){console.error("[Directive] Error in onRecovery callback:",U);}if(ne==="throw")throw Z;return ne},getLastError(){return q[q.length-1]??null},getAllErrors(){return [...q]},clearErrors(){q.length=0;},getRetryLaterManager(){return S},processDueRetries(){return S.processDueRetries()},clearRetryAttempts(M){_.delete(M),S.cancelRetry(M);}}}var Ne=typeof process<"u"?process.env.NODE_ENV!=="production":true;function at(m,r=100){try{return JSON.stringify(m)?.slice(0,r)??String(m)}catch{return "[circular or non-serializable]"}}function ct(m){let{schema:r,onChange:A,onBatch:R}=m,g=Object.keys(r).length===0,S=m.validate??process.env.NODE_ENV!=="production",_=m.strictKeys??(process.env.NODE_ENV!=="production"&&!g),T=m.redactErrors??false,b=new Map,N=new Set,O=new Map,L=new Set,I=0,M=[],C=new Set,B=false,K=[],Z=100;function ne(o){return o!==null&&typeof o=="object"&&"safeParse"in o&&typeof o.safeParse=="function"&&"_def"in o&&"parse"in o&&typeof o.parse=="function"}function U(o){let w=o;if(w._typeName)return w._typeName;if(ne(o)){let z=o._def;if(z?.typeName)return z.typeName.replace(/^Zod/,"").toLowerCase()}return "unknown"}function H(o){return T?"[redacted]":at(o)}function W(o){return o===null?"null":Array.isArray(o)?"array":typeof o}function f(o,w,z){let Y=z.safeParse(w);if(Y.success)return;let ye=W(w),ve=H(w),j=Y.error?.message??Y.error?.issues?.[0]?.message??"Validation failed",ee=U(z);throw new Error(`[Directive] Validation failed for "${o}": expected ${ee}, got ${ye} ${ve}. ${j}`)}function i(o){if(typeof o._lastFailedIndex=="number"&&o._lastFailedIndex>=0){let w=` (element at index ${o._lastFailedIndex} failed)`;return o._lastFailedIndex=-1,w}return ""}function u(o,w,z){let Y=z._validators;if(!Y||!Array.isArray(Y)||Y.length===0)return;let ye=z._typeName??"unknown";for(let ve=0;ve<Y.length;ve++){let j=Y[ve];if(typeof j!="function"||j(w))continue;let ee=W(w),me=H(w),Se=i(z),pe=ve===0?"":` (validator ${ve+1} failed)`;throw new Error(`[Directive] Validation failed for "${o}": expected ${ye}, got ${ee} ${me}${pe}${Se}`)}}function c(o){if(_)throw new Error(`[Directive] Unknown fact key: "${o}". Key not defined in schema.`);console.warn(`[Directive] Unknown fact key: "${o}"`);}function D(o,w){if(!S)return;let z=r[o];if(!z){c(o);return}if(ne(z)){f(o,w,z);return}u(o,w,z);}function F(o){O.get(o)?.forEach(w=>w());}function X(){L.forEach(o=>o());}function ue(o,w,z){if(B){K.push({key:o,value:w,prev:z});return}B=true;try{A?.(o,w,z),F(o),X(),re(". A listener is repeatedly mutating facts that re-trigger notifications");}finally{B=false;}}function re(o){let w=0;for(;K.length>0;){if(++w>Z)throw K.length=0,new Error(`[Directive] Infinite notification loop detected after ${Z} iterations${o}.`);let z=[...K];K.length=0;for(let Y of z)A?.(Y.key,Y.value,Y.prev),F(Y.key);X();}}function h(){if(!(I>0)){if(R&&M.length>0&&R([...M]),C.size>0){B=true;try{for(let o of C)F(o);X(),re(" during flush");}finally{B=false;}}M.length=0,C.clear();}}let k={get(o){return chunkWFIJ6OST_cjs.j(o),b.get(o)},has(o){return chunkWFIJ6OST_cjs.j(o),b.has(o)},set(o,w){Ne&&D(o,w);let z=b.get(o);Object.is(z,w)||(b.set(o,w),N.add(o),I>0?(M.push({key:o,value:w,prev:z,type:"set"}),C.add(o)):ue(o,w,z));},delete(o){let w=b.get(o);b.delete(o),N.delete(o),I>0?(M.push({key:o,value:void 0,prev:w,type:"delete"}),C.add(o)):ue(o,void 0,w);},batch(o){I++;try{o();}finally{I--,h();}},subscribe(o,w){for(let z of o){let Y=z;O.has(Y)||O.set(Y,new Set),O.get(Y).add(w);}return ()=>{for(let z of o){let Y=O.get(z);Y&&(Y.delete(w),Y.size===0&&O.delete(z));}}},subscribeAll(o){return L.add(o),()=>L.delete(o)},toObject(){let o={};for(let w of N)b.has(w)&&(o[w]=b.get(w));return o}};return k.destroy=()=>{O.clear(),L.clear();},k.registerKeys=o=>{for(let w of Object.keys(o))chunkWFIJ6OST_cjs.k.has(w)||(r[w]=o[w],N.add(w));},k}var Ie=new WeakMap;function Be(m,r,A=r){return new Proxy(m,{get(R,q){if(typeof q=="string"&&chunkWFIJ6OST_cjs.k.has(q))return;let g=Reflect.get(R,q);if(typeof q=="symbol"||typeof g!="object"||g===null)return g;if(Ie.has(g))return Ie.get(g);let S=Be(g,r,`${A}.${String(q)}`);return Ie.set(g,S),S},set(R,q,g){return typeof q!="symbol"&&console.warn(`[Directive] Nested mutation on "facts.${A}.${String(q)}" will not trigger reactivity. Use: facts.${r} = { ...facts.${r}, ... }`),Reflect.set(R,q,g)}})}function lt(m,r){let A=()=>({get:q=>chunkWFIJ6OST_cjs.i(()=>m.get(q)),has:q=>chunkWFIJ6OST_cjs.i(()=>m.has(q))});return new Proxy({},{get(q,g){if(typeof g=="symbol"||chunkWFIJ6OST_cjs.k.has(g))return;if(g==="$store")return m;if(g==="$snapshot")return A;let S=m.get(g);return Ne&&S!==null&&typeof S=="object"?Be(S,g):S},set(q,g,S){return typeof g=="symbol"||g==="$store"||g==="$snapshot"||chunkWFIJ6OST_cjs.k.has(g)?false:(m.set(g,S),true)},deleteProperty(q,g){return typeof g=="symbol"||g==="$store"||g==="$snapshot"||chunkWFIJ6OST_cjs.k.has(g)?false:(m.delete(g),true)},has(q,g){return g==="$store"||g==="$snapshot"?true:typeof g=="symbol"||chunkWFIJ6OST_cjs.k.has(g)?false:m.has(g)},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(q,g){return g==="$store"||g==="$snapshot"?{configurable:true,enumerable:false,writable:false}:{configurable:true,enumerable:true,writable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function We(m){let r=ct(m),A=lt(r,m.schema);return {store:r,facts:A}}function ze(){let m=[];function r(g){if(g)try{return g()}catch(S){console.error("[Directive] Plugin error:",S);return}}async function A(g){if(g)try{return await g()}catch(S){console.error("[Directive] Plugin error:",S);return}}function R(g){return (...S)=>{for(let _ of m)r(()=>_[g]?.(...S));}}return {register(g){m.some(S=>S.name===g.name)&&(console.warn(`[Directive] Plugin "${g.name}" is already registered, replacing...`),this.unregister(g.name)),m.push(g);},unregister(g){let S=m.findIndex(_=>_.name===g);S!==-1&&m.splice(S,1);},getPlugins(){return [...m]},async emitInit(g){for(let S of m)await A(()=>S.onInit?.(g));},emitStart:R("onStart"),emitStop:R("onStop"),emitDestroy:R("onDestroy"),emitFactSet:R("onFactSet"),emitFactDelete:R("onFactDelete"),emitFactsBatch:R("onFactsBatch"),emitDerivationCompute:R("onDerivationCompute"),emitDerivationInvalidate:R("onDerivationInvalidate"),emitReconcileStart:R("onReconcileStart"),emitReconcileEnd:R("onReconcileEnd"),emitConstraintEvaluate:R("onConstraintEvaluate"),emitConstraintError:R("onConstraintError"),emitRequirementCreated:R("onRequirementCreated"),emitRequirementMet:R("onRequirementMet"),emitRequirementCanceled:R("onRequirementCanceled"),emitResolverStart:R("onResolverStart"),emitResolverComplete:R("onResolverComplete"),emitResolverError:R("onResolverError"),emitResolverRetry:R("onResolverRetry"),emitResolverCancel:R("onResolverCancel"),emitEffectRun:R("onEffectRun"),emitEffectError:R("onEffectError"),emitSnapshot:R("onSnapshot"),emitHistoryNavigate:R("onHistoryNavigate"),emitError:R("onError"),emitErrorRecovery:R("onErrorRecovery"),emitDefinitionRegister:R("onDefinitionRegister"),emitDefinitionAssign:R("onDefinitionAssign"),emitDefinitionUnregister:R("onDefinitionUnregister"),emitDefinitionCall:R("onDefinitionCall"),emitTraceComplete:R("onTraceComplete")}}var Ve={attempts:1,backoff:"none",initialDelay:100,maxDelay:3e4},He={enabled:false,windowMs:50};function ut(m,r){let{backoff:A,initialDelay:R=100,maxDelay:q=3e4}=m,g;switch(A){case "none":g=R;break;case "linear":g=R*r;break;case "exponential":g=R*2**(r-1);break;default:g=R;}return Math.max(1,Math.min(g,q))}function ft(m){if(process.env.NODE_ENV!=="production")for(let[r,A]of Object.entries(m)){if(!A.resolve&&!A.resolveBatch&&!A.resolveBatchWithResults)throw new Error(`[Directive] Resolver "${r}" must define either resolve() or resolveBatch(). Add one of these methods to handle requirements.`);if(!(!A.batch?.enabled||A.resolveBatch||A.resolveBatchWithResults))if(A.resolve)console.warn(`[Directive] Resolver "${r}" has batch.enabled but no resolveBatch(). Falling back to individual resolve() calls. Add resolveBatch() for true bulk operations.`);else throw new Error(`[Directive] Resolver "${r}" has batch.enabled=true but no resolve(), resolveBatch(), or resolveBatchWithResults() method.`)}}function Le(m){let{definitions:r,facts:A,store:R,onStart:q,onComplete:g,onError:S,onRetry:_,onCancel:T,onResolutionComplete:b}=m;ft(r);let N=new Map,O=new Map,L=1e3,I=new Map,M=new Map,C=1e3;function B(){if(O.size>L){let s=O.size-L,y=O.keys();for(let p=0;p<s;p++){let $=y.next().value;$&&O.delete($);}}}function K(s){return typeof s=="object"&&s!==null&&"requirement"in s&&typeof s.requirement=="string"}function Z(s){return typeof s=="object"&&s!==null&&"requirement"in s&&typeof s.requirement=="function"}function ne(s,y){return K(s)?y.type===s.requirement:Z(s)?s.requirement(y):false}function U(s,y){let p=M.get(s);if(!p)return null;M.delete(s),M.set(s,p);for(let $ of p){let e=r[$];if(e&&ne(e,y))return $}return null}function H(s,y){if(!M.has(s)){if(M.size>=C){let p=M.keys().next().value;p!==void 0&&M.delete(p);}M.set(s,new Set);}M.get(s).add(y);}function W(s){let y=s.type,p=U(y,s);if(p)return p;for(let[$,e]of Object.entries(r))if(ne(e,s))return H(y,$),$;return null}function f(s){return {facts:A,signal:s,snapshot:()=>A.$snapshot()}}async function i(s,y,p,$){let e=s instanceof Error?s:new Error(String(s));if($.signal.aborted)return {action:"abort",error:e};if(p.shouldRetry&&!p.shouldRetry(e,y))return {action:"break",error:e};if(y<p.attempts){if($.signal.aborted)return {action:"abort",error:e};let n=ut(p,y);if(await new Promise(l=>{let d=setTimeout(l,n),E=()=>{clearTimeout(d),l();};$.signal.addEventListener("abort",E,{once:true});}),$.signal.aborted)return {action:"abort",error:e}}return {action:"continue",error:e}}async function u(s,y,p,$){if(!s.resolve)return;let e;R.batch(()=>{e=s.resolve(p.requirement,f($));});let n=s.timeout;if(n&&n>0){await chunkBEJ6ICA7_cjs.a(e,n,`Resolver "${y}" timed out after ${n}ms`);return}await e;}function c(s,y,p){let $=Date.now()-p;O.set(y.id,{state:"success",requirementId:y.id,completedAt:Date.now(),duration:$}),B(),g?.(s,y,$);}function D(s,y,p,$){O.set(y.id,{state:"error",requirementId:y.id,error:p,failedAt:Date.now(),attempts:$}),B(),S?.(s,y,p);}function F(s,y,p){let $=N.get(s);$&&($.attempt=y,$.status={state:"running",requirementId:s,startedAt:p,attempt:y});}async function X(s,y,p,$,e){let n=await i(s,y,p,$);return n.action==="continue"&&y<p.attempts&&e(y+1),{lastError:n.error,shouldContinue:n.action==="continue"}}async function ue(s,y,p){let $=r[s];if(!$)return;let e={...Ve,...$.retry},n=null,l=N.get(y.id)?.startedAt??Date.now();for(let d=1;d<=e.attempts;d++){if(p.signal.aborted)return;F(y.id,d,l);try{await u($,s,y,p.signal),c(s,y,l);return}catch(E){let x=await X(E,d,e,p,G=>_?.(s,y,G));if(n=x.lastError,!x.shouldContinue)break}}D(s,y,n,e.attempts);}async function re(s,y,p){return y&&y>0?chunkBEJ6ICA7_cjs.a(s,y,p):s}async function h(s,y,p,$,e,n,l,d){let E;R.batch(()=>{E=s.resolveBatchWithResults($,e);});let x=await re(E,n,`Batch resolver "${y}" timed out after ${n}ms`);if(x.length!==p.length)throw new Error(`[Directive] Batch resolver "${y}" returned ${x.length} results but expected ${p.length}. Results array must match input order.`);let G=false;for(let Q=0;Q<p.length;Q++){let te=p[Q],J=x[Q];if(J.success){c(y,te,l);continue}G=true;let ie=J.error??new Error("Batch item failed");O.set(te.id,{state:"error",requirementId:te.id,error:ie,failedAt:Date.now(),attempts:d}),S?.(y,te,ie);}return !G||p.some((Q,te)=>x[te]?.success)?"done":"retry"}async function k(s,y,p,$,e,n,l){let d;R.batch(()=>{d=s.resolveBatch($,e);}),await re(d,n,`Batch resolver "${y}" timed out after ${n}ms`);for(let E of p)c(y,E,l);}function o(s,y,p,$){for(let e of y)D(s,e,p,$);}async function w(s,y){await Promise.all(y.map(p=>{let $=new AbortController;return ue(s,p,$)}));}async function z(s,y,p,$,e,n,l){let d=f($),E=p.map(x=>x.requirement);return s.resolveBatchWithResults?h(s,y,p,E,d,e,n,l):(await k(s,y,p,E,d,e,n),"done")}function Y(s,y,p){for(let $ of y)_?.(s,$,p);}async function ye(s,y,p,$,e){let n=new AbortController,l=Date.now(),d=null;for(let E=1;E<=$.attempts;E++){if(n.signal.aborted)return null;try{if(await z(s,y,p,n.signal,e,l,E)==="done")return null}catch(x){let G=await X(x,E,$,n,Q=>Y(y,p,Q));if(d=G.lastError,!G.shouldContinue)break}}return d}async function ve(s,y){let p=r[s];if(!p)return;if(!p.resolveBatch&&!p.resolveBatchWithResults){await w(s,y);return}let $={...Ve,...p.retry},n={...He,...p.batch}.timeoutMs??p.timeout,l=await ye(p,s,y,$,n);l&&o(s,y,l,$.attempts);}let j=1e4;function ee(s){s.timer&&(clearTimeout(s.timer),s.timer=null);}function me(s){return I.has(s)||I.set(s,{resolverId:s,requirements:[],timer:null}),I.get(s)}function Se(s,y){let p=r[s];if(!p)return;let $={...He,...p.batch},e=me(s),n=$.maxSize||j;if(e.requirements.length>=n&&(ee(e),pe(s)),e.requirements.push(y),$.maxSize&&e.requirements.length>=$.maxSize){ee(e),pe(s);return}ee(e),e.timer=setTimeout(()=>{pe(s);},$.windowMs);}function pe(s){let y=I.get(s);if(!y||y.requirements.length===0)return;let p=[...y.requirements];y.requirements=[],y.timer=null,ve(s,p).then(()=>{b?.();});}return {resolve(s){if(N.has(s.id))return;let y=W(s.requirement);if(!y){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] No resolver found for requirement type "${s.requirement.type}" (id: ${s.id})`);return}let p=r[y];if(!p)return;if(p.batch?.enabled){Se(y,s);return}let $=new AbortController,e=Date.now(),n={requirementId:s.id,resolverId:y,controller:$,startedAt:e,attempt:1,status:{state:"pending",requirementId:s.id,startedAt:e},originalRequirement:s};N.set(s.id,n),q?.(y,s),ue(y,s,$).finally(()=>{N.delete(s.id)&&b?.();});},cancel(s){let y=N.get(s);if(y){y.controller.abort(),N.delete(s),O.set(s,{state:"canceled",requirementId:s,canceledAt:Date.now()}),B(),T?.(y.resolverId,y.originalRequirement);return}for(let p of I.values()){let $=p.requirements.findIndex(e=>e.id===s);if($!==-1){let[e]=p.requirements.splice($,1);O.set(s,{state:"canceled",requirementId:s,canceledAt:Date.now()}),B(),e&&T?.(p.resolverId,e);return}}},cancelAll(){let s=[...N.keys()];for(let y of s)this.cancel(y);for(let y of I.values()){y.timer&&clearTimeout(y.timer);for(let p of y.requirements)O.set(p.id,{state:"canceled",requirementId:p.id,canceledAt:Date.now()}),T?.(y.resolverId,p);}I.clear(),B();},getStatus(s){let y=N.get(s);if(y)return y.status;let p=O.get(s);return p||{state:"idle"}},getInflight(){return [...N.keys()]},getInflightInfo(){return [...N.values()].map(s=>({id:s.requirementId,resolverId:s.resolverId,startedAt:s.startedAt}))},getInflightCount(){return N.size},isResolving(s){return N.has(s)},processBatches(){for(let s of I.keys())pe(s);},hasPendingBatches(){for(let s of I.values())if(s.requirements.length>0)return true;return false},registerDefinitions(s){for(let[y,p]of Object.entries(s))r[y]=p;M.clear();},assignDefinition(s,y){if(!r[s])throw new Error(`[Directive] Cannot assign resolver "${s}" \u2014 it does not exist. Use register() to create it.`);r[s]=y,M.clear();},unregisterDefinition(s){if(!r[s])return;for(let[p,$]of N)$.resolverId===s&&($.controller.abort(),N.delete(p),O.set(p,{state:"canceled",requirementId:p,canceledAt:Date.now()}),T?.(s,$.originalRequirement));let y=I.get(s);if(y){y.timer&&clearTimeout(y.timer);for(let p of y.requirements)O.set(p.id,{state:"canceled",requirementId:p.id,canceledAt:Date.now()}),T?.(s,p);I.delete(s);}delete r[s],M.clear(),B();},async callOne(s,y){let p=r[s];if(!p)throw new Error(`[Directive] Cannot call resolver "${s}" \u2014 it does not exist.`);let $=new AbortController,e=f($.signal);if(p.resolve){let n;R.batch(()=>{n=p.resolve(y,e);}),await n;}},destroy(){this.cancelAll(),O.clear(),M.clear();}}}function Ue(m){let{mergedDerive:r,getDerivation:A,definitions:R}=m,q={register:(g,S)=>R.register("derivation",g,S),assign:(g,S)=>R.assign("derivation",g,S),unregister:g=>R.unregister("derivation",g),call:g=>R.call("derivation",g),isDynamic:g=>R.isDynamic("derivation",g),listDynamic:()=>R.listDynamic("derivation")};return new Proxy({},{get(g,S){if(typeof S!="symbol"&&!chunkWFIJ6OST_cjs.k.has(S)){if(S in q)return q[S];if(S in r)return A(S)}},has(g,S){return typeof S=="symbol"||chunkWFIJ6OST_cjs.k.has(S)?false:S in r||S in q},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(g,S){if(typeof S!="symbol"&&!chunkWFIJ6OST_cjs.k.has(S)&&(S in r||S in q))return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function Xe(m){let{mergedEvents:r,dispatchEvent:A}=m;return new Proxy({},{get(R,q){if(typeof q!="symbol"&&!chunkWFIJ6OST_cjs.k.has(q))return g=>{A(q,g);}},has(R,q){return typeof q=="symbol"||chunkWFIJ6OST_cjs.k.has(q)?false:q in r},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(R,q){if(typeof q!="symbol"&&!chunkWFIJ6OST_cjs.k.has(q)&&q in r)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(m){let{mergedConstraints:r,mergedResolvers:A,mergedDerive:R,mergedEffects:q,constraintsManager:g,resolversManager:S,derivationsManager:_,effectsManager:T,pluginManager:b,getState:N,scheduleReconcile:O,maxDeferredRegistrations:L}=m,I={constraints:new Set,resolvers:new Set,derivations:new Set,effects:new Set},M={constraints:new Map,resolvers:new Map,derivations:new Map,effects:new Map},C=[];function B(i){if(dt.has(i))throw new Error(`[Directive] Derivation ID "${i}" conflicts with a reserved derive method name.`)}let K={constraint:{label:"Constraint",mergedMap:r,manager:g,dynamicSet:I.constraints,originalsMap:M.constraints,reconciles:true},resolver:{label:"Resolver",mergedMap:A,manager:S,dynamicSet:I.resolvers,originalsMap:M.resolvers,reconciles:true},derivation:{label:"Derivation",mergedMap:R,manager:_,dynamicSet:I.derivations,originalsMap:M.derivations,reconciles:false,validateId:B},effect:{label:"Effect",mergedMap:q,manager:T,dynamicSet:I.effects,originalsMap:M.effects,reconciles:false}};function Z(i){if(typeof i!="string"||i.length===0)throw new Error(`[Directive] Definition ID must be a non-empty string. Received: ${String(i)}`);if(chunkWFIJ6OST_cjs.k.has(i))throw new Error(`[Directive] Security: Definition ID "${i}" is a blocked property.`);if(i.includes("::"))throw new Error(`[Directive] Definition ID "${i}" cannot contain "::". This separator is reserved for namespacing.`)}function ne(i,u,c){let D=K[i];if(D.validateId?.(u),u in D.mergedMap)throw new Error(`[Directive] ${D.label} "${u}" already exists. Use assign() to override.`);if(i!=="derivation"){let F=c;F.meta&&(F.meta=ge(F.meta));}D.mergedMap[u]=c,D.manager.registerDefinitions({[u]:c}),D.dynamicSet.add(u),b.emitDefinitionRegister(i,u,c),D.reconciles&&O();}function U(i,u,c){let D=K[i];if(D.validateId?.(u),!(u in D.mergedMap))throw new Error(`[Directive] ${D.label} "${u}" does not exist. Use register() to create it.`);if(i!=="derivation"){let X=c;X.meta&&(X.meta=ge(X.meta));}let F=D.mergedMap[u];D.manager.assignDefinition(u,c),D.originalsMap.set(u,F),D.mergedMap[u]=c,b.emitDefinitionAssign(i,u,c,F),D.reconciles&&O();}function H(i,u){let c=K[i];if(!c.dynamicSet.has(u)){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] Cannot unregister static ${i} "${u}". Only dynamically registered ${i}s can be removed.`);return}c.manager.unregisterDefinition(u),delete c.mergedMap[u],c.dynamicSet.delete(u),c.originalsMap.delete(u),b.emitDefinitionUnregister(i,u),c.reconciles&&O();}function W(){if(C.length===0)return;let i=C.splice(0);for(let u of i)try{switch(u.op){case "register":ne(u.type,u.id,u.def);break;case "assign":U(u.type,u.id,u.def);break;case "unregister":H(u.type,u.id);break}}catch(c){process.env.NODE_ENV!=="production"&&console.error(`[Directive] Error in deferred ${u.op} for ${u.type} "${u.id}":`,c);}}function f(i,u,c,D){let{isDestroyed:F,isReconciling:X}=N();if(F)throw new Error(`[Directive] Cannot ${i} ${u} "${c}" on a destroyed system.`);if(Z(c),X){if(C.length>=L)throw new Error(`[Directive] Too many deferred registrations (max ${L}). Avoid calling register/assign/unregister in resolver or effect callbacks during reconciliation.`);i==="unregister"?C.push({op:i,type:u,id:c}):C.push({op:i,type:u,id:c,def:D});return}switch(i){case "register":ne(u,c,D);break;case "assign":U(u,c,D);break;case "unregister":H(u,c);break}}return {register(i,u,c){f("register",i,u,c);},assign(i,u,c){f("assign",i,u,c);},unregister(i,u){f("unregister",i,u);},call(i,u,c){let{isDestroyed:D}=N();if(D)throw new Error(`[Directive] Cannot call ${i} "${u}" on a destroyed system.`);switch(Z(u),b.emitDefinitionCall(i,u,c),i){case "constraint":return g.callOne(u,c);case "resolver":return S.callOne(u,c);case "derivation":return _.callOne(u);case "effect":return T.callOne(u)}},isDynamic(i,u){switch(i){case "constraint":return I.constraints.has(u);case "resolver":return I.resolvers.has(u);case "derivation":return I.derivations.has(u);case "effect":return I.effects.has(u)}},listDynamic(i){switch(i){case "constraint":return [...I.constraints];case "resolver":return [...I.resolvers];case "derivation":return [...I.derivations];case "effect":return [...I.effects]}},flushDeferred:W,getOriginal(i,u){let D={constraint:M.constraints,resolver:M.resolvers,derivation:M.derivations,effect:M.effects}[i];if(D)return D.get(u)},restoreOriginal(i,u){let D={constraint:M.constraints,resolver:M.resolvers,derivation:M.derivations,effect:M.effects}[i];if(!D||!D.has(u))return false;let F=D.get(u);return f("assign",i,u,F),D.delete(u),true},destroy(){C.length=0,I.constraints.clear(),I.resolvers.clear(),I.derivations.clear(),I.effects.clear(),M.constraints.clear(),M.resolvers.clear(),M.derivations.clear(),M.effects.clear();}}}function Ge(m){let{traceConfig:r,pluginManager:A,resolverMetaLookup:R}=m;if(!(r===true||typeof r=="object"&&r!==null))return {enabled:false,recordFactChange(){},startRun(){return 0},currentTrace:null,getEntries(){return null},attributeResolverStart(){},recordResolverComplete(){},recordResolverError(){},decrementInflight(){},finalizeCurrentRun(){},drainPendingChanges(){},destroy(){}};let g=(typeof r=="object"&&r!==null?r.maxRuns:void 0)??100,S=[],_=new Map,T=0,b=null,N=[],O=new Map,L=new Map,I=new Map,M=null,C=0,B=0,K={count:0,totalDuration:0,avgDuration:0,maxDuration:0,avgResolverCount:0,totalResolverCount:0,avgFactChangeCount:0,totalFactChangeCount:0};function Z(c){let D=_.get(c);if(D&&D.status==="pending"){D.status="settled";let F=I.get(c);D.duration=F!==void 0?performance.now()-F:Date.now()-D.timestamp,I.delete(c),L.delete(c),D.causalChain=H(D),W(D),B++,A.emitTraceComplete(D);}}function ne(c){let D=O.get(c);if(O.delete(c),D!==void 0){let F=(L.get(D)??1)-1;F<=0?Z(D):L.set(D,F);}}function U(){let c=S.shift();if(c&&(_.delete(c.id),I.delete(c.id),c.status==="pending")){L.delete(c.id);for(let[D,F]of O)F===c.id&&O.delete(D);}}function H(c){let D=[];for(let F of c.factChanges)D.push(`${F.key} changed`);for(let F of c.derivationsRecomputed)D.push(`${F.id} recomputed`);for(let F of c.constraintsHit)D.push(`${F.id} constraint hit`);for(let F of c.requirementsAdded)D.push(`${F.type} requirement added`);for(let F of c.resolversCompleted)D.push(`${F.resolver} resolved (${F.duration.toFixed(0)}ms)`);for(let F of c.resolversErrored)D.push(`${F.resolver} errored`);for(let F of c.effectsRun)D.push(`${F.id} effect ran`);return D.join(" \u2192 ")}function W(c){K.count++,K.totalDuration+=c.duration,K.avgDuration=K.totalDuration/K.count,c.duration>K.maxDuration&&(K.maxDuration=c.duration);let D=c.resolversStarted.length;K.totalResolverCount+=D,K.avgResolverCount=K.totalResolverCount/K.count;let F=c.factChanges.length;K.totalFactChangeCount+=F,K.avgFactChangeCount=K.totalFactChangeCount/K.count;let X=[];K.count>3&&c.duration>K.avgDuration*5&&X.push(`Duration ${c.duration.toFixed(0)}ms is 5x+ above average (${K.avgDuration.toFixed(0)}ms)`),c.resolversErrored.length>0&&X.push(`${c.resolversErrored.length} resolver(s) errored`),X.length>0&&(c.anomalies=X);}function f(c){S.push(c),_.set(c.id,c),S.length>g&&U(),B++;}function i(c){return c.factChanges.length>0||c.constraintsHit.length>0||c.requirementsAdded.length>0||c.effectsRun.length>0}return {enabled:true,get currentTrace(){return b},set currentTrace(c){b=c;},recordFactChange(c,D,F){N.push({key:c,oldValue:D,newValue:F});},startRun(){let c=performance.now(),D=++T;return I.set(D,c),b={id:D,timestamp:Date.now(),duration:0,status:"pending",factChanges:N.splice(0),derivationsRecomputed:[],constraintsHit:[],requirementsAdded:[],requirementsRemoved:[],resolversStarted:[],resolversCompleted:[],resolversErrored:[],effectsRun:[],effectErrors:[]},c},getEntries(){return (!M||C!==B)&&(M=[...S],C=B),M},attributeResolverStart(c){b&&O.set(c,b.id);},recordResolverComplete(c,D,F){let X=O.get(c);if(X!==void 0){let ue=_.get(X);ue&&ue.resolversCompleted.push({resolver:D,requirementId:c,duration:F,meta:R?.(D)});}},recordResolverError(c,D,F){let X=O.get(c);if(X!==void 0){let ue=_.get(X);ue&&ue.resolversErrored.push({resolver:D,requirementId:c,error:F,meta:R?.(D)});}},decrementInflight(c){ne(c);},finalizeCurrentRun(c){if(!b)return;if(b.duration=performance.now()-c,!i(b)){I.delete(b.id),b=null;return}let D=b.resolversStarted.length;D===0?(b.status="settled",b.causalChain=H(b),W(b),f(b),A.emitTraceComplete(b)):(b.status="pending",f(b),L.set(b.id,D)),b=null;},drainPendingChanges(){N.length=0;},destroy(){S.length=0,_.clear(),O.clear(),L.clear(),I.clear(),N.length=0,b=null,M=null;}}}function gn(m){let r=Object.create(null),A=Object.create(null),R=Object.create(null),q=Object.create(null),g=Object.create(null),S=Object.create(null),_=new Map,T=new Map,b=new Map,N=new Map;for(let e of m.modules){let n=(d,E)=>{if(d)for(let x of Object.keys(d)){if(chunkWFIJ6OST_cjs.k.has(x))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${x}" in ${E}. This could indicate a prototype pollution attempt.`);if(E==="schema"&&x.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${x}" 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 d of Object.keys(e.schema)){let E=b.get(d);if(E)throw new Error(`[Directive] Schema collision: Fact "${d}" is defined in both module "${E}" and "${e.id}". Use namespacing (e.g., "${e.id}::${d}") or merge into one module.`);b.set(d,e.id);}let l=(d,E)=>{if(d)for(let x of Object.keys(d)){let G=N.get(x);if(G&&G!==e.id)throw new Error(`[Directive] Definition collision: ${E} "${x}" is defined in both module "${G}" and "${e.id}". Use namespacing or rename to avoid conflicts.`);N.set(x,e.id);}};if(l(e.derive,"derivation"),l(e.effects,"effect"),l(e.constraints,"constraint"),l(e.resolvers,"resolver"),l(e.events,"event"),Object.assign(r,e.schema),e.events){for(let[d,E]of Object.entries(e.events))if(typeof E=="object"&&E!==null&&Object.hasOwn(E,"handler")){let x=E;if(e.events[d]=x.handler,x.meta){let G=ge(x.meta);G&&T.set(d,G);}}Object.assign(A,e.events);}if(e.derive&&Object.assign(R,e.derive),e.effects&&Object.assign(q,e.effects),e.constraints&&Object.assign(g,e.constraints),e.resolvers&&Object.assign(S,e.resolvers),e.meta){let d=ge(e.meta);d&&_.set(e.id,d);}}for(let e of Object.values(g))e.meta&&(e.meta=ge(e.meta));for(let e of Object.values(S))e.meta&&(e.meta=ge(e.meta));for(let e of Object.values(q)){let n=e;n.meta&&(n.meta=ge(n.meta));}for(let e of Object.values(r)){let n=e;n._meta&&(n._meta=ge(n._meta));}let O=null;if(m.modules.some(e=>e.history?.snapshotEvents)){O=new Set;for(let e of m.modules){let n=e;if(n.history?.snapshotEvents)for(let l of n.history.snapshotEvents)O.add(l);else if(n.events)for(let l of Object.keys(n.events))O.add(l);}}let I=0,M=false;if(process.env.NODE_ENV!=="production"){let e=new Set(Object.keys(R));for(let n of Object.keys(r))e.has(n)&&console.warn(`[Directive] "${n}" exists as both a fact and a derivation. This may cause unexpected dependency tracking behavior.`);}let C=ze();for(let e of m.plugins??[])C.register(e);let B=C.getPlugins().length>0,K=_e({config:m.errorBoundary,onError:e=>C.emitError(e),onRecovery:(e,n)=>C.emitErrorRecovery(e,n)}),Z=null,ne=()=>{},U=()=>{},H=null,W=Ge({traceConfig:m.trace,pluginManager:C,resolverMetaLookup:e=>S[e]?.meta}),f=W.enabled,{store:i,facts:u}=We({schema:r,onChange:(e,n,l)=>{C.emitFactSet(e,n,l),ne(e),f&&W.recordFactChange(String(e),l,n),!H?.isRestoring&&(I===0&&(M=true),j.changedKeys.add(e),me());},onBatch:e=>{C.emitFactsBatch(e);let n=[];for(let l of e)n.push(l.key);if(f)for(let l of e)W.recordFactChange(l.key,l.prev,l.type==="delete"?void 0:l.value);if(U(n),!H?.isRestoring){I===0&&(M=true);for(let l of e)j.changedKeys.add(l.key);me();}}}),c=Fe({definitions:R,facts:u,onCompute:(e,n,l,d)=>{B&&C.emitDerivationCompute(e,n,d),W.currentTrace&&W.currentTrace.derivationsRecomputed.push({id:e,deps:d?[...d]:[],oldValue:l,newValue:n,meta:c.getMeta(e)});},onInvalidate:B?e=>C.emitDerivationInvalidate(e):void 0,onError:(e,n)=>{K.handleError("derivation",e,n)==="retry"&&c.invalidate(e);}});ne=e=>c.invalidate(e),U=e=>c.invalidateMany(e);let D=Ke({definitions:q,facts:u,store:i,onRun:(e,n)=>{B&&C.emitEffectRun(e),W.currentTrace&&W.currentTrace.effectsRun.push({id:e,triggeredBy:n,meta:q[e]?.meta});},onError:(e,n)=>{let l=K.handleError("effect",e,n);B&&C.emitEffectError(e,n),W.currentTrace&&W.currentTrace.effectErrors.push({id:e,error:String(n),meta:q[e]?.meta}),l==="disable"&&D.disable(e),l==="retry"&&(j.changedKeys.add("*"),me());}}),F=Object.create(null);for(let e of Object.values(S))e.key&&typeof e.requirement=="string"&&(F[e.requirement]=e.key);let X=$e({definitions:g,facts:u,requirementKeys:F,onEvaluate:B?(e,n)=>C.emitConstraintEvaluate(e,n):void 0,onError:(e,n)=>{let l=K.handleError("constraint",e,n);B&&C.emitConstraintError(e,n),l==="disable"&&X.disable(e);}});function ue(e){for(let n of Object.values(e))n.key&&typeof n.requirement=="string"&&X.setRequirementKey(n.requirement,n.key);}let re=Le({definitions:S,facts:u,store:i,onStart:B?(e,n)=>C.emitResolverStart(e,n):void 0,onComplete:(e,n,l)=>{K.clearRetryAttempts(e),B&&(C.emitResolverComplete(e,n,l),C.emitRequirementMet(n,e)),X.markResolved(n.fromConstraint),f&&(W.recordResolverComplete(n.id,e,l),W.decrementInflight(n.id));},onError:(e,n,l)=>{let d=K.handleError("resolver",e,l,n);if(B&&C.emitResolverError(e,n,l),d==="disable"&&X.disable(n.fromConstraint),d==="retry"&&(j.previousRequirements.remove(n.id),me()),d==="retry-later"){let x=K.getRetryLaterManager().getPendingRetries().find(G=>G.sourceId===e);x&&!x.callback&&(x.callback=()=>{me();});}f&&(W.recordResolverError(n.id,e,String(l)),W.decrementInflight(n.id));},onRetry:(e,n,l)=>C.emitResolverRetry(e,n,l),onCancel:(e,n)=>{C.emitResolverCancel(e,n),C.emitRequirementCanceled(n),f&&W.decrementInflight(n.id);},onResolutionComplete:()=>{z(),me();}}),h=new Set;function k(){for(let e of h)e();}let o=m.history?Pe({historyOption:m.history,facts:u,store:i,onSnapshot:e=>{C.emitSnapshot(e),k();},onHistoryChange:(e,n)=>{C.emitHistoryNavigate(e,n),k();}}):Ae();H=o;let w=new Set;function z(){for(let e of w)e();}let Y=50,ye=100,ve=0,j={isRunning:false,isReconciling:false,reconcileScheduled:false,isInitializing:false,isInitialized:false,isReady:false,isDestroyed:false,changedKeys:new Set,previousRequirements:new Re,readyPromise:null,readyResolve:null},ee=Je({mergedConstraints:g,mergedResolvers:S,mergedDerive:R,mergedEffects:q,constraintsManager:X,resolversManager:re,derivationsManager:c,effectsManager:D,pluginManager:C,getState:()=>j,scheduleReconcile:me,maxDeferredRegistrations:ye});function me(){!j.isRunning||j.reconcileScheduled||j.isInitializing||(j.reconcileScheduled=true,z(),queueMicrotask(()=>{j.reconcileScheduled=false,j.isRunning&&!j.isInitializing&&Se().catch(e=>{process.env.NODE_ENV!=="production"&&console.error("[Directive] Unexpected error in reconcile:",e);});}));}async function Se(){if(j.isReconciling)return;if(ve++,ve>Y){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] Reconcile loop exceeded ${Y} iterations. This usually means resolvers are creating circular requirement chains. Check that resolvers aren't mutating facts that re-trigger their own constraints.`),f&&W.drainPendingChanges(),j.previousRequirements=new Re,ve=0;return}j.isReconciling=true,z();let e=f?W.startRun():0,n=W.currentTrace;if(n)for(let l of n.factChanges){let d=r[l.key];l.meta=d?._meta;}try{if(j.changedKeys.size>0){if(O===null||M){let J=j.changedKeys,ie=J.size<=5?`facts-changed:${[...J].join(",")}`:`facts-changed:${[...J].slice(0,5).join(",")}+${J.size-5}more`;o.takeSnapshot(ie);}M=!1;}let l=u.$snapshot();C.emitReconcileStart(l),await D.runEffects(j.changedKeys);let d=new Set(j.changedKeys);j.changedKeys.clear();let E=await X.evaluate(d),x=new Re;for(let J of E)x.add(J),C.emitRequirementCreated(J);if(n){let J=new Set(E.map(ie=>ie.fromConstraint));for(let ie of J){let se=X.getState(ie);if(se){let ce=X.getDependencies(ie);n.constraintsHit.push({id:ie,priority:se.priority,deps:ce?[...ce]:[],meta:g[ie]?.meta});}}}let{added:G,removed:Q}=x.diff(j.previousRequirements);if(n){for(let J of G)n.requirementsAdded.push({id:J.id,type:J.requirement.type,fromConstraint:J.fromConstraint});for(let J of Q)n.requirementsRemoved.push({id:J.id,type:J.requirement.type,fromConstraint:J.fromConstraint});}for(let J of Q)re.cancel(J.id);for(let J of G)re.resolve(J);if(n){let J=re.getInflightInfo(),ie=new Map(J.map(se=>[se.id,se]));for(let se of G){let ae=ie.get(se.id)?.resolverId??"unknown";n.resolversStarted.push({resolver:ae,requirementId:se.id,meta:S[ae]?.meta}),W.attributeResolverStart(se.id);}}j.previousRequirements=x;let te=re.getInflightInfo();if(m.plugins&&m.plugins.length>0){let J=Q.length>0?new Map(te.map(se=>[se.id,se.resolverId])):void 0,ie={unmet:E.filter(se=>!re.isResolving(se.id)),inflight:te,completed:[],canceled:Q.map(se=>({id:se.id,resolverId:J?.get(se.id)??"unknown"}))};C.emitReconcileEnd(ie);}j.isReady||(j.isReady=!0,j.readyResolve&&(j.readyResolve(),j.readyResolve=null));}finally{f&&W.finalizeCurrentRun(e),j.isReconciling=false,ee.flushDeferred(),ve=0,j.changedKeys.size>0&&me(),z();}}function pe(e,n){let l=A[e];if(l){I++,(O===null||O.has(e))&&(M=true);try{i.batch(()=>{l(u,{type:e,...n});});}finally{I--;}}else process.env.NODE_ENV!=="production"&&console.warn(`[Directive] Unknown event type "${e}". No handler is registered for this event. Available events: ${Object.keys(A).join(", ")||"(none)"}`);}let he=Ue({mergedDerive:R,getDerivation:e=>c.get(e),definitions:ee}),s=Xe({mergedEvents:A,dispatchEvent:pe});function y(){let e=[];for(let[n,l]of _)e.push({type:"module",id:n,meta:l});for(let n of Object.keys(r)){let l=r[n]?._meta;l&&e.push({type:"fact",id:n,meta:l});}for(let[n,l]of T)e.push({type:"event",id:n,meta:l});for(let[n,l]of Object.entries(g))l.meta&&e.push({type:"constraint",id:n,meta:l.meta});for(let[n,l]of Object.entries(S))l.meta&&e.push({type:"resolver",id:n,meta:l.meta});for(let[n,l]of Object.entries(q)){let d=l.meta;d&&e.push({type:"effect",id:n,meta:d});}for(let n of Object.keys(R)){let l=c.getMeta(n);l&&e.push({type:"derivation",id:n,meta:l});}return e}let p={facts:u,history:o.isEnabled?o:null,derive:he,events:s,constraints:{disable:e=>X.disable(e),enable:e=>X.enable(e),isDisabled:e=>X.isDisabled(e),register:(e,n)=>{ee.register("constraint",e,n);},assign:(e,n)=>{ee.assign("constraint",e,n);},unregister:e=>{ee.unregister("constraint",e);},call:(e,n)=>ee.call("constraint",e,n),isDynamic:e=>ee.isDynamic("constraint",e),listDynamic:()=>ee.listDynamic("constraint")},effects:{disable:e=>D.disable(e),enable:e=>D.enable(e),isEnabled:e=>D.isEnabled(e),register:(e,n)=>{ee.register("effect",e,n);},assign:(e,n)=>{ee.assign("effect",e,n);},unregister:e=>{ee.unregister("effect",e);},call:e=>ee.call("effect",e),isDynamic:e=>ee.isDynamic("effect",e),listDynamic:()=>ee.listDynamic("effect")},resolvers:{register:(e,n)=>{ee.register("resolver",e,n),ue({[e]:n});},assign:(e,n)=>{ee.assign("resolver",e,n),ue({[e]:n});},unregister:e=>{let n=S[e];n?.key&&typeof n.requirement=="string"&&X.removeRequirementKey(n.requirement),ee.unregister("resolver",e);},call:(e,n)=>ee.call("resolver",e,n),isDynamic:e=>ee.isDynamic("resolver",e),listDynamic:()=>ee.listDynamic("resolver")},get trace(){return W.getEntries()},meta:{module(e){return _.get(e)},fact(e){return r[e]?._meta},event(e){return T.get(e)},constraint(e){return g[e]?.meta},resolver(e){return S[e]?.meta},effect(e){return q[e]?.meta},derivation(e){return c.getMeta(e)},byCategory(e){return y().filter(n=>n.meta.category===e)},byTag(e){return y().filter(n=>n.meta.tags?.includes(e))}},observe(e){let n=`__observer_${Date.now()}_${Math.random().toString(36).slice(2)}`,l={name:n,onInit:()=>e({type:"system.init"}),onStart:()=>e({type:"system.start"}),onStop:()=>e({type:"system.stop"}),onDestroy:()=>e({type:"system.destroy"}),onFactSet:(d,E,x)=>e({type:"fact.change",key:d,prev:x,next:E}),onConstraintEvaluate:(d,E)=>e({type:"constraint.evaluate",id:d,active:E}),onConstraintError:(d,E)=>e({type:"constraint.error",id:d,error:E}),onRequirementCreated:d=>e({type:"requirement.created",id:d.id,requirementType:d.requirement.type}),onRequirementMet:(d,E)=>e({type:"requirement.met",id:d.id,byResolver:E}),onRequirementCanceled:d=>e({type:"requirement.canceled",id:d.id}),onResolverStart:(d,E)=>e({type:"resolver.start",resolver:d,requirementId:E.id}),onResolverComplete:(d,E,x)=>e({type:"resolver.complete",resolver:d,requirementId:E.id,duration:x}),onResolverError:(d,E,x)=>e({type:"resolver.error",resolver:d,requirementId:E.id,error:x}),onEffectRun:d=>e({type:"effect.run",id:d}),onEffectError:(d,E)=>e({type:"effect.error",id:d,error:E}),onDerivationCompute:(d,E)=>e({type:"derivation.compute",id:d,value:E}),onReconcileStart:()=>e({type:"reconcile.start"}),onReconcileEnd:d=>{let E=d;e({type:"reconcile.end",added:Array.isArray(E.unmet)?E.unmet.length:0,removed:0});}};return C.register(l),()=>C.unregister(n)},initialize(){if(!j.isInitialized){j.isInitializing=true;for(let e of m.modules)e.init&&i.batch(()=>{e.init(u);});m.onAfterModuleInit&&i.batch(()=>{m.onAfterModuleInit();}),j.isInitializing=false,j.isInitialized=true;for(let e of Object.keys(R))c.get(e);}},start(){if(!j.isRunning){j.isInitialized||this.initialize(),j.isRunning=true;for(let e of m.modules)e.hooks?.onStart?.(p);if(C.emitStart(p),m.errorBoundary?.retryLater&&!Z){let e=Math.max(m.errorBoundary.retryLater.delayMs??1e3,250);Z=setInterval(()=>{let n=K.processDueRetries();for(let l of n)l.callback?l.callback():me();},Math.min(e,500));}me();}},stop(){if(j.isRunning){j.isRunning=false,Z!==null&&(clearInterval(Z),Z=null),K.getRetryLaterManager().clearAll(),re.cancelAll(),D.cleanupAll();for(let e of m.modules)e.hooks?.onStop?.(p);C.emitStop(p);}},destroy(){j.isDestroyed||(this.stop(),j.isDestroyed=true,i.destroy?.(),re.destroy(),K.clearErrors(),w.clear(),h.clear(),W.destroy(),ee.destroy(),_.clear(),T.clear(),C.emitDestroy(p));},dispatch(e){chunkWFIJ6OST_cjs.k.has(e.type)||pe(e.type,e);},read(e){return c.get(e)},subscribe(e,n){let l=[],d=[];for(let x of e)x in R?l.push(x):x in r?d.push(x):process.env.NODE_ENV!=="production"&&console.warn(`[Directive] subscribe: unknown key "${x}"`);let E=[];return l.length>0&&E.push(c.subscribe(l,n)),d.length>0&&E.push(i.subscribe(d,n)),()=>{for(let x of E)x();}},watch(e,n,l){let d=l?.equalityFn?(x,G)=>l.equalityFn(x,G):(x,G)=>Object.is(x,G);if(e in R){let x=c.get(e);return c.subscribe([e],()=>{let G=c.get(e);if(!d(G,x)){let Q=x;x=G,n(G,Q);}})}process.env.NODE_ENV!=="production"&&(e in r||console.warn(`[Directive] watch: unknown key "${e}"`));let E=i.get(e);return i.subscribe([e],()=>{let x=i.get(e);if(!d(x,E)){let G=E;E=x,n(x,G);}})},when(e,n){return new Promise((l,d)=>{let E=i.toObject();if(e(E)){l();return}let x,G,Q=()=>{x?.(),G!==void 0&&clearTimeout(G);};x=i.subscribeAll(()=>{let te=i.toObject();e(te)&&(Q(),l());}),n?.timeout!==void 0&&n.timeout>0&&(G=setTimeout(()=>{Q(),d(new Error(`[Directive] when: timed out after ${n.timeout}ms`));},n.timeout));})},inspect(){return {unmet:j.previousRequirements.all(),inflight:re.getInflightInfo(),facts:Object.keys(r).map(e=>({key:e,meta:r[e]?._meta})),events:Object.keys(A).map(e=>({name:e,meta:T.get(e)})),constraints:X.getAllStates().map(e=>({id:e.id,active:e.lastResult??false,disabled:X.isDisabled(e.id),priority:e.priority,hitCount:e.hitCount,lastActiveAt:e.lastActiveAt,meta:g[e.id]?.meta})),resolvers:Object.fromEntries(re.getInflight().map(e=>[e,re.getStatus(e)])),resolverDefs:Object.entries(S).map(([e,n])=>({id:e,requirement:typeof n.requirement=="string"?n.requirement:"(predicate)",meta:n.meta})),effects:Object.entries(q).map(([e,n])=>({id:e,meta:n.meta})),derivations:Object.keys(R).map(e=>({id:e,meta:c.getMeta(e)})),modules:m.modules.map(e=>({id:e.id,meta:_.get(e.id)})),traceEnabled:f,...f?{trace:structuredClone(W.getEntries()??[])}:{}}},explain(e){let l=j.previousRequirements.all().find(ce=>ce.id===e);if(!l)return null;let d=X.getState(l.fromConstraint),E=re.getStatus(e),x={},G=X.getDependencies(l.fromConstraint);if(G)for(let ce of G)x[ce]=i.get(ce);else for(let[ce,ae]of Object.entries(i.toObject()))x[ce]=ae;let Q=g[l.fromConstraint],te=Q?.meta?.label??l.fromConstraint,J=[`Requirement "${l.requirement.type}" (id: ${l.id})`,`\u251C\u2500 Produced by constraint: ${te}`,`\u251C\u2500 Constraint priority: ${d?.priority??0}`,`\u251C\u2500 Constraint active: ${d?.lastResult??"unknown"}`,`\u251C\u2500 Resolver status: ${E.state}`];Q?.meta?.description&&J.push(`\u251C\u2500 Description: ${Q.meta.description}`);let ie=Object.entries(l.requirement).filter(([ce])=>ce!=="type").map(([ce,ae])=>`${ce}=${JSON.stringify(ae)}`).join(", ");ie&&J.push(`\u251C\u2500 Requirement payload: { ${ie} }`);let se=Object.entries(x).slice(0,10);return se.length>0&&(J.push("\u2514\u2500 Relevant facts:"),se.forEach(([ce,ae],t)=>{let a=t===se.length-1?" \u2514\u2500":" \u251C\u2500",v=typeof ae=="object"?JSON.stringify(ae):String(ae);J.push(`${a} ${ce} = ${v.slice(0,50)}${v.length>50?"...":""}`);})),J.join(`
|
|
2
|
-
`)},getOriginal(e,n){return ee.getOriginal(e,n)},restoreOriginal(e,n){return ee.restoreOriginal(e,n)},async settle(e=5e3){let n=()=>re.getInflightCount()===0&&!j.isReconciling&&!j.reconcileScheduled&&!re.hasPendingBatches();if(re.hasPendingBatches()&&re.processBatches(),await new Promise(l=>queueMicrotask(l)),!n())return new Promise((l,d)=>{let E=false,x=()=>{E||(E=true,clearTimeout(G),Q());},G=setTimeout(()=>{x();let te=[],J=re.getInflightInfo();J.length>0&&te.push(`${J.length} resolvers inflight: ${J.map(se=>se.resolverId).join(", ")}`),j.isReconciling&&te.push("reconciliation in progress"),j.reconcileScheduled&&te.push("reconcile scheduled");let ie=j.previousRequirements.all();ie.length>0&&te.push(`${ie.length} unmet requirements: ${ie.map(se=>se.requirement.type).join(", ")}`),d(new Error(`[Directive] settle() timed out after ${e}ms. ${te.join("; ")}`));},e),Q=this.onSettledChange(()=>{re.hasPendingBatches()&&re.processBatches(),queueMicrotask(()=>{!E&&n()&&(x(),l());});});})},getSnapshot(){return {facts:i.toObject(),version:1}},getDistributableSnapshot(e={}){let{includeDerivations:n,excludeDerivations:l,includeFacts:d,ttlSeconds:E,metadata:x,includeVersion:G}=e,Q={},te=Object.keys(R),J=new Set(te),ie;if(n){if(ie=n.filter(ae=>J.has(ae)),process.env.NODE_ENV!=="production"){let ae=n.filter(t=>!J.has(t));ae.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown derivation keys ignored: ${ae.join(", ")}. Available: ${te.join(", ")||"(none)"}`);}}else ie=te;if(l){let ae=new Set(l);ie=ie.filter(t=>!ae.has(t));}for(let ae of ie)try{Q[ae]=c.get(ae);}catch(t){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] getDistributableSnapshot: Skipping derivation "${ae}" due to error:`,t);}if(d&&d.length>0){let ae=i.toObject(),t=Object.keys(ae);if(process.env.NODE_ENV!=="production"){let a=d.filter(v=>!(v in ae));a.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown fact keys ignored: ${a.join(", ")}. Available: ${t.join(", ")||"(none)"}`);}for(let a of d)a in ae&&(Q[a]=ae[a]);}let se=Date.now(),ce={data:Q,createdAt:se};return E!==void 0&&E>0&&(ce.expiresAt=se+E*1e3),G&&(ce.version=chunkBEJ6ICA7_cjs.e(Q)),x&&(ce.metadata=x),ce},watchDistributableSnapshot(e,n){let{includeDerivations:l,excludeDerivations:d}=e,E=Object.keys(R),x;if(l?x=l.filter(te=>E.includes(te)):x=E,d){let te=new Set(d);x=x.filter(J=>!te.has(J));}if(x.length===0)return process.env.NODE_ENV!=="production"&&console.warn("[Directive] watchDistributableSnapshot: No derivations to watch. Callback will never be called."),()=>{};let Q=this.getDistributableSnapshot({...e,includeVersion:true}).version;return c.subscribe(x,()=>{let te=this.getDistributableSnapshot({...e,includeVersion:true});te.version!==Q&&(Q=te.version,n(te));})},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(!chunkBEJ6ICA7_cjs.c(e))throw new Error("[Directive] restore() rejected: snapshot contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");i.batch(()=>{for(let[n,l]of Object.entries(e.facts))chunkWFIJ6OST_cjs.k.has(n)||i.set(n,l);});},onSettledChange(e){return w.add(e),()=>{w.delete(e);}},onHistoryChange(e){return h.add(e),()=>{h.delete(e);}},batch(e){i.batch(e);},get isSettled(){return re.getInflightCount()===0&&!re.hasPendingBatches()&&!j.isReconciling&&!j.reconcileScheduled},get isRunning(){return j.isRunning},get isInitialized(){return j.isInitialized},get isReady(){return j.isReady},whenReady(){return j.isReady?Promise.resolve():j.isRunning?(j.readyPromise||(j.readyPromise=new Promise(e=>{j.readyResolve=e;})),j.readyPromise):Promise.reject(new Error("[Directive] whenReady() called before start(). Call system.start() first, then await system.whenReady()."))}};function $(e){if(j.isReconciling)throw new Error(`[Directive] Cannot register module "${e.id}" during reconciliation. Wait for the current reconciliation cycle to complete.`);if(j.isDestroyed)throw new Error(`[Directive] Cannot register module "${e.id}" on a destroyed system.`);let n=(l,d)=>{if(l)for(let E of Object.keys(l)){if(chunkWFIJ6OST_cjs.k.has(E))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${E}" in ${d}.`);if(d==="schema"&&E.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${E}" 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 l of Object.keys(e.schema))if(l in r)throw new Error(`[Directive] Schema collision: Fact "${l}" already exists. Cannot register module "${e.id}".`);if(process.env.NODE_ENV!=="production"&&e.derive){let l=new Set(Object.keys(r));for(let d of Object.keys(e.derive))l.has(d)&&console.warn(`[Directive] "${d}" exists as both a fact and a derivation after registering module "${e.id}".`);}if(e.history?.snapshotEvents){O===null&&(O=new Set(Object.keys(A)));for(let l of e.history.snapshotEvents)O.add(l);}else if(O!==null&&e.events)for(let l of Object.keys(e.events))O.add(l);Object.assign(r,e.schema);for(let l of Object.values(e.schema)){let d=l;d._meta&&(d._meta=ge(d._meta));}if(e.events){for(let[l,d]of Object.entries(e.events))if(typeof d=="object"&&d!==null&&Object.hasOwn(d,"handler")){let E=d;if(e.events[l]=E.handler,E.meta){let x=ge(E.meta);x&&T.set(l,x);}}Object.assign(A,e.events);}if(e.derive&&(Object.assign(R,e.derive),c.registerDefinitions(e.derive)),e.effects){for(let l of Object.values(e.effects)){let d=l;d.meta&&(d.meta=ge(d.meta));}Object.assign(q,e.effects),D.registerDefinitions(e.effects);}if(e.constraints){for(let l of Object.values(e.constraints)){let d=l;d.meta&&(d.meta=ge(d.meta));}Object.assign(g,e.constraints),X.registerDefinitions(e.constraints);}if(e.resolvers){for(let l of Object.values(e.resolvers)){let d=l;d.meta&&(d.meta=ge(d.meta));}Object.assign(S,e.resolvers),re.registerDefinitions(e.resolvers),ue(e.resolvers);}if(i.registerKeys(e.schema),e.meta){let l=ge(e.meta);l&&_.set(e.id,l);}m.modules.push(e),e.init&&i.batch(()=>{e.init(u);}),e.hooks?.onInit?.(p),j.isRunning&&(e.hooks?.onStart?.(p),me());}p.registerModule=$,C.emitInit(p);for(let e of m.modules)e.hooks?.onInit?.(p);return p}exports.a=Ce;exports.b=be;exports.c=Ze;exports.d=Ye;exports.e=Qe;exports.f=et;exports.g=vt;exports.h=yt;exports.i=Pe;exports.j=Ae;exports.k=nt;exports.l=kt;exports.m=Mt;exports.n=Ct;exports.o=Re;exports.p=$e;exports.q=Fe;exports.r=Ke;exports.s=st;exports.t=_e;exports.u=ct;exports.v=lt;exports.w=We;exports.x=ze;exports.y=Le;exports.z=gn;//# sourceMappingURL=chunk-NZ6EK6W5.cjs.map
|
|
3
|
-
//# sourceMappingURL=chunk-NZ6EK6W5.cjs.map
|