@akashjs/runtime 0.1.27 → 0.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/{chunk-62IX4IG4.js → chunk-367DJVST.js} +3 -3
  2. package/dist/{chunk-62IX4IG4.js.map → chunk-367DJVST.js.map} +1 -1
  3. package/dist/chunk-4PK4YNND.js +2 -0
  4. package/dist/{chunk-FAPX3I6C.js.map → chunk-4PK4YNND.js.map} +1 -1
  5. package/dist/chunk-5NJYYK3Q.js +2 -0
  6. package/dist/{chunk-UKDME6Q2.js.map → chunk-5NJYYK3Q.js.map} +1 -1
  7. package/dist/{chunk-HTRGNLQ3.cjs → chunk-A3VPGLBN.cjs} +2 -2
  8. package/dist/{chunk-HTRGNLQ3.cjs.map → chunk-A3VPGLBN.cjs.map} +1 -1
  9. package/dist/{chunk-QSDVJOXO.js → chunk-CEJF44LZ.js} +2 -2
  10. package/dist/{chunk-QSDVJOXO.js.map → chunk-CEJF44LZ.js.map} +1 -1
  11. package/dist/{chunk-RNEUYA5Z.cjs → chunk-JSBB2VV3.cjs} +2 -2
  12. package/dist/{chunk-RNEUYA5Z.cjs.map → chunk-JSBB2VV3.cjs.map} +1 -1
  13. package/dist/chunk-RTJ6UDGV.cjs +13 -0
  14. package/dist/chunk-RTJ6UDGV.cjs.map +1 -0
  15. package/dist/{chunk-PKLS2KBS.cjs → chunk-TBCX5WQQ.cjs} +3 -3
  16. package/dist/{chunk-PKLS2KBS.cjs.map → chunk-TBCX5WQQ.cjs.map} +1 -1
  17. package/dist/{chunk-X3UYPEA4.js → chunk-TS5UKZTG.js} +2 -2
  18. package/dist/{chunk-X3UYPEA4.js.map → chunk-TS5UKZTG.js.map} +1 -1
  19. package/dist/chunk-TWA4T6PX.js +13 -0
  20. package/dist/chunk-TWA4T6PX.js.map +1 -0
  21. package/dist/{chunk-SHCUCZG5.cjs → chunk-VBAO65QP.cjs} +2 -2
  22. package/dist/{chunk-SHCUCZG5.cjs.map → chunk-VBAO65QP.cjs.map} +1 -1
  23. package/dist/{chunk-XKGVN2FC.js → chunk-WG5GKD3B.js} +3 -3
  24. package/dist/{chunk-XKGVN2FC.js.map → chunk-WG5GKD3B.js.map} +1 -1
  25. package/dist/{chunk-ZMG2PPCB.cjs → chunk-YIVBLM2A.cjs} +3 -3
  26. package/dist/{chunk-ZMG2PPCB.cjs.map → chunk-YIVBLM2A.cjs.map} +1 -1
  27. package/dist/{chunk-UGVQQVQF.cjs → chunk-YN2TQLVA.cjs} +2 -2
  28. package/dist/{chunk-UGVQQVQF.cjs.map → chunk-YN2TQLVA.cjs.map} +1 -1
  29. package/dist/core.cjs +1 -1
  30. package/dist/core.js +1 -1
  31. package/dist/index.cjs +10 -21
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.js +10 -21
  34. package/dist/index.js.map +1 -1
  35. package/dist/machine.cjs +1 -1
  36. package/dist/machine.js +1 -1
  37. package/dist/offline.cjs +1 -1
  38. package/dist/offline.js +1 -1
  39. package/dist/pwa.cjs +1 -1
  40. package/dist/pwa.js +1 -1
  41. package/dist/ssr.cjs +1 -1
  42. package/dist/ssr.js +1 -1
  43. package/dist/store.cjs +1 -1
  44. package/dist/store.js +1 -1
  45. package/dist/sync.cjs +1 -1
  46. package/dist/sync.js +1 -1
  47. package/dist/test.cjs +1 -1
  48. package/dist/test.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-FAPX3I6C.js +0 -2
  51. package/dist/chunk-JGHHEF7H.js +0 -2
  52. package/dist/chunk-JGHHEF7H.js.map +0 -1
  53. package/dist/chunk-MWEB7QDN.cjs +0 -2
  54. package/dist/chunk-MWEB7QDN.cjs.map +0 -1
  55. package/dist/chunk-UKDME6Q2.js +0 -2
@@ -1,5 +1,5 @@
1
- import {e}from'./chunk-JGHHEF7H.js';var v={AK0010:{code:"AK0010",message:"provide() called outside of component setup.",hint:"provide() must be called inside defineComponent()."},AK0012:{code:"AK0012",message:"inject() called outside of component setup.",hint:"inject() must be called inside defineComponent()."},AK0013:{code:"AK0013",message:"No provider found for injected context.",hint:"Make sure an ancestor component calls provide() with this key."},AK0020:{code:"AK0020",message:"onMount() called outside of component setup.",hint:"onMount() must be called inside defineComponent()."},AK0021:{code:"AK0021",message:"onUnmount() called outside of component setup.",hint:"onUnmount() must be called inside defineComponent()."},AK0022:{code:"AK0022",message:"onError() called outside of component setup.",hint:"onError() must be called inside defineComponent()."},AK0030:{code:"AK0030",message:"Circular dependency detected in computed signal.",hint:"A computed signal is reading itself, directly or via other computeds."},AK0031:{code:"AK0031",message:"Signal set() called during computation.",hint:"Do not set signals inside computed() or during effect execution. Use batch() or set signals in event handlers."},AK0040:{code:"AK0040",message:"Component setup must return a render function.",hint:"The function passed to defineComponent() must return () => AkashNode."},AK0041:{code:"AK0041",message:"Required prop is missing.",hint:"Check that the parent component is passing all required props."},AK0050:{code:"AK0050",message:"useRoute() called outside of router context.",hint:"Make sure your component is rendered inside a router provider."},AK0051:{code:"AK0051",message:"No route matched the current URL.",hint:"Add a catch-all route ([...rest]) to handle unmatched paths."},AK0052:{code:"AK0052",message:"Route guard threw an error.",hint:"Check the guard function for unhandled exceptions."},AK0060:{code:"AK0060",message:"Form submitted while invalid.",hint:"The submit handler was not called because validation failed. Check form.errors()."},AK0061:{code:"AK0061",message:"Async validator timed out.",hint:"The async validator did not resolve within the expected time. Check your async validation logic."},AK0070:{code:"AK0070",message:"HTTP request failed.",hint:"Check the server response status and network connectivity."},AK0071:{code:"AK0071",message:"createResource() fetcher threw an error.",hint:"Check the fetcher function passed to createResource()."}},P="https://akashjs.dev/errors";function L(e,n){let t=v[e];if(!t)return `[AkashJS ${e}] Unknown error code.`;let o=`[AkashJS ${e}] ${t.message}`;return n&&(o+=`
1
+ import {n}from'./chunk-TWA4T6PX.js';var v={AK0010:{code:"AK0010",message:"provide() called outside of component setup.",hint:"provide() must be called inside defineComponent()."},AK0012:{code:"AK0012",message:"inject() called outside of component setup.",hint:"inject() must be called inside defineComponent()."},AK0013:{code:"AK0013",message:"No provider found for injected context.",hint:"Make sure an ancestor component calls provide() with this key."},AK0020:{code:"AK0020",message:"onMount() called outside of component setup.",hint:"onMount() must be called inside defineComponent()."},AK0021:{code:"AK0021",message:"onUnmount() called outside of component setup.",hint:"onUnmount() must be called inside defineComponent()."},AK0022:{code:"AK0022",message:"onError() called outside of component setup.",hint:"onError() must be called inside defineComponent()."},AK0030:{code:"AK0030",message:"Circular dependency detected in computed signal.",hint:"A computed signal is reading itself, directly or via other computeds."},AK0031:{code:"AK0031",message:"Signal set() called during computation.",hint:"Do not set signals inside computed() or during effect execution. Use batch() or set signals in event handlers."},AK0040:{code:"AK0040",message:"Component setup must return a render function.",hint:"The function passed to defineComponent() must return () => AkashNode."},AK0041:{code:"AK0041",message:"Required prop is missing.",hint:"Check that the parent component is passing all required props."},AK0050:{code:"AK0050",message:"useRoute() called outside of router context.",hint:"Make sure your component is rendered inside a router provider."},AK0051:{code:"AK0051",message:"No route matched the current URL.",hint:"Add a catch-all route ([...rest]) to handle unmatched paths."},AK0052:{code:"AK0052",message:"Route guard threw an error.",hint:"Check the guard function for unhandled exceptions."},AK0060:{code:"AK0060",message:"Form submitted while invalid.",hint:"The submit handler was not called because validation failed. Check form.errors()."},AK0061:{code:"AK0061",message:"Async validator timed out.",hint:"The async validator did not resolve within the expected time. Check your async validation logic."},AK0070:{code:"AK0070",message:"HTTP request failed.",hint:"Check the server response status and network connectivity."},AK0071:{code:"AK0071",message:"createResource() fetcher threw an error.",hint:"Check the fetcher function passed to createResource()."}},P="https://akashjs.dev/errors";function L(e,n){let t=v[e];if(!t)return `[AkashJS ${e}] Unknown error code.`;let o=`[AkashJS ${e}] ${t.message}`;return n&&(o+=`
2
2
  ${n}`),o+=`
3
3
  ${t.hint}`,o+=`
4
- See: ${P}/${e}`,o}function g(e,n){return new Error(L(e,n))}function D(e){return v[e]}function F(){return Object.keys(v)}var M=Symbol("akash.context"),p=null;function S(e=p){let n={values:new Map,parent:e};return p=n,n}function w(e){p=e.parent;}function C(){return p}function K(e,n){let t=p;p=e;try{return n()}finally{p=t;}}function I(e){return {[M]:true,_type:void 0,defaultValue:e,id:Symbol("context")}}function B(e,n){if(!p)throw g("AK0010");p.values.set(e.id,n);}function O(e,n){if(!p)throw g("AK0012");let t=p;for(;t;){if(t.values.has(e.id))return t.values.get(e.id);t=t.parent;}if(n!==void 0)return n;if(e.defaultValue!==void 0)return e.defaultValue;throw g("AK0013")}function q(e,n){let t=document.createElement(e);if(n)for(let[o,a]of Object.entries(n))E(t,o,a);return t}function J(e){return document.createTextNode(e)}function W(e){let n=document.createElement("template");return n.innerHTML=e,n.content.cloneNode(true)}function E(e,n,t){if(n==="class"||n==="className")e.className=t;else if(n==="style"&&typeof t=="object"&&t!==null)Object.assign(e.style,t);else if(n==="innerHTML")e.innerHTML=t;else if(n!=="ref")if(n.startsWith("on")){let o=n.slice(2).toLowerCase();e.addEventListener(o,t);}else n in e?e[n]=t:t===false||t==null?e.removeAttribute(n):e.setAttribute(n,t===true?"":String(t));}function X(e$1,n){return e(()=>{e$1.textContent=String(n());},{render:true})}function z(e$1,n,t){return e(()=>{E(e$1,n,t());},{render:true})}function G(e$1,n){return e(()=>{e$1.style.display=n()?"":"none";},{render:true})}function b(e=""){return document.createComment(e)}function R(e$1,n,t,o,a){let s=null,A=C(),N=e(()=>{let i=t();if(s){for(let l of s.nodes)try{l.parentNode?.removeChild(l);}catch{}s.dispose?.(),s=null;}let d=i?o:a,h=n.parentNode;if(d&&h){let l=A?K(A,d):d(),r=l instanceof DocumentFragment?Array.from(l.childNodes):[l];for(let c of r)h.insertBefore(c,n);s={nodes:r,dispose:null};}},{render:true});return ()=>{if(N(),s){for(let i of s.nodes)try{i.parentNode?.removeChild(i);}catch{}s.dispose?.();}}}function j(e$1,n,t,o,a){let s=[],A=C(),N=e(()=>{let i=t(),d=[],h=new Map;for(let r of s)h.set(r.key,r);for(let r=0;r<i.length;r++){let c=i[r],u=o(c,r),f=h.get(u);if(f)h.delete(u),f.value=c,d.push(f);else {let T=A?K(A,()=>a(c,r)):a(c,r),y=T instanceof DocumentFragment?Array.from(T.childNodes):[T];d.push({key:u,value:c,nodes:y,dispose:null});}}for(let r of h.values()){for(let c of r.nodes)c.parentNode&&c.parentNode.removeChild(c);r.dispose?.();}let l=n.parentNode;if(l)for(let r of d)for(let c of r.nodes)l.insertBefore(c,n);s=d;},{render:true});return ()=>{N();for(let i of s){for(let d of i.nodes)d.parentNode&&d.parentNode.removeChild(d);i.dispose?.();}s=[];}}function Q(e){let n=b("show"),t=document.createDocumentFragment();t.appendChild(n);let o=typeof e.when=="function"?e.when:()=>e.when,a;return R(t,n,()=>(a=o(),!!a),()=>x(e.children(a)),e.fallback?()=>x(e.fallback()):void 0),t}function Y(e){let n=b("for"),t=document.createDocumentFragment();t.appendChild(n);let o=typeof e.each=="function"?e.each:()=>e.each;return j(t,n,o,e.key,(a,s)=>x(e.children(a,s))),t}function x(e){if(e==null||typeof e=="boolean")return document.createTextNode("");if(typeof e=="string"||typeof e=="number")return document.createTextNode(String(e));if(e instanceof Node)return e;if(Array.isArray(e)){let n=document.createDocumentFragment();for(let t of e)n.appendChild(x(t));return n}return document.createTextNode(String(e))}function Z(e,n,t){let o=x(n);t?e.insertBefore(o,t):e.appendChild(o);}function re(e){return e.__reactive=true,e}var m=null;function ie(e){if(!m)throw g("AK0020");m.mount.push(e);}function se(e){if(!m)throw g("AK0021");m.unmount.push(e);}function ce(e){if(!m)throw g("AK0022");m.error.push(e);}function de(){return {current:void 0}}function ae(e){let n=t=>{let{children:o,...a}=t??{},N={props:new Proxy(a,{get(u,f,T){let y=Reflect.get(u,f,T);return typeof y=="function"&&y.__reactive?y():y}}),children:typeof o=="function"?o:()=>o??null},i={mount:[],unmount:[],error:[]},d=m;m=i;let h=C(),l=S(h),r,c;try{if(r=e(N),typeof r!="function")throw g("AK0040");let u=r();c=x(u);}catch(u){if(w(l),m=d,i.error.length>0){for(let f of i.error)f(u instanceof Error?u:new Error(String(u)));return document.createComment("error")}throw u}return w(l),m=d,i.mount.length>0&&queueMicrotask(()=>{for(let u of i.mount)try{let f=u();typeof f=="function"&&i.unmount.push(f);}catch(f){for(let T of i.error)T(f instanceof Error?f:new Error(String(f)));}}),c};return n._akash=true,n}export{de as A,ae as B,L as a,g as b,D as c,F as d,C as e,K as f,I as g,B as h,O as i,q as j,J as k,W as l,E as m,X as n,z as o,G as p,R as q,j as r,Q as s,Y as t,x as u,Z as v,re as w,ie as x,se as y,ce as z};//# sourceMappingURL=chunk-62IX4IG4.js.map
5
- //# sourceMappingURL=chunk-62IX4IG4.js.map
4
+ See: ${P}/${e}`,o}function g(e,n){return new Error(L(e,n))}function D(e){return v[e]}function F(){return Object.keys(v)}var M=Symbol("akash.context"),p=null;function S(e=p){let n={values:new Map,parent:e};return p=n,n}function w(e){p=e.parent;}function C(){return p}function K(e,n){let t=p;p=e;try{return n()}finally{p=t;}}function I(e){return {[M]:true,_type:void 0,defaultValue:e,id:Symbol("context")}}function B(e,n){if(!p)throw g("AK0010");p.values.set(e.id,n);}function O(e,n){if(!p)throw g("AK0012");let t=p;for(;t;){if(t.values.has(e.id))return t.values.get(e.id);t=t.parent;}if(n!==void 0)return n;if(e.defaultValue!==void 0)return e.defaultValue;throw g("AK0013")}function q(e,n){let t=document.createElement(e);if(n)for(let[o,a]of Object.entries(n))E(t,o,a);return t}function J(e){return document.createTextNode(e)}function W(e){let n=document.createElement("template");return n.innerHTML=e,n.content.cloneNode(true)}function E(e,n,t){if(n==="class"||n==="className")e.className=t;else if(n==="style"&&typeof t=="object"&&t!==null)Object.assign(e.style,t);else if(n==="innerHTML")e.innerHTML=t;else if(n!=="ref")if(n.startsWith("on")){let o=n.slice(2).toLowerCase();e.addEventListener(o,t);}else n in e?e[n]=t:t===false||t==null?e.removeAttribute(n):e.setAttribute(n,t===true?"":String(t));}function X(e,n$1){return n(()=>{e.textContent=String(n$1());},{render:true})}function z(e,n$1,t){return n(()=>{E(e,n$1,t());},{render:true})}function G(e,n$1){return n(()=>{e.style.display=n$1()?"":"none";},{render:true})}function b(e=""){return document.createComment(e)}function R(e,n$1,t,o,a){let s=null,A=C(),N=n(()=>{let i=t();if(s){for(let l of s.nodes)try{l.parentNode?.removeChild(l);}catch{}s.dispose?.(),s=null;}let d=i?o:a,h=n$1.parentNode;if(d&&h){let l=A?K(A,d):d(),r=l instanceof DocumentFragment?Array.from(l.childNodes):[l];for(let c of r)h.insertBefore(c,n$1);s={nodes:r,dispose:null};}},{render:true});return ()=>{if(N(),s){for(let i of s.nodes)try{i.parentNode?.removeChild(i);}catch{}s.dispose?.();}}}function j(e,n$1,t,o,a){let s=[],A=C(),N=n(()=>{let i=t(),d=[],h=new Map;for(let r of s)h.set(r.key,r);for(let r=0;r<i.length;r++){let c=i[r],u=o(c,r),f=h.get(u);if(f)h.delete(u),f.value=c,d.push(f);else {let T=A?K(A,()=>a(c,r)):a(c,r),y=T instanceof DocumentFragment?Array.from(T.childNodes):[T];d.push({key:u,value:c,nodes:y,dispose:null});}}for(let r of h.values()){for(let c of r.nodes)c.parentNode&&c.parentNode.removeChild(c);r.dispose?.();}let l=n$1.parentNode;if(l)for(let r of d)for(let c of r.nodes)l.insertBefore(c,n$1);s=d;},{render:true});return ()=>{N();for(let i of s){for(let d of i.nodes)d.parentNode&&d.parentNode.removeChild(d);i.dispose?.();}s=[];}}function Q(e){let n=b("show"),t=document.createDocumentFragment();t.appendChild(n);let o=typeof e.when=="function"?e.when:()=>e.when,a;return R(t,n,()=>(a=o(),!!a),()=>x(e.children(a)),e.fallback?()=>x(e.fallback()):void 0),t}function Y(e){let n=b("for"),t=document.createDocumentFragment();t.appendChild(n);let o=typeof e.each=="function"?e.each:()=>e.each;return j(t,n,o,e.key,(a,s)=>x(e.children(a,s))),t}function x(e){if(e==null||typeof e=="boolean")return document.createTextNode("");if(typeof e=="string"||typeof e=="number")return document.createTextNode(String(e));if(e instanceof Node)return e;if(Array.isArray(e)){let n=document.createDocumentFragment();for(let t of e)n.appendChild(x(t));return n}return document.createTextNode(String(e))}function Z(e,n,t){let o=x(n);t?e.insertBefore(o,t):e.appendChild(o);}function re(e){return e.__reactive=true,e}var m=null;function ie(e){if(!m)throw g("AK0020");m.mount.push(e);}function se(e){if(!m)throw g("AK0021");m.unmount.push(e);}function ce(e){if(!m)throw g("AK0022");m.error.push(e);}function de(){return {current:void 0}}function ae(e){let n=t=>{let{children:o,...a}=t??{},N={props:new Proxy(a,{get(u,f,T){let y=Reflect.get(u,f,T);return typeof y=="function"&&y.__reactive?y():y}}),children:typeof o=="function"?o:()=>o??null},i={mount:[],unmount:[],error:[]},d=m;m=i;let h=C(),l=S(h),r,c;try{if(r=e(N),typeof r!="function")throw g("AK0040");let u=r();c=x(u);}catch(u){if(w(l),m=d,i.error.length>0){for(let f of i.error)f(u instanceof Error?u:new Error(String(u)));return document.createComment("error")}throw u}return w(l),m=d,i.mount.length>0&&queueMicrotask(()=>{for(let u of i.mount)try{let f=u();typeof f=="function"&&i.unmount.push(f);}catch(f){for(let T of i.error)T(f instanceof Error?f:new Error(String(f)));}}),c};return n._akash=true,n}export{de as A,ae as B,L as a,g as b,D as c,F as d,C as e,K as f,I as g,B as h,O as i,q as j,J as k,W as l,E as m,X as n,z as o,G as p,R as q,j as r,Q as s,Y as t,x as u,Z as v,re as w,ie as x,se as y,ce as z};//# sourceMappingURL=chunk-367DJVST.js.map
5
+ //# sourceMappingURL=chunk-367DJVST.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/context.ts","../src/dom.ts","../src/component.ts"],"names":["errors","DOC_BASE","formatError","code","context","def","msg","akashError","getErrorDef","getAllErrorCodes","CONTEXT_BRAND","currentScope","pushScope","parent","scope","popScope","getCurrentScope","runInScope","fn","prev","createContext","defaultValue","provide","key","value","inject","fallback","createElement","tag","attrs","el","setProperty","createText","cloneTemplate","html","template","event","bindText","node","effect","bindProperty","bindVisible","createAnchor","label","renderConditional","anchor","condition","trueBranch","falseBranch","current","dispose","branch","liveParent","fragment","nodes","renderList","items","keyFn","renderItem","currentItems","newData","newItems","oldMap","item","i","data","existing","Show","props","container","getWhen","whenValue","nodeToDOM","For","getEach","index","child","insert","domNode","__getter","currentHooks","onMount","onUnmount","onError","ref","defineComponent","setup","component","rawProps","childrenProp","restProps","ctx","target","receiver","val","hooks","prevHooks","parentScope","renderFn","rendered","err","handler","mountFn","cleanup"],"mappings":"oCAqBA,IAAMA,EAAmC,CAEvC,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,8CAAA,CACT,IAAA,CAAM,oDACR,CAAA,CACA,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,6CAAA,CACT,IAAA,CAAM,mDACR,CAAA,CACA,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,yCAAA,CACT,IAAA,CAAM,gEACR,CAAA,CAGA,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,8CAAA,CACT,IAAA,CAAM,oDACR,CAAA,CACA,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,gDAAA,CACT,IAAA,CAAM,sDACR,CAAA,CACA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,8CAAA,CACT,KAAM,oDACR,CAAA,CAGA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,kDAAA,CACT,KAAM,uEACR,CAAA,CACA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,yCAAA,CACT,KAAM,gHACR,CAAA,CAGA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,gDAAA,CACT,KAAM,uEACR,CAAA,CACA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,2BAAA,CACT,KAAM,gEACR,CAAA,CAGA,MAAA,CAAQ,CACN,KAAM,QAAA,CACN,OAAA,CAAS,+CACT,IAAA,CAAM,gEACR,EACA,MAAA,CAAQ,CACN,KAAM,QAAA,CACN,OAAA,CAAS,o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,CAAc,OAAO,CACvC,CACA,MAAMA,CACR,CAGA,OAAArF,CAAAA,CAASD,CAAK,CAAA,CACdkE,CAAAA,CAAegB,CAAAA,CAGXD,CAAAA,CAAM,KAAA,CAAM,MAAA,CAAS,GACvB,cAAA,CAAe,IAAM,CACnB,IAAA,IAAWO,KAAWP,CAAAA,CAAM,KAAA,CAC1B,GAAI,CACF,IAAMQ,CAAAA,CAAUD,CAAAA,EAAQ,CACpB,OAAOC,CAAAA,EAAY,UAAA,EACrBR,CAAAA,CAAM,OAAA,CAAQ,KAAKQ,CAAO,EAE9B,CAAA,MAASH,CAAAA,CAAK,CACZ,IAAA,IAAWC,CAAAA,IAAWN,CAAAA,CAAM,KAAA,CAC1BM,EAAQD,CAAAA,YAAe,KAAA,CAAQA,CAAAA,CAAM,IAAI,KAAA,CAAM,MAAA,CAAOA,CAAG,CAAC,CAAC,EAE/D,CAEJ,CAAC,CAAA,CAGItB,CACT,CAAA,CAEA,OAAAS,CAAAA,CAAU,MAAA,CAAS,KACZA,CACT","file":"chunk-62IX4IG4.js","sourcesContent":["/**\n * Error message catalog.\n *\n * Every AkashJS runtime error has a unique code (AK0001, AK0002, etc.),\n * a one-line description, and a link to detailed documentation.\n *\n * Usage:\n * throw akashError('AK0010', 'provide()');\n */\n\n// --- Error registry ---\n\nexport interface ErrorDef {\n /** Error code */\n code: string;\n /** Short description */\n message: string;\n /** Extended explanation and fix suggestion */\n hint: string;\n}\n\nconst errors: Record<string, ErrorDef> = {\n // --- Context errors (AK001x) ---\n AK0010: {\n code: 'AK0010',\n message: 'provide() called outside of component setup.',\n hint: 'provide() must be called inside defineComponent().',\n },\n AK0012: {\n code: 'AK0012',\n message: 'inject() called outside of component setup.',\n hint: 'inject() must be called inside defineComponent().',\n },\n AK0013: {\n code: 'AK0013',\n message: 'No provider found for injected context.',\n hint: 'Make sure an ancestor component calls provide() with this key.',\n },\n\n // --- Lifecycle errors (AK002x) ---\n AK0020: {\n code: 'AK0020',\n message: 'onMount() called outside of component setup.',\n hint: 'onMount() must be called inside defineComponent().',\n },\n AK0021: {\n code: 'AK0021',\n message: 'onUnmount() called outside of component setup.',\n hint: 'onUnmount() must be called inside defineComponent().',\n },\n AK0022: {\n code: 'AK0022',\n message: 'onError() called outside of component setup.',\n hint: 'onError() must be called inside defineComponent().',\n },\n\n // --- Signal errors (AK003x) ---\n AK0030: {\n code: 'AK0030',\n message: 'Circular dependency detected in computed signal.',\n hint: 'A computed signal is reading itself, directly or via other computeds.',\n },\n AK0031: {\n code: 'AK0031',\n message: 'Signal set() called during computation.',\n hint: 'Do not set signals inside computed() or during effect execution. Use batch() or set signals in event handlers.',\n },\n\n // --- Component errors (AK004x) ---\n AK0040: {\n code: 'AK0040',\n message: 'Component setup must return a render function.',\n hint: 'The function passed to defineComponent() must return () => AkashNode.',\n },\n AK0041: {\n code: 'AK0041',\n message: 'Required prop is missing.',\n hint: 'Check that the parent component is passing all required props.',\n },\n\n // --- Router errors (AK005x) ---\n AK0050: {\n code: 'AK0050',\n message: 'useRoute() called outside of router context.',\n hint: 'Make sure your component is rendered inside a router provider.',\n },\n AK0051: {\n code: 'AK0051',\n message: 'No route matched the current URL.',\n hint: 'Add a catch-all route ([...rest]) to handle unmatched paths.',\n },\n AK0052: {\n code: 'AK0052',\n message: 'Route guard threw an error.',\n hint: 'Check the guard function for unhandled exceptions.',\n },\n\n // --- Form errors (AK006x) ---\n AK0060: {\n code: 'AK0060',\n message: 'Form submitted while invalid.',\n hint: 'The submit handler was not called because validation failed. Check form.errors().',\n },\n AK0061: {\n code: 'AK0061',\n message: 'Async validator timed out.',\n hint: 'The async validator did not resolve within the expected time. Check your async validation logic.',\n },\n\n // --- HTTP errors (AK007x) ---\n AK0070: {\n code: 'AK0070',\n message: 'HTTP request failed.',\n hint: 'Check the server response status and network connectivity.',\n },\n AK0071: {\n code: 'AK0071',\n message: 'createResource() fetcher threw an error.',\n hint: 'Check the fetcher function passed to createResource().',\n },\n};\n\n// --- Public API ---\n\nconst DOC_BASE = 'https://akashjs.dev/errors';\n\n/**\n * Format an AkashJS error with code, message, hint, and doc link.\n */\nexport function formatError(code: string, context?: string): string {\n const def = errors[code];\n if (!def) {\n return `[AkashJS ${code}] Unknown error code.`;\n }\n\n let msg = `[AkashJS ${code}] ${def.message}`;\n if (context) {\n msg += `\\n ${context}`;\n }\n msg += `\\n ${def.hint}`;\n msg += `\\n See: ${DOC_BASE}/${code}`;\n return msg;\n}\n\n/**\n * Create and throw an AkashJS error.\n */\nexport function akashError(code: string, context?: string): Error {\n return new Error(formatError(code, context));\n}\n\n/**\n * Get the error definition for a code.\n */\nexport function getErrorDef(code: string): ErrorDef | undefined {\n return errors[code];\n}\n\n/**\n * Get all registered error codes.\n */\nexport function getAllErrorCodes(): string[] {\n return Object.keys(errors);\n}\n","/**\n * Lightweight dependency injection via provide/inject.\n *\n * Context is scoped to the component tree — no injector hierarchy,\n * no decorators, no classes. Just createContext(), provide(), inject().\n */\n\n// --- Types ---\n\nimport { akashError } from './errors.js';\n\nconst CONTEXT_BRAND = Symbol('akash.context');\n\nexport interface InjectionKey<T> {\n readonly [CONTEXT_BRAND]: true;\n readonly _type: T; // phantom type — never used at runtime\n readonly defaultValue: T | undefined;\n readonly id: symbol;\n}\n\n// --- Context stack (managed by component system) ---\n\ninterface ContextScope {\n values: Map<symbol, unknown>;\n parent: ContextScope | null;\n}\n\nlet currentScope: ContextScope | null = null;\n\n/** @internal — called by defineComponent to push/pop context scopes */\nexport function pushScope(parent: ContextScope | null = currentScope): ContextScope {\n const scope: ContextScope = { values: new Map(), parent };\n currentScope = scope;\n return scope;\n}\n\n/** @internal */\nexport function popScope(scope: ContextScope): void {\n currentScope = scope.parent;\n}\n\n/** @internal */\nexport function getCurrentScope(): ContextScope | null {\n return currentScope;\n}\n\n/**\n * Run a function within a given scope so that provide/inject\n * work correctly for components created asynchronously\n * (e.g., lazy-loaded route components).\n */\nexport function runInScope<T>(scope: ContextScope, fn: () => T): T {\n const prev = currentScope;\n currentScope = scope;\n try {\n return fn();\n } finally {\n currentScope = prev;\n }\n}\n\n// --- Public API ---\n\n/**\n * Create a typed context key with an optional default value.\n *\n * ```ts\n * const ThemeContext = createContext<'light' | 'dark'>('light');\n * ```\n */\nexport function createContext<T>(defaultValue?: T): InjectionKey<T> {\n return {\n [CONTEXT_BRAND]: true,\n _type: undefined as T,\n defaultValue,\n id: Symbol('context'),\n };\n}\n\n/**\n * Provide a value for a context key in the current component scope.\n * All descendant components can inject() this value.\n *\n * Must be called inside defineComponent() setup.\n */\nexport function provide<T>(key: InjectionKey<T>, value: T): void {\n if (!currentScope) {\n throw akashError('AK0010');\n }\n currentScope.values.set(key.id, value);\n}\n\n/**\n * Inject a value from the nearest ancestor that provided it.\n *\n * Must be called inside defineComponent() setup.\n */\nexport function inject<T>(key: InjectionKey<T>): T;\nexport function inject<T>(key: InjectionKey<T>, fallback: T): T;\nexport function inject<T>(key: InjectionKey<T>, fallback?: T): T {\n if (!currentScope) {\n throw akashError('AK0012');\n }\n\n // Walk up the scope chain\n let scope: ContextScope | null = currentScope;\n while (scope) {\n if (scope.values.has(key.id)) {\n return scope.values.get(key.id) as T;\n }\n scope = scope.parent;\n }\n\n // Check fallback, then default\n if (fallback !== undefined) return fallback;\n if (key.defaultValue !== undefined) return key.defaultValue;\n\n throw akashError('AK0013');\n}\n","/**\n * Direct DOM rendering runtime.\n *\n * No virtual DOM. The compiler generates calls to these helpers.\n * Signal reads inside templates become fine-grained effects that\n * update only the specific DOM node that changed.\n */\n\nimport { effect } from './signals.js';\nimport { getCurrentScope, runInScope } from './context.js';\nimport type { AkashNode } from './types.js';\n\n// --- DOM creation helpers (used by compiler output) ---\n\n/** Create an element and optionally set static attributes */\nexport function createElement(\n tag: string,\n attrs?: Record<string, unknown>,\n): HTMLElement {\n const el = document.createElement(tag);\n if (attrs) {\n for (const [key, value] of Object.entries(attrs)) {\n setProperty(el, key, value);\n }\n }\n return el;\n}\n\n/** Create a text node */\nexport function createText(value: string): Text {\n return document.createTextNode(value);\n}\n\n/** Clone a template element for static structure */\nexport function cloneTemplate(html: string): DocumentFragment {\n const template = document.createElement('template');\n template.innerHTML = html;\n return template.content.cloneNode(true) as DocumentFragment;\n}\n\n// --- Property/attribute setting ---\n\nexport function setProperty(el: HTMLElement, key: string, value: unknown): void {\n if (key === 'class' || key === 'className') {\n el.className = value as string;\n } else if (key === 'style' && typeof value === 'object' && value !== null) {\n Object.assign(el.style, value);\n } else if (key === 'innerHTML') {\n el.innerHTML = value as string;\n } else if (key === 'ref') {\n // Handled separately by component system\n } else if (key.startsWith('on')) {\n const event = key.slice(2).toLowerCase();\n el.addEventListener(event, value as EventListener);\n } else if (key in el) {\n (el as Record<string, unknown>)[key] = value;\n } else if (value === false || value == null) {\n el.removeAttribute(key);\n } else {\n el.setAttribute(key, value === true ? '' : String(value));\n }\n}\n\n// --- Reactive binding (used by compiler for dynamic expressions) ---\n\n/** Bind a reactive expression to a text node's content */\nexport function bindText(node: Text, fn: () => unknown): () => void {\n return effect(\n () => {\n node.textContent = String(fn());\n },\n { render: true },\n );\n}\n\n/** Bind a reactive expression to an element's attribute/property */\nexport function bindProperty(\n el: HTMLElement,\n key: string,\n fn: () => unknown,\n): () => void {\n return effect(\n () => {\n setProperty(el, key, fn());\n },\n { render: true },\n );\n}\n\n/** Bind a reactive expression to an element's visibility (display) */\nexport function bindVisible(el: HTMLElement, fn: () => boolean): () => void {\n return effect(\n () => {\n el.style.display = fn() ? '' : 'none';\n },\n { render: true },\n );\n}\n\n// --- Conditional rendering ---\n\n/** Anchor node type for marking insertion points */\ntype Anchor = Comment;\n\nfunction createAnchor(label = ''): Anchor {\n return document.createComment(label);\n}\n\ninterface ConditionalBlock {\n nodes: Node[];\n dispose: (() => void) | null;\n}\n\n/**\n * Render a conditional block. Swaps DOM fragments based on a reactive\n * condition. Used by the compiler for :if directives and <Show>.\n */\nexport function renderConditional(\n parent: Node,\n anchor: Node,\n condition: () => boolean,\n trueBranch: () => Node,\n falseBranch?: () => Node,\n): () => void {\n let current: ConditionalBlock | null = null;\n\n // Capture scope so children created in branches inherit provide/inject context\n const scope = getCurrentScope();\n\n const dispose = effect(\n () => {\n const value = condition();\n\n // Remove old nodes\n if (current) {\n for (const node of current.nodes) {\n try { node.parentNode?.removeChild(node); } catch {}\n }\n current.dispose?.();\n current = null;\n }\n\n // Insert new nodes — use anchor.parentNode since the anchor may have\n // moved from the initial DocumentFragment into the real DOM\n const branch = value ? trueBranch : falseBranch;\n const liveParent = anchor.parentNode;\n if (branch && liveParent) {\n const fragment = scope ? runInScope(scope, branch) : branch();\n const nodes = fragment instanceof DocumentFragment\n ? Array.from(fragment.childNodes)\n : [fragment];\n for (const node of nodes) {\n liveParent.insertBefore(node, anchor);\n }\n current = { nodes, dispose: null };\n }\n },\n { render: true },\n );\n\n return () => {\n dispose();\n if (current) {\n for (const node of current.nodes) {\n try { node.parentNode?.removeChild(node); } catch {}\n }\n current.dispose?.();\n }\n };\n}\n\n// --- List rendering ---\n\ninterface ListItem<T> {\n key: unknown;\n value: T;\n nodes: Node[];\n dispose: (() => void) | null;\n}\n\n/**\n * Render a reactive list with keyed reconciliation.\n * Used by the compiler for :for directives and <For>.\n */\nexport function renderList<T>(\n parent: Node,\n anchor: Node,\n items: () => T[],\n keyFn: (item: T, index: number) => unknown,\n renderItem: (item: T, index: number) => Node,\n): () => void {\n let currentItems: ListItem<T>[] = [];\n\n // Capture scope so children created in renderItem inherit provide/inject context\n const scope = getCurrentScope();\n\n const dispose = effect(\n () => {\n const newData = items();\n const newItems: ListItem<T>[] = [];\n const oldMap = new Map<unknown, ListItem<T>>();\n\n for (const item of currentItems) {\n oldMap.set(item.key, item);\n }\n\n // Build new list, reuse existing DOM nodes when keys match\n for (let i = 0; i < newData.length; i++) {\n const data = newData[i];\n const key = keyFn(data, i);\n const existing = oldMap.get(key);\n\n if (existing) {\n oldMap.delete(key);\n existing.value = data;\n newItems.push(existing);\n } else {\n const fragment = scope ? runInScope(scope, () => renderItem(data, i)) : renderItem(data, i);\n const nodes = fragment instanceof DocumentFragment\n ? Array.from(fragment.childNodes)\n : [fragment];\n newItems.push({ key, value: data, nodes, dispose: null });\n }\n }\n\n // Remove items that are no longer in the list\n for (const item of oldMap.values()) {\n for (const node of item.nodes) {\n if (node.parentNode) node.parentNode.removeChild(node);\n }\n item.dispose?.();\n }\n\n // Reconcile DOM order — use anchor.parentNode since anchor may have\n // moved from the initial DocumentFragment into the real DOM\n const liveParent = anchor.parentNode;\n if (liveParent) {\n for (const item of newItems) {\n for (const node of item.nodes) {\n liveParent.insertBefore(node, anchor);\n }\n }\n }\n\n currentItems = newItems;\n },\n { render: true },\n );\n\n return () => {\n dispose();\n for (const item of currentItems) {\n for (const node of item.nodes) {\n if (node.parentNode) node.parentNode.removeChild(node);\n }\n item.dispose?.();\n }\n currentItems = [];\n };\n}\n\n// --- Built-in control flow components ---\n\n/** Props for the <Show> component */\nexport interface ShowProps<T> {\n when: (() => T | null | undefined | false) | T | null | undefined | false;\n fallback?: () => AkashNode;\n children: (value: T) => AkashNode;\n}\n\n/**\n * <Show> component — conditionally renders children with type narrowing.\n * The children callback receives the non-null/undefined value.\n * `when` can be a reactive getter or a static value.\n */\nexport function Show<T>(props: ShowProps<T>): Node {\n const anchor = createAnchor('show');\n const container = document.createDocumentFragment();\n container.appendChild(anchor);\n\n // Resolve when — if it's a function, always call it (supports both\n // compiler-generated __reactive getters and plain programmatic functions)\n const getWhen = typeof props.when === 'function'\n ? props.when as () => T | null | undefined | false\n : () => props.when as T | null | undefined | false;\n\n // Capture the when value once per evaluation so the condition check\n // and the children callback receive the same value (fixes nested For contexts)\n let whenValue: T | null | undefined | false;\n renderConditional(\n container,\n anchor,\n () => { whenValue = getWhen(); return !!whenValue; },\n () => nodeToDOM(props.children(whenValue as T)),\n props.fallback ? () => nodeToDOM(props.fallback!()) : undefined,\n );\n\n return container;\n}\n\n/** Props for the <For> component */\nexport interface ForProps<T> {\n each: (() => T[]) | T[];\n key: (item: T) => unknown;\n children: (item: T, index: number) => AkashNode;\n}\n\n/**\n * <For> component — renders a list with keyed reconciliation.\n * `each` can be a reactive getter or a static array.\n */\nexport function For<T>(props: ForProps<T>): Node {\n const anchor = createAnchor('for');\n const container = document.createDocumentFragment();\n container.appendChild(anchor);\n\n // Resolve each — if it's a function, always call it (supports both\n // compiler-generated __reactive getters and plain programmatic functions)\n const getEach = typeof props.each === 'function'\n ? props.each as () => T[]\n : () => props.each as T[];\n\n renderList(\n container,\n anchor,\n getEach,\n props.key,\n (item, index) => nodeToDOM(props.children(item, index)),\n );\n\n return container;\n}\n\n// --- Helpers ---\n\n/** Convert an AkashNode to a DOM Node */\nexport function nodeToDOM(node: AkashNode): Node {\n if (node == null || typeof node === 'boolean') {\n return document.createTextNode('');\n }\n if (typeof node === 'string' || typeof node === 'number') {\n return document.createTextNode(String(node));\n }\n if (node instanceof Node) {\n return node;\n }\n if (Array.isArray(node)) {\n const fragment = document.createDocumentFragment();\n for (const child of node) {\n fragment.appendChild(nodeToDOM(child));\n }\n return fragment;\n }\n return document.createTextNode(String(node));\n}\n\n/** Insert a node into a parent before an anchor */\nexport function insert(parent: Node, node: AkashNode, anchor?: Node): void {\n const domNode = nodeToDOM(node);\n if (anchor) {\n parent.insertBefore(domNode, anchor);\n } else {\n parent.appendChild(domNode);\n }\n}\n","/**\n * Component system.\n *\n * Components are functions. defineComponent() wraps a setup function\n * that runs once, establishes signals and effects, and returns a\n * render function that produces DOM nodes.\n */\n\nimport { effect } from './signals.js';\nimport { pushScope, popScope, getCurrentScope } from './context.js';\nimport { nodeToDOM } from './dom.js';\nimport { akashError } from './errors.js';\nimport type { AkashNode } from './types.js';\n\n// --- Reactive getter marker (used by compiler) ---\n\n/** Mark a function as a compiler-generated reactive getter */\nexport function __getter<T>(fn: () => T): (() => T) & { __reactive: true } {\n (fn as any).__reactive = true;\n return fn as any;\n}\n\n// --- Types ---\n\nexport interface Ref<T = HTMLElement> {\n current: T | undefined;\n}\n\nexport interface ComponentContext<P extends Record<string, unknown> = Record<string, unknown>> {\n props: Readonly<P>;\n children: () => AkashNode;\n}\n\nexport type Component<P extends Record<string, unknown> = Record<string, unknown>> = {\n (props: P & { children?: AkashNode | (() => AkashNode) }): Node;\n _akash: true;\n};\n\n// --- Lifecycle hook storage ---\n\ninterface LifecycleHooks {\n mount: Array<() => void | (() => void)>;\n unmount: Array<() => void>;\n error: Array<(error: Error) => void>;\n}\n\nlet currentHooks: LifecycleHooks | null = null;\n\n// --- Public lifecycle hooks ---\n\n/**\n * Register a callback to run after the component is mounted to the DOM.\n * If the callback returns a function, it will be called on unmount (cleanup).\n */\nexport function onMount(fn: () => void | (() => void)): void {\n if (!currentHooks) {\n throw akashError('AK0020');\n }\n currentHooks.mount.push(fn);\n}\n\n/**\n * Register a callback to run before the component is unmounted.\n */\nexport function onUnmount(fn: () => void): void {\n if (!currentHooks) {\n throw akashError('AK0021');\n }\n currentHooks.unmount.push(fn);\n}\n\n/**\n * Register an error handler for this component and its descendants.\n */\nexport function onError(fn: (error: Error) => void): void {\n if (!currentHooks) {\n throw akashError('AK0022');\n }\n currentHooks.error.push(fn);\n}\n\n/**\n * Create a ref for accessing a DOM element.\n */\nexport function ref<T = HTMLElement>(): Ref<T> {\n return { current: undefined };\n}\n\n// --- defineComponent ---\n\n/**\n * Define a component. The setup function runs once per instance.\n * It receives a context with typed props and must return a render function.\n *\n * ```ts\n * const Counter = defineComponent<{ initial: number }>((ctx) => {\n * const count = signal(ctx.props.initial);\n * return () => <div>{count()}</div>;\n * });\n * ```\n */\nexport function defineComponent<P extends Record<string, unknown> = Record<string, unknown>>(\n setup: (ctx: ComponentContext<P>) => () => AkashNode,\n): Component<P> {\n const component = (rawProps: P & { children?: AkashNode | (() => AkashNode) }): Node => {\n // Separate children from props, unwrap getter functions for reactivity\n const { children: childrenProp, ...restProps } = rawProps ?? {};\n const props = new Proxy(restProps as unknown as P, {\n get(target, key, receiver) {\n const val = Reflect.get(target, key, receiver);\n // Unwrap compiler-generated reactive getters (marked with __reactive)\n if (typeof val === 'function' && (val as any).__reactive) {\n return val();\n }\n return val;\n },\n });\n\n const childrenFn: () => AkashNode =\n typeof childrenProp === 'function'\n ? childrenProp\n : () => childrenProp ?? null;\n\n const ctx: ComponentContext<P> = {\n props,\n children: childrenFn,\n };\n\n // Set up lifecycle hooks collector\n const hooks: LifecycleHooks = { mount: [], unmount: [], error: [] };\n const prevHooks = currentHooks;\n currentHooks = hooks;\n\n // Push context scope for provide/inject\n const parentScope = getCurrentScope();\n const scope = pushScope(parentScope);\n\n let renderFn: () => AkashNode;\n let domNode: Node;\n\n try {\n renderFn = setup(ctx);\n if (typeof renderFn !== 'function') { throw akashError('AK0040'); }\n const rendered = renderFn();\n domNode = nodeToDOM(rendered);\n } catch (err) {\n popScope(scope);\n currentHooks = prevHooks;\n if (hooks.error.length > 0) {\n for (const handler of hooks.error) {\n handler(err instanceof Error ? err : new Error(String(err)));\n }\n return document.createComment('error');\n }\n throw err;\n }\n\n // Restore parent state\n popScope(scope);\n currentHooks = prevHooks;\n\n // Run mount callbacks (microtask to ensure DOM is attached)\n if (hooks.mount.length > 0) {\n queueMicrotask(() => {\n for (const mountFn of hooks.mount) {\n try {\n const cleanup = mountFn();\n if (typeof cleanup === 'function') {\n hooks.unmount.push(cleanup);\n }\n } catch (err) {\n for (const handler of hooks.error) {\n handler(err instanceof Error ? err : new Error(String(err)));\n }\n }\n }\n });\n }\n\n return domNode;\n };\n\n component._akash = true as const;\n return component as Component<P>;\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/context.ts","../src/dom.ts","../src/component.ts"],"names":["errors","DOC_BASE","formatError","code","context","def","msg","akashError","getErrorDef","getAllErrorCodes","CONTEXT_BRAND","currentScope","pushScope","parent","scope","popScope","getCurrentScope","runInScope","fn","prev","createContext","defaultValue","provide","key","value","inject","fallback","createElement","tag","attrs","el","setProperty","createText","cloneTemplate","html","template","event","bindText","node","effect","bindProperty","bindVisible","createAnchor","label","renderConditional","anchor","condition","trueBranch","falseBranch","current","dispose","branch","liveParent","fragment","nodes","renderList","items","keyFn","renderItem","currentItems","newData","newItems","oldMap","item","i","data","existing","Show","props","container","getWhen","whenValue","nodeToDOM","For","getEach","index","child","insert","domNode","__getter","currentHooks","onMount","onUnmount","onError","ref","defineComponent","setup","component","rawProps","childrenProp","restProps","ctx","target","receiver","val","hooks","prevHooks","parentScope","renderFn","rendered","err","handler","mountFn","cleanup"],"mappings":"oCAqBA,IAAMA,EAAmC,CAEvC,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,8CAAA,CACT,IAAA,CAAM,oDACR,CAAA,CACA,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,6CAAA,CACT,IAAA,CAAM,mDACR,CAAA,CACA,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,yCAAA,CACT,IAAA,CAAM,gEACR,CAAA,CAGA,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,8CAAA,CACT,IAAA,CAAM,oDACR,CAAA,CACA,MAAA,CAAQ,CACN,IAAA,CAAM,QAAA,CACN,QAAS,gDAAA,CACT,IAAA,CAAM,sDACR,CAAA,CACA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,8CAAA,CACT,KAAM,oDACR,CAAA,CAGA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,kDAAA,CACT,KAAM,uEACR,CAAA,CACA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,yCAAA,CACT,KAAM,gHACR,CAAA,CAGA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,gDAAA,CACT,KAAM,uEACR,CAAA,CACA,OAAQ,CACN,IAAA,CAAM,SACN,OAAA,CAAS,2BAAA,CACT,KAAM,gEACR,CAAA,CAGA,MAAA,CAAQ,CACN,KAAM,QAAA,CACN,OAAA,CAAS,+CACT,IAAA,CAAM,gEACR,EACA,MAAA,CAAQ,CACN,KAAM,QAAA,CACN,OAAA,CAAS,oCACT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Ac,OAAO,CACvC,CACA,MAAMA,CACR,CAGA,OAAArF,CAAAA,CAASD,CAAK,CAAA,CACdkE,CAAAA,CAAegB,CAAAA,CAGXD,CAAAA,CAAM,KAAA,CAAM,MAAA,CAAS,GACvB,cAAA,CAAe,IAAM,CACnB,IAAA,IAAWO,KAAWP,CAAAA,CAAM,KAAA,CAC1B,GAAI,CACF,IAAMQ,CAAAA,CAAUD,CAAAA,EAAQ,CACpB,OAAOC,CAAAA,EAAY,UAAA,EACrBR,CAAAA,CAAM,OAAA,CAAQ,KAAKQ,CAAO,EAE9B,CAAA,MAASH,CAAAA,CAAK,CACZ,IAAA,IAAWC,CAAAA,IAAWN,CAAAA,CAAM,KAAA,CAC1BM,EAAQD,CAAAA,YAAe,KAAA,CAAQA,CAAAA,CAAM,IAAI,KAAA,CAAM,MAAA,CAAOA,CAAG,CAAC,CAAC,EAE/D,CAEJ,CAAC,CAAA,CAGItB,CACT,CAAA,CAEA,OAAAS,CAAAA,CAAU,MAAA,CAAS,KACZA,CACT","file":"chunk-367DJVST.js","sourcesContent":["/**\n * Error message catalog.\n *\n * Every AkashJS runtime error has a unique code (AK0001, AK0002, etc.),\n * a one-line description, and a link to detailed documentation.\n *\n * Usage:\n * throw akashError('AK0010', 'provide()');\n */\n\n// --- Error registry ---\n\nexport interface ErrorDef {\n /** Error code */\n code: string;\n /** Short description */\n message: string;\n /** Extended explanation and fix suggestion */\n hint: string;\n}\n\nconst errors: Record<string, ErrorDef> = {\n // --- Context errors (AK001x) ---\n AK0010: {\n code: 'AK0010',\n message: 'provide() called outside of component setup.',\n hint: 'provide() must be called inside defineComponent().',\n },\n AK0012: {\n code: 'AK0012',\n message: 'inject() called outside of component setup.',\n hint: 'inject() must be called inside defineComponent().',\n },\n AK0013: {\n code: 'AK0013',\n message: 'No provider found for injected context.',\n hint: 'Make sure an ancestor component calls provide() with this key.',\n },\n\n // --- Lifecycle errors (AK002x) ---\n AK0020: {\n code: 'AK0020',\n message: 'onMount() called outside of component setup.',\n hint: 'onMount() must be called inside defineComponent().',\n },\n AK0021: {\n code: 'AK0021',\n message: 'onUnmount() called outside of component setup.',\n hint: 'onUnmount() must be called inside defineComponent().',\n },\n AK0022: {\n code: 'AK0022',\n message: 'onError() called outside of component setup.',\n hint: 'onError() must be called inside defineComponent().',\n },\n\n // --- Signal errors (AK003x) ---\n AK0030: {\n code: 'AK0030',\n message: 'Circular dependency detected in computed signal.',\n hint: 'A computed signal is reading itself, directly or via other computeds.',\n },\n AK0031: {\n code: 'AK0031',\n message: 'Signal set() called during computation.',\n hint: 'Do not set signals inside computed() or during effect execution. Use batch() or set signals in event handlers.',\n },\n\n // --- Component errors (AK004x) ---\n AK0040: {\n code: 'AK0040',\n message: 'Component setup must return a render function.',\n hint: 'The function passed to defineComponent() must return () => AkashNode.',\n },\n AK0041: {\n code: 'AK0041',\n message: 'Required prop is missing.',\n hint: 'Check that the parent component is passing all required props.',\n },\n\n // --- Router errors (AK005x) ---\n AK0050: {\n code: 'AK0050',\n message: 'useRoute() called outside of router context.',\n hint: 'Make sure your component is rendered inside a router provider.',\n },\n AK0051: {\n code: 'AK0051',\n message: 'No route matched the current URL.',\n hint: 'Add a catch-all route ([...rest]) to handle unmatched paths.',\n },\n AK0052: {\n code: 'AK0052',\n message: 'Route guard threw an error.',\n hint: 'Check the guard function for unhandled exceptions.',\n },\n\n // --- Form errors (AK006x) ---\n AK0060: {\n code: 'AK0060',\n message: 'Form submitted while invalid.',\n hint: 'The submit handler was not called because validation failed. Check form.errors().',\n },\n AK0061: {\n code: 'AK0061',\n message: 'Async validator timed out.',\n hint: 'The async validator did not resolve within the expected time. Check your async validation logic.',\n },\n\n // --- HTTP errors (AK007x) ---\n AK0070: {\n code: 'AK0070',\n message: 'HTTP request failed.',\n hint: 'Check the server response status and network connectivity.',\n },\n AK0071: {\n code: 'AK0071',\n message: 'createResource() fetcher threw an error.',\n hint: 'Check the fetcher function passed to createResource().',\n },\n};\n\n// --- Public API ---\n\nconst DOC_BASE = 'https://akashjs.dev/errors';\n\n/**\n * Format an AkashJS error with code, message, hint, and doc link.\n */\nexport function formatError(code: string, context?: string): string {\n const def = errors[code];\n if (!def) {\n return `[AkashJS ${code}] Unknown error code.`;\n }\n\n let msg = `[AkashJS ${code}] ${def.message}`;\n if (context) {\n msg += `\\n ${context}`;\n }\n msg += `\\n ${def.hint}`;\n msg += `\\n See: ${DOC_BASE}/${code}`;\n return msg;\n}\n\n/**\n * Create and throw an AkashJS error.\n */\nexport function akashError(code: string, context?: string): Error {\n return new Error(formatError(code, context));\n}\n\n/**\n * Get the error definition for a code.\n */\nexport function getErrorDef(code: string): ErrorDef | undefined {\n return errors[code];\n}\n\n/**\n * Get all registered error codes.\n */\nexport function getAllErrorCodes(): string[] {\n return Object.keys(errors);\n}\n","/**\n * Lightweight dependency injection via provide/inject.\n *\n * Context is scoped to the component tree — no injector hierarchy,\n * no decorators, no classes. Just createContext(), provide(), inject().\n */\n\n// --- Types ---\n\nimport { akashError } from './errors.js';\n\nconst CONTEXT_BRAND = Symbol('akash.context');\n\nexport interface InjectionKey<T> {\n readonly [CONTEXT_BRAND]: true;\n readonly _type: T; // phantom type — never used at runtime\n readonly defaultValue: T | undefined;\n readonly id: symbol;\n}\n\n// --- Context stack (managed by component system) ---\n\ninterface ContextScope {\n values: Map<symbol, unknown>;\n parent: ContextScope | null;\n}\n\nlet currentScope: ContextScope | null = null;\n\n/** @internal — called by defineComponent to push/pop context scopes */\nexport function pushScope(parent: ContextScope | null = currentScope): ContextScope {\n const scope: ContextScope = { values: new Map(), parent };\n currentScope = scope;\n return scope;\n}\n\n/** @internal */\nexport function popScope(scope: ContextScope): void {\n currentScope = scope.parent;\n}\n\n/** @internal */\nexport function getCurrentScope(): ContextScope | null {\n return currentScope;\n}\n\n/**\n * Run a function within a given scope so that provide/inject\n * work correctly for components created asynchronously\n * (e.g., lazy-loaded route components).\n */\nexport function runInScope<T>(scope: ContextScope, fn: () => T): T {\n const prev = currentScope;\n currentScope = scope;\n try {\n return fn();\n } finally {\n currentScope = prev;\n }\n}\n\n// --- Public API ---\n\n/**\n * Create a typed context key with an optional default value.\n *\n * ```ts\n * const ThemeContext = createContext<'light' | 'dark'>('light');\n * ```\n */\nexport function createContext<T>(defaultValue?: T): InjectionKey<T> {\n return {\n [CONTEXT_BRAND]: true,\n _type: undefined as T,\n defaultValue,\n id: Symbol('context'),\n };\n}\n\n/**\n * Provide a value for a context key in the current component scope.\n * All descendant components can inject() this value.\n *\n * Must be called inside defineComponent() setup.\n */\nexport function provide<T>(key: InjectionKey<T>, value: T): void {\n if (!currentScope) {\n throw akashError('AK0010');\n }\n currentScope.values.set(key.id, value);\n}\n\n/**\n * Inject a value from the nearest ancestor that provided it.\n *\n * Must be called inside defineComponent() setup.\n */\nexport function inject<T>(key: InjectionKey<T>): T;\nexport function inject<T>(key: InjectionKey<T>, fallback: T): T;\nexport function inject<T>(key: InjectionKey<T>, fallback?: T): T {\n if (!currentScope) {\n throw akashError('AK0012');\n }\n\n // Walk up the scope chain\n let scope: ContextScope | null = currentScope;\n while (scope) {\n if (scope.values.has(key.id)) {\n return scope.values.get(key.id) as T;\n }\n scope = scope.parent;\n }\n\n // Check fallback, then default\n if (fallback !== undefined) return fallback;\n if (key.defaultValue !== undefined) return key.defaultValue;\n\n throw akashError('AK0013');\n}\n","/**\n * Direct DOM rendering runtime.\n *\n * No virtual DOM. The compiler generates calls to these helpers.\n * Signal reads inside templates become fine-grained effects that\n * update only the specific DOM node that changed.\n */\n\nimport { effect } from './signals.js';\nimport { getCurrentScope, runInScope } from './context.js';\nimport type { AkashNode } from './types.js';\n\n// --- DOM creation helpers (used by compiler output) ---\n\n/** Create an element and optionally set static attributes */\nexport function createElement(\n tag: string,\n attrs?: Record<string, unknown>,\n): HTMLElement {\n const el = document.createElement(tag);\n if (attrs) {\n for (const [key, value] of Object.entries(attrs)) {\n setProperty(el, key, value);\n }\n }\n return el;\n}\n\n/** Create a text node */\nexport function createText(value: string): Text {\n return document.createTextNode(value);\n}\n\n/** Clone a template element for static structure */\nexport function cloneTemplate(html: string): DocumentFragment {\n const template = document.createElement('template');\n template.innerHTML = html;\n return template.content.cloneNode(true) as DocumentFragment;\n}\n\n// --- Property/attribute setting ---\n\nexport function setProperty(el: HTMLElement, key: string, value: unknown): void {\n if (key === 'class' || key === 'className') {\n el.className = value as string;\n } else if (key === 'style' && typeof value === 'object' && value !== null) {\n Object.assign(el.style, value);\n } else if (key === 'innerHTML') {\n el.innerHTML = value as string;\n } else if (key === 'ref') {\n // Handled separately by component system\n } else if (key.startsWith('on')) {\n const event = key.slice(2).toLowerCase();\n el.addEventListener(event, value as EventListener);\n } else if (key in el) {\n (el as Record<string, unknown>)[key] = value;\n } else if (value === false || value == null) {\n el.removeAttribute(key);\n } else {\n el.setAttribute(key, value === true ? '' : String(value));\n }\n}\n\n// --- Reactive binding (used by compiler for dynamic expressions) ---\n\n/** Bind a reactive expression to a text node's content */\nexport function bindText(node: Text, fn: () => unknown): () => void {\n return effect(\n () => {\n node.textContent = String(fn());\n },\n { render: true },\n );\n}\n\n/** Bind a reactive expression to an element's attribute/property */\nexport function bindProperty(\n el: HTMLElement,\n key: string,\n fn: () => unknown,\n): () => void {\n return effect(\n () => {\n setProperty(el, key, fn());\n },\n { render: true },\n );\n}\n\n/** Bind a reactive expression to an element's visibility (display) */\nexport function bindVisible(el: HTMLElement, fn: () => boolean): () => void {\n return effect(\n () => {\n el.style.display = fn() ? '' : 'none';\n },\n { render: true },\n );\n}\n\n// --- Conditional rendering ---\n\n/** Anchor node type for marking insertion points */\ntype Anchor = Comment;\n\nfunction createAnchor(label = ''): Anchor {\n return document.createComment(label);\n}\n\ninterface ConditionalBlock {\n nodes: Node[];\n dispose: (() => void) | null;\n}\n\n/**\n * Render a conditional block. Swaps DOM fragments based on a reactive\n * condition. Used by the compiler for :if directives and <Show>.\n */\nexport function renderConditional(\n parent: Node,\n anchor: Node,\n condition: () => boolean,\n trueBranch: () => Node,\n falseBranch?: () => Node,\n): () => void {\n let current: ConditionalBlock | null = null;\n\n // Capture scope so children created in branches inherit provide/inject context\n const scope = getCurrentScope();\n\n const dispose = effect(\n () => {\n const value = condition();\n\n // Remove old nodes\n if (current) {\n for (const node of current.nodes) {\n try { node.parentNode?.removeChild(node); } catch {}\n }\n current.dispose?.();\n current = null;\n }\n\n // Insert new nodes — use anchor.parentNode since the anchor may have\n // moved from the initial DocumentFragment into the real DOM\n const branch = value ? trueBranch : falseBranch;\n const liveParent = anchor.parentNode;\n if (branch && liveParent) {\n const fragment = scope ? runInScope(scope, branch) : branch();\n const nodes = fragment instanceof DocumentFragment\n ? Array.from(fragment.childNodes)\n : [fragment];\n for (const node of nodes) {\n liveParent.insertBefore(node, anchor);\n }\n current = { nodes, dispose: null };\n }\n },\n { render: true },\n );\n\n return () => {\n dispose();\n if (current) {\n for (const node of current.nodes) {\n try { node.parentNode?.removeChild(node); } catch {}\n }\n current.dispose?.();\n }\n };\n}\n\n// --- List rendering ---\n\ninterface ListItem<T> {\n key: unknown;\n value: T;\n nodes: Node[];\n dispose: (() => void) | null;\n}\n\n/**\n * Render a reactive list with keyed reconciliation.\n * Used by the compiler for :for directives and <For>.\n */\nexport function renderList<T>(\n parent: Node,\n anchor: Node,\n items: () => T[],\n keyFn: (item: T, index: number) => unknown,\n renderItem: (item: T, index: number) => Node,\n): () => void {\n let currentItems: ListItem<T>[] = [];\n\n // Capture scope so children created in renderItem inherit provide/inject context\n const scope = getCurrentScope();\n\n const dispose = effect(\n () => {\n const newData = items();\n const newItems: ListItem<T>[] = [];\n const oldMap = new Map<unknown, ListItem<T>>();\n\n for (const item of currentItems) {\n oldMap.set(item.key, item);\n }\n\n // Build new list, reuse existing DOM nodes when keys match\n for (let i = 0; i < newData.length; i++) {\n const data = newData[i];\n const key = keyFn(data, i);\n const existing = oldMap.get(key);\n\n if (existing) {\n oldMap.delete(key);\n existing.value = data;\n newItems.push(existing);\n } else {\n const fragment = scope ? runInScope(scope, () => renderItem(data, i)) : renderItem(data, i);\n const nodes = fragment instanceof DocumentFragment\n ? Array.from(fragment.childNodes)\n : [fragment];\n newItems.push({ key, value: data, nodes, dispose: null });\n }\n }\n\n // Remove items that are no longer in the list\n for (const item of oldMap.values()) {\n for (const node of item.nodes) {\n if (node.parentNode) node.parentNode.removeChild(node);\n }\n item.dispose?.();\n }\n\n // Reconcile DOM order — use anchor.parentNode since anchor may have\n // moved from the initial DocumentFragment into the real DOM\n const liveParent = anchor.parentNode;\n if (liveParent) {\n for (const item of newItems) {\n for (const node of item.nodes) {\n liveParent.insertBefore(node, anchor);\n }\n }\n }\n\n currentItems = newItems;\n },\n { render: true },\n );\n\n return () => {\n dispose();\n for (const item of currentItems) {\n for (const node of item.nodes) {\n if (node.parentNode) node.parentNode.removeChild(node);\n }\n item.dispose?.();\n }\n currentItems = [];\n };\n}\n\n// --- Built-in control flow components ---\n\n/** Props for the <Show> component */\nexport interface ShowProps<T> {\n when: (() => T | null | undefined | false) | T | null | undefined | false;\n fallback?: () => AkashNode;\n children: (value: T) => AkashNode;\n}\n\n/**\n * <Show> component — conditionally renders children with type narrowing.\n * The children callback receives the non-null/undefined value.\n * `when` can be a reactive getter or a static value.\n */\nexport function Show<T>(props: ShowProps<T>): Node {\n const anchor = createAnchor('show');\n const container = document.createDocumentFragment();\n container.appendChild(anchor);\n\n // Resolve when — if it's a function, always call it (supports both\n // compiler-generated __reactive getters and plain programmatic functions)\n const getWhen = typeof props.when === 'function'\n ? props.when as () => T | null | undefined | false\n : () => props.when as T | null | undefined | false;\n\n // Capture the when value once per evaluation so the condition check\n // and the children callback receive the same value (fixes nested For contexts)\n let whenValue: T | null | undefined | false;\n renderConditional(\n container,\n anchor,\n () => { whenValue = getWhen(); return !!whenValue; },\n () => nodeToDOM(props.children(whenValue as T)),\n props.fallback ? () => nodeToDOM(props.fallback!()) : undefined,\n );\n\n return container;\n}\n\n/** Props for the <For> component */\nexport interface ForProps<T> {\n each: (() => T[]) | T[];\n key: (item: T) => unknown;\n children: (item: T, index: number) => AkashNode;\n}\n\n/**\n * <For> component — renders a list with keyed reconciliation.\n * `each` can be a reactive getter or a static array.\n */\nexport function For<T>(props: ForProps<T>): Node {\n const anchor = createAnchor('for');\n const container = document.createDocumentFragment();\n container.appendChild(anchor);\n\n // Resolve each — if it's a function, always call it (supports both\n // compiler-generated __reactive getters and plain programmatic functions)\n const getEach = typeof props.each === 'function'\n ? props.each as () => T[]\n : () => props.each as T[];\n\n renderList(\n container,\n anchor,\n getEach,\n props.key,\n (item, index) => nodeToDOM(props.children(item, index)),\n );\n\n return container;\n}\n\n// --- Helpers ---\n\n/** Convert an AkashNode to a DOM Node */\nexport function nodeToDOM(node: AkashNode): Node {\n if (node == null || typeof node === 'boolean') {\n return document.createTextNode('');\n }\n if (typeof node === 'string' || typeof node === 'number') {\n return document.createTextNode(String(node));\n }\n if (node instanceof Node) {\n return node;\n }\n if (Array.isArray(node)) {\n const fragment = document.createDocumentFragment();\n for (const child of node) {\n fragment.appendChild(nodeToDOM(child));\n }\n return fragment;\n }\n return document.createTextNode(String(node));\n}\n\n/** Insert a node into a parent before an anchor */\nexport function insert(parent: Node, node: AkashNode, anchor?: Node): void {\n const domNode = nodeToDOM(node);\n if (anchor) {\n parent.insertBefore(domNode, anchor);\n } else {\n parent.appendChild(domNode);\n }\n}\n","/**\n * Component system.\n *\n * Components are functions. defineComponent() wraps a setup function\n * that runs once, establishes signals and effects, and returns a\n * render function that produces DOM nodes.\n */\n\nimport { effect } from './signals.js';\nimport { pushScope, popScope, getCurrentScope } from './context.js';\nimport { nodeToDOM } from './dom.js';\nimport { akashError } from './errors.js';\nimport type { AkashNode } from './types.js';\n\n// --- Reactive getter marker (used by compiler) ---\n\n/** Mark a function as a compiler-generated reactive getter */\nexport function __getter<T>(fn: () => T): (() => T) & { __reactive: true } {\n (fn as any).__reactive = true;\n return fn as any;\n}\n\n// --- Types ---\n\nexport interface Ref<T = HTMLElement> {\n current: T | undefined;\n}\n\nexport interface ComponentContext<P extends Record<string, unknown> = Record<string, unknown>> {\n props: Readonly<P>;\n children: () => AkashNode;\n}\n\nexport type Component<P extends Record<string, unknown> = Record<string, unknown>> = {\n (props: P & { children?: AkashNode | (() => AkashNode) }): Node;\n _akash: true;\n};\n\n// --- Lifecycle hook storage ---\n\ninterface LifecycleHooks {\n mount: Array<() => void | (() => void)>;\n unmount: Array<() => void>;\n error: Array<(error: Error) => void>;\n}\n\nlet currentHooks: LifecycleHooks | null = null;\n\n// --- Public lifecycle hooks ---\n\n/**\n * Register a callback to run after the component is mounted to the DOM.\n * If the callback returns a function, it will be called on unmount (cleanup).\n */\nexport function onMount(fn: () => void | (() => void)): void {\n if (!currentHooks) {\n throw akashError('AK0020');\n }\n currentHooks.mount.push(fn);\n}\n\n/**\n * Register a callback to run before the component is unmounted.\n */\nexport function onUnmount(fn: () => void): void {\n if (!currentHooks) {\n throw akashError('AK0021');\n }\n currentHooks.unmount.push(fn);\n}\n\n/**\n * Register an error handler for this component and its descendants.\n */\nexport function onError(fn: (error: Error) => void): void {\n if (!currentHooks) {\n throw akashError('AK0022');\n }\n currentHooks.error.push(fn);\n}\n\n/**\n * Create a ref for accessing a DOM element.\n */\nexport function ref<T = HTMLElement>(): Ref<T> {\n return { current: undefined };\n}\n\n// --- defineComponent ---\n\n/**\n * Define a component. The setup function runs once per instance.\n * It receives a context with typed props and must return a render function.\n *\n * ```ts\n * const Counter = defineComponent<{ initial: number }>((ctx) => {\n * const count = signal(ctx.props.initial);\n * return () => <div>{count()}</div>;\n * });\n * ```\n */\nexport function defineComponent<P extends Record<string, unknown> = Record<string, unknown>>(\n setup: (ctx: ComponentContext<P>) => () => AkashNode,\n): Component<P> {\n const component = (rawProps: P & { children?: AkashNode | (() => AkashNode) }): Node => {\n // Separate children from props, unwrap getter functions for reactivity\n const { children: childrenProp, ...restProps } = rawProps ?? {};\n const props = new Proxy(restProps as unknown as P, {\n get(target, key, receiver) {\n const val = Reflect.get(target, key, receiver);\n // Unwrap compiler-generated reactive getters (marked with __reactive)\n if (typeof val === 'function' && (val as any).__reactive) {\n return val();\n }\n return val;\n },\n });\n\n const childrenFn: () => AkashNode =\n typeof childrenProp === 'function'\n ? childrenProp\n : () => childrenProp ?? null;\n\n const ctx: ComponentContext<P> = {\n props,\n children: childrenFn,\n };\n\n // Set up lifecycle hooks collector\n const hooks: LifecycleHooks = { mount: [], unmount: [], error: [] };\n const prevHooks = currentHooks;\n currentHooks = hooks;\n\n // Push context scope for provide/inject\n const parentScope = getCurrentScope();\n const scope = pushScope(parentScope);\n\n let renderFn: () => AkashNode;\n let domNode: Node;\n\n try {\n renderFn = setup(ctx);\n if (typeof renderFn !== 'function') { throw akashError('AK0040'); }\n const rendered = renderFn();\n domNode = nodeToDOM(rendered);\n } catch (err) {\n popScope(scope);\n currentHooks = prevHooks;\n if (hooks.error.length > 0) {\n for (const handler of hooks.error) {\n handler(err instanceof Error ? err : new Error(String(err)));\n }\n return document.createComment('error');\n }\n throw err;\n }\n\n // Restore parent state\n popScope(scope);\n currentHooks = prevHooks;\n\n // Run mount callbacks (microtask to ensure DOM is attached)\n if (hooks.mount.length > 0) {\n queueMicrotask(() => {\n for (const mountFn of hooks.mount) {\n try {\n const cleanup = mountFn();\n if (typeof cleanup === 'function') {\n hooks.unmount.push(cleanup);\n }\n } catch (err) {\n for (const handler of hooks.error) {\n handler(err instanceof Error ? err : new Error(String(err)));\n }\n }\n }\n });\n }\n\n return domNode;\n };\n\n component._akash = true as const;\n return component as Component<P>;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {l,m,n}from'./chunk-TWA4T6PX.js';var k=[];function v(s){k.push(...s.plugins);}var g=new Map;function x(s,a){return ()=>{if(g.has(s))return g.get(s);let r=a.state(),o=A(s,r,a);return g.set(s,o),o}}function A(s,a,r){let o={},c=Object.keys(a);for(let t of c)o[t]=l(a[t]);let n$1={$id:s};for(let t of c)n$1[t]=o[t];if(r.getters)for(let[t,e]of Object.entries(r.getters))n$1[t]=m(()=>e.call(n$1,o));let l$1=[...k,...r.plugins??[]];if(r.actions)for(let[t,e]of Object.entries(r.actions))n$1[t]=(...i)=>{for(let f of l$1)f.onAction?.(n$1,t,i);return e.apply(n$1,i)};n$1.$reset=()=>{let t=r.state();for(let e of c)o[e].set(t[e]);},n$1.$patch=t=>{for(let[e,i]of Object.entries(t))e in o&&o[e].set(i);},n$1.$snapshot=()=>{let t={};for(let e of c)t[e]=o[e]();return t};let u=new Set,S=null;n$1.$subscribe=t=>{if(u.add(t),!S){let e=true;S=n(()=>{for(let f of c)o[f]();if(e){e=false;return}let i=n$1.$snapshot();for(let f of u)f(i);});}return ()=>{u.delete(t),u.size===0&&S&&(S(),S=null);}};for(let t of l$1)t.init?.(n$1);return n$1}function b(){g.clear();}function R(){return g}export{v as a,x as b,b as c,R as d};//# sourceMappingURL=chunk-4PK4YNND.js.map
2
+ //# sourceMappingURL=chunk-4PK4YNND.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/store.ts"],"names":["globalPlugins","configureStores","options","storeInstances","defineStore","id","definition","initialState","store","createStoreInstance","stateSignals","stateKeys","key","signal","getterFn","computed","plugins","actionFn","args","plugin","fresh","partial","value","snapshot","subscribers","subscribeEffect","callback","isInitial","effect","cb","clearStores","__getStoreInstances"],"mappings":"wCAoFA,IAAMA,EAA+B,EAAC,CAG/B,SAASC,CAAAA,CAAgBC,EAA2C,CACzEF,CAAAA,CAAc,IAAA,CAAK,GAAGE,EAAQ,OAAO,EACvC,CAIA,IAAMC,EAAiB,IAAI,GAAA,CAQpB,SAASC,CAAAA,CAKdC,EACAC,CAAAA,CACsB,CACtB,OAAO,IAAM,CAEX,GAAIH,CAAAA,CAAe,GAAA,CAAIE,CAAE,EACvB,OAAOF,CAAAA,CAAe,GAAA,CAAIE,CAAE,EAG9B,IAAME,CAAAA,CAAeD,CAAAA,CAAW,KAAA,GAC1BE,CAAAA,CAAQC,CAAAA,CAAoBJ,CAAAA,CAAIE,CAAAA,CAAcD,CAAU,CAAA,CAC9D,OAAAH,CAAAA,CAAe,GAAA,CAAI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CAAAA,IAAUH,CAAAA,CAASG,CAAAA,CAAO,OAAOX,CAAK,CAAA,CAEjD,OAAOA,CACT,CAKO,SAASsB,CAAAA,EAAoB,CAClC3B,CAAAA,CAAe,QACjB,CAGO,SAAS4B,CAAAA,EAAyD,CACvE,OAAO5B,CACT","file":"chunk-FAPX3I6C.js","sourcesContent":["/**\n * Global state management via defineStore().\n *\n * Stores are singleton signal containers that persist across\n * components. They provide shared state, computed getters,\n * and actions — no external library needed.\n *\n * ```ts\n * const useCounterStore = defineStore('counter', {\n * state: () => ({ count: 0, name: 'Counter' }),\n * getters: {\n * doubled: (state) => state.count() * 2,\n * },\n * actions: {\n * increment() { this.count.update(c => c + 1); },\n * reset() { this.count.set(0); },\n * },\n * });\n *\n * // In any component:\n * const store = useCounterStore();\n * store.count(); // 0\n * store.doubled(); // 0\n * store.increment();\n * store.count(); // 1\n * ```\n */\n\nimport { signal, computed, effect } from './signals.js';\nimport type { Signal, ReadonlySignal } from './signals.js';\n\n// --- Types ---\n\ntype StateFactory<S> = () => S;\n\ntype Getters<S, G> = {\n [K in keyof G]: (state: SignalifiedState<S>) => G[K];\n};\n\ntype Actions<A> = {\n [K in keyof A]: A[K] extends (...args: infer P) => infer R\n ? (...args: P) => R\n : never;\n};\n\n/** Maps plain state values to signals */\ntype SignalifiedState<S> = {\n [K in keyof S]: Signal<S[K]>;\n};\n\n/** The store instance returned to consumers */\nexport type Store<S, G, A> = SignalifiedState<S> & {\n [K in keyof G]: ReadonlySignal<G[K]>;\n} & {\n [K in keyof A]: A[K] extends (...args: infer P) => infer R\n ? (...args: P) => R\n : never;\n} & {\n /** Reset all state to initial values */\n $reset(): void;\n /** Merge partial state into the store */\n $patch(partial: Partial<S>): void;\n /** Subscribe to all state changes */\n $subscribe(callback: (state: S) => void): () => void;\n /** Get a plain snapshot of current state */\n $snapshot(): S;\n /** Store ID */\n $id: string;\n};\n\nexport interface StoreDefinition<S, G, A> {\n state: StateFactory<S>;\n getters?: Getters<S, G>;\n actions?: A;\n plugins?: StorePlugin[];\n}\n\n// --- Plugin system ---\n\nexport interface StorePlugin {\n init?(store: Store<any, any, any>): void;\n onAction?(store: Store<any, any, any>, actionName: string, args: unknown[]): void;\n}\n\nconst globalPlugins: StorePlugin[] = [];\n\n/** Register global plugins that apply to all stores */\nexport function configureStores(options: { plugins: StorePlugin[] }): void {\n globalPlugins.push(...options.plugins);\n}\n\n// --- Store registry (singleton) ---\n\nconst storeInstances = new Map<string, Store<any, any, any>>();\n\n// --- defineStore ---\n\n/**\n * Define a global store. Returns a composable function that\n * always returns the same store instance (singleton).\n */\nexport function defineStore<\n S extends Record<string, unknown>,\n G extends Record<string, unknown> = {},\n A extends Record<string, (...args: any[]) => any> = {},\n>(\n id: string,\n definition: StoreDefinition<S, G, A>,\n): () => Store<S, G, A> {\n return () => {\n // Return existing instance if already created\n if (storeInstances.has(id)) {\n return storeInstances.get(id) as Store<S, G, A>;\n }\n\n const initialState = definition.state();\n const store = createStoreInstance(id, initialState, definition);\n storeInstances.set(id, store);\n return store;\n };\n}\n\nfunction createStoreInstance<\n S extends Record<string, unknown>,\n G extends Record<string, unknown>,\n A extends Record<string, (...args: any[]) => any>,\n>(\n id: string,\n initialState: S,\n definition: StoreDefinition<S, G, A>,\n): Store<S, G, A> {\n // Create signals for each state property\n const stateSignals: Record<string, Signal<unknown>> = {};\n const stateKeys = Object.keys(initialState);\n\n for (const key of stateKeys) {\n stateSignals[key] = signal(initialState[key]);\n }\n\n // Build the store object first so getters can reference other getters via `this`\n const store: any = { $id: id };\n\n // Add state signals\n for (const key of stateKeys) {\n store[key] = stateSignals[key];\n }\n\n // Create computed getters — bound to store so `this.otherGetter()` works\n if (definition.getters) {\n for (const [key, getterFn] of Object.entries(definition.getters)) {\n store[key] = computed(() =>\n (getterFn as Function).call(store, stateSignals),\n );\n }\n }\n\n // Collect all plugins (global + per-store)\n const plugins = [...globalPlugins, ...(definition.plugins ?? [])];\n\n // Bind actions with `this` pointing to the full store (state + getters + actions)\n if (definition.actions) {\n for (const [key, actionFn] of Object.entries(definition.actions)) {\n store[key] = (...args: unknown[]) => {\n for (const plugin of plugins) plugin.onAction?.(store, key, args);\n return (actionFn as Function).apply(store, args);\n };\n }\n }\n\n // $reset\n store.$reset = () => {\n const fresh = definition.state();\n for (const key of stateKeys) {\n stateSignals[key].set(fresh[key as keyof S]);\n }\n };\n\n // $patch — merge partial state\n store.$patch = (partial: Partial<S>) => {\n for (const [key, value] of Object.entries(partial)) {\n if (key in stateSignals) {\n stateSignals[key].set(value);\n }\n }\n };\n\n // $snapshot\n store.$snapshot = (): S => {\n const snapshot: Record<string, unknown> = {};\n for (const key of stateKeys) {\n snapshot[key] = stateSignals[key]();\n }\n return snapshot as S;\n };\n\n // $subscribe — watch all state signals and notify on change\n const subscribers = new Set<(state: S) => void>();\n let subscribeEffect: (() => void) | null = null;\n store.$subscribe = (callback: (state: S) => void): (() => void) => {\n subscribers.add(callback);\n // Start watching if this is the first subscriber\n if (!subscribeEffect) {\n let isInitial = true;\n subscribeEffect = effect(() => {\n // Read all state signals to track them\n for (const key of stateKeys) {\n stateSignals[key]();\n }\n // Skip initial run — only notify on actual changes\n if (isInitial) {\n isInitial = false;\n return;\n }\n const snapshot = store.$snapshot();\n for (const cb of subscribers) {\n cb(snapshot);\n }\n });\n }\n return () => {\n subscribers.delete(callback);\n // Dispose effect when no subscribers remain\n if (subscribers.size === 0 && subscribeEffect) {\n subscribeEffect();\n subscribeEffect = null;\n }\n };\n };\n\n // Initialize plugins\n for (const plugin of plugins) plugin.init?.(store);\n\n return store as Store<S, G, A>;\n}\n\n/**\n * Clear all store instances (useful for testing).\n */\nexport function clearStores(): void {\n storeInstances.clear();\n}\n\n/** @internal — exposes store registry for devtools */\nexport function __getStoreInstances(): Map<string, Store<any, any, any>> {\n return storeInstances;\n}\n"]}
1
+ {"version":3,"sources":["../src/store.ts"],"names":["globalPlugins","configureStores","options","storeInstances","defineStore","id","definition","initialState","store","createStoreInstance","stateSignals","stateKeys","key","signal","getterFn","computed","plugins","actionFn","args","plugin","fresh","partial","value","snapshot","subscribers","subscribeEffect","callback","isInitial","effect","cb","clearStores","__getStoreInstances"],"mappings":"wCAoFA,IAAMA,EAA+B,EAAC,CAG/B,SAASC,CAAAA,CAAgBC,EAA2C,CACzEF,CAAAA,CAAc,IAAA,CAAK,GAAGE,EAAQ,OAAO,EACvC,CAIA,IAAMC,EAAiB,IAAI,GAAA,CAQpB,SAASC,CAAAA,CAKdC,EACAC,CAAAA,CACsB,CACtB,OAAO,IAAM,CAEX,GAAIH,CAAAA,CAAe,GAAA,CAAIE,CAAE,EACvB,OAAOF,CAAAA,CAAe,GAAA,CAAIE,CAAE,EAG9B,IAAME,CAAAA,CAAeD,CAAAA,CAAW,KAAA,GAC1BE,CAAAA,CAAQC,CAAAA,CAAoBJ,CAAAA,CAAIE,CAAAA,CAAcD,CAAU,CAAA,CAC9D,OAAAH,CAAAA,CAAe,GAAA,CAAIE,EAAIG,CAAK,CAAA,CACrBA,CACT,CACF,CAEA,SAASC,CAAAA,CAKPJ,CAAAA,CACAE,CAAAA,CACAD,EACgB,CAEhB,IAAMI,CAAAA,CAAgD,GAChDC,CAAAA,CAAY,MAAA,CAAO,IAAA,CAAKJ,CAAY,EAE1C,IAAA,IAAWK,CAAAA,IAAOD,EAChBD,CAAAA,CAAaE,CAAG,EAAIC,CAAAA,CAAON,CAAAA,CAAaK,CAAG,CAAC,EAI9C,IAAMJ,GAAAA,CAAa,CAAE,GAAA,CAAKH,CAAG,CAAA,CAG7B,IAAA,IAAWO,CAAAA,IAAOD,CAAAA,CAChBH,IAAMI,CAAG,CAAA,CAAIF,CAAAA,CAAaE,CAAG,EAI/B,GAAIN,CAAAA,CAAW,OAAA,CACb,IAAA,GAAW,CAACM,CAAAA,CAAKE,CAAQ,CAAA,GAAK,MAAA,CAAO,QAAQR,CAAAA,CAAW,OAAO,CAAA,CAC7DE,GAAAA,CAAMI,CAAG,CAAA,CAAIG,CAAAA,CAAS,IACnBD,CAAA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AAAA,CAAY,GAAA,CAAIE,CAAQ,CAAA,CAEpB,CAACD,CAAAA,CAAiB,CACpB,IAAIE,CAAAA,CAAY,IAAA,CAChBF,CAAAA,CAAkBG,CAAAA,CAAO,IAAM,CAE7B,IAAA,IAAWhB,CAAAA,IAAOD,CAAAA,CAChBD,EAAaE,CAAG,CAAA,EAAE,CAGpB,GAAIe,EAAW,CACbA,CAAAA,CAAY,KAAA,CACZ,MACF,CACA,IAAMJ,CAAAA,CAAWf,GAAAA,CAAM,SAAA,GACvB,IAAA,IAAWqB,CAAAA,IAAML,EACfK,CAAAA,CAAGN,CAAQ,EAEf,CAAC,EACH,CACA,OAAO,IAAM,CACXC,CAAAA,CAAY,MAAA,CAAOE,CAAQ,EAEvBF,CAAAA,CAAY,IAAA,GAAS,CAAA,EAAKC,CAAAA,GAC5BA,GAAgB,CAChBA,CAAAA,CAAkB,IAAA,EAEtB,CACF,EAGA,IAAA,IAAWN,CAAAA,IAAUH,GAAAA,CAASG,CAAAA,CAAO,OAAOX,GAAK,CAAA,CAEjD,OAAOA,GACT,CAKO,SAASsB,CAAAA,EAAoB,CAClC3B,CAAAA,CAAe,QACjB,CAGO,SAAS4B,CAAAA,EAAyD,CACvE,OAAO5B,CACT","file":"chunk-4PK4YNND.js","sourcesContent":["/**\n * Global state management via defineStore().\n *\n * Stores are singleton signal containers that persist across\n * components. They provide shared state, computed getters,\n * and actions — no external library needed.\n *\n * ```ts\n * const useCounterStore = defineStore('counter', {\n * state: () => ({ count: 0, name: 'Counter' }),\n * getters: {\n * doubled: (state) => state.count() * 2,\n * },\n * actions: {\n * increment() { this.count.update(c => c + 1); },\n * reset() { this.count.set(0); },\n * },\n * });\n *\n * // In any component:\n * const store = useCounterStore();\n * store.count(); // 0\n * store.doubled(); // 0\n * store.increment();\n * store.count(); // 1\n * ```\n */\n\nimport { signal, computed, effect } from './signals.js';\nimport type { Signal, ReadonlySignal } from './signals.js';\n\n// --- Types ---\n\ntype StateFactory<S> = () => S;\n\ntype Getters<S, G> = {\n [K in keyof G]: (state: SignalifiedState<S>) => G[K];\n};\n\ntype Actions<A> = {\n [K in keyof A]: A[K] extends (...args: infer P) => infer R\n ? (...args: P) => R\n : never;\n};\n\n/** Maps plain state values to signals */\ntype SignalifiedState<S> = {\n [K in keyof S]: Signal<S[K]>;\n};\n\n/** The store instance returned to consumers */\nexport type Store<S, G, A> = SignalifiedState<S> & {\n [K in keyof G]: ReadonlySignal<G[K]>;\n} & {\n [K in keyof A]: A[K] extends (...args: infer P) => infer R\n ? (...args: P) => R\n : never;\n} & {\n /** Reset all state to initial values */\n $reset(): void;\n /** Merge partial state into the store */\n $patch(partial: Partial<S>): void;\n /** Subscribe to all state changes */\n $subscribe(callback: (state: S) => void): () => void;\n /** Get a plain snapshot of current state */\n $snapshot(): S;\n /** Store ID */\n $id: string;\n};\n\nexport interface StoreDefinition<S, G, A> {\n state: StateFactory<S>;\n getters?: Getters<S, G>;\n actions?: A;\n plugins?: StorePlugin[];\n}\n\n// --- Plugin system ---\n\nexport interface StorePlugin {\n init?(store: Store<any, any, any>): void;\n onAction?(store: Store<any, any, any>, actionName: string, args: unknown[]): void;\n}\n\nconst globalPlugins: StorePlugin[] = [];\n\n/** Register global plugins that apply to all stores */\nexport function configureStores(options: { plugins: StorePlugin[] }): void {\n globalPlugins.push(...options.plugins);\n}\n\n// --- Store registry (singleton) ---\n\nconst storeInstances = new Map<string, Store<any, any, any>>();\n\n// --- defineStore ---\n\n/**\n * Define a global store. Returns a composable function that\n * always returns the same store instance (singleton).\n */\nexport function defineStore<\n S extends Record<string, unknown>,\n G extends Record<string, unknown> = {},\n A extends Record<string, (...args: any[]) => any> = {},\n>(\n id: string,\n definition: StoreDefinition<S, G, A>,\n): () => Store<S, G, A> {\n return () => {\n // Return existing instance if already created\n if (storeInstances.has(id)) {\n return storeInstances.get(id) as Store<S, G, A>;\n }\n\n const initialState = definition.state();\n const store = createStoreInstance(id, initialState, definition);\n storeInstances.set(id, store);\n return store;\n };\n}\n\nfunction createStoreInstance<\n S extends Record<string, unknown>,\n G extends Record<string, unknown>,\n A extends Record<string, (...args: any[]) => any>,\n>(\n id: string,\n initialState: S,\n definition: StoreDefinition<S, G, A>,\n): Store<S, G, A> {\n // Create signals for each state property\n const stateSignals: Record<string, Signal<unknown>> = {};\n const stateKeys = Object.keys(initialState);\n\n for (const key of stateKeys) {\n stateSignals[key] = signal(initialState[key]);\n }\n\n // Build the store object first so getters can reference other getters via `this`\n const store: any = { $id: id };\n\n // Add state signals\n for (const key of stateKeys) {\n store[key] = stateSignals[key];\n }\n\n // Create computed getters — bound to store so `this.otherGetter()` works\n if (definition.getters) {\n for (const [key, getterFn] of Object.entries(definition.getters)) {\n store[key] = computed(() =>\n (getterFn as Function).call(store, stateSignals),\n );\n }\n }\n\n // Collect all plugins (global + per-store)\n const plugins = [...globalPlugins, ...(definition.plugins ?? [])];\n\n // Bind actions with `this` pointing to the full store (state + getters + actions)\n if (definition.actions) {\n for (const [key, actionFn] of Object.entries(definition.actions)) {\n store[key] = (...args: unknown[]) => {\n for (const plugin of plugins) plugin.onAction?.(store, key, args);\n return (actionFn as Function).apply(store, args);\n };\n }\n }\n\n // $reset\n store.$reset = () => {\n const fresh = definition.state();\n for (const key of stateKeys) {\n stateSignals[key].set(fresh[key as keyof S]);\n }\n };\n\n // $patch — merge partial state\n store.$patch = (partial: Partial<S>) => {\n for (const [key, value] of Object.entries(partial)) {\n if (key in stateSignals) {\n stateSignals[key].set(value);\n }\n }\n };\n\n // $snapshot\n store.$snapshot = (): S => {\n const snapshot: Record<string, unknown> = {};\n for (const key of stateKeys) {\n snapshot[key] = stateSignals[key]();\n }\n return snapshot as S;\n };\n\n // $subscribe — watch all state signals and notify on change\n const subscribers = new Set<(state: S) => void>();\n let subscribeEffect: (() => void) | null = null;\n store.$subscribe = (callback: (state: S) => void): (() => void) => {\n subscribers.add(callback);\n // Start watching if this is the first subscriber\n if (!subscribeEffect) {\n let isInitial = true;\n subscribeEffect = effect(() => {\n // Read all state signals to track them\n for (const key of stateKeys) {\n stateSignals[key]();\n }\n // Skip initial run — only notify on actual changes\n if (isInitial) {\n isInitial = false;\n return;\n }\n const snapshot = store.$snapshot();\n for (const cb of subscribers) {\n cb(snapshot);\n }\n });\n }\n return () => {\n subscribers.delete(callback);\n // Dispose effect when no subscribers remain\n if (subscribers.size === 0 && subscribeEffect) {\n subscribeEffect();\n subscribeEffect = null;\n }\n };\n };\n\n // Initialize plugins\n for (const plugin of plugins) plugin.init?.(store);\n\n return store as Store<S, G, A>;\n}\n\n/**\n * Clear all store instances (useful for testing).\n */\nexport function clearStores(): void {\n storeInstances.clear();\n}\n\n/** @internal — exposes store registry for devtools */\nexport function __getStoreInstances(): Map<string, Store<any, any, any>> {\n return storeInstances;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {l,m}from'./chunk-TWA4T6PX.js';async function j(a,t=1){return typeof indexedDB>"u"?Promise.reject(new Error("IndexedDB not available")):new Promise((c,r)=>{try{let n=indexedDB.open(a,t);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains("items")||i.createObjectStore("items"),i.objectStoreNames.contains("pending")||i.createObjectStore("pending",{autoIncrement:!0});},n.onsuccess=()=>c(n.result),n.onerror=()=>r(n.error??new Error("IndexedDB open failed"));}catch(n){r(n);}})}async function x(a,t){return new Promise((c,r)=>{let i=a.transaction(t,"readonly").objectStore(t).getAll();i.onsuccess=()=>c(i.result),i.onerror=()=>r(i.error);})}async function D(a,t,c,r){return new Promise((n,i)=>{let l=a.transaction(t,"readwrite");l.objectStore(t).put(r,c),l.oncomplete=()=>n(),l.onerror=()=>i(l.error);})}async function B(a,t,c){return new Promise((r,n)=>{let i=a.transaction(t,"readwrite");i.objectStore(t).delete(c),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);})}async function p(a,t){return new Promise((c,r)=>{let n=a.transaction(t,"readwrite");n.objectStore(t).clear(),n.oncomplete=()=>c(),n.onerror=()=>r(n.error);})}function A(a,t={}){let c=t.keyField??"id",r=l([]),n=l([]),i=l(false),l$1=l(typeof navigator<"u"?navigator.onLine:true),b=m(()=>n().length),o=null,m$1=null,T=false;typeof window<"u"&&(window.addEventListener("online",()=>{l$1.set(true),v();}),window.addEventListener("offline",()=>l$1.set(false)));async function O(){if(!(typeof indexedDB>"u"))try{o=await j(`akash-offline-${a}`,t.version??1);let e=await x(o,"items");r.set(e);let s=await x(o,"pending");n.set(s);}catch(e){console.error("[AkashJS] Offline store init failed:",e);}}let k=O();if(t.sync){let e=t.sync.interval??3e4;m$1=setInterval(()=>{l$1()&&b()>0&&!i()&&v();},e);}function g(e){return String(e[c])}function w(e){let s=g(e);r.update(d=>{let f=d.findIndex(u=>g(u)===s);if(f!==-1){let u=[...d];return u[f]=e,u}return [...d,e]}),S({type:"put",key:s,value:e,timestamp:Date.now()}),o&&D(o,"items",s,e);}function I(e){r.update(s=>s.filter(d=>g(d)!==e)),S({type:"delete",key:e,timestamp:Date.now()}),o&&B(o,"items",e);}function S(e){n.update(s=>[...s,e]),o&&o.transaction("pending","readwrite").objectStore("pending").add(e);}async function v(){if(await k,!t.sync||i()||T)return;let e=n();if(e.length===0)return;i.set(true);let s=t.sync.fetch??globalThis.fetch.bind(globalThis);try{if((await s(t.sync.url,{method:"POST",headers:{"Content-Type":"application/json",...t.sync.headers},body:JSON.stringify({ops:e})})).ok){n.set([]),o&&await p(o,"pending");let f=await s(t.sync.url,{headers:t.sync.headers});if(f.ok){let u=await f.json();if(r.set(u),o){await p(o,"items");for(let P of u)await D(o,"items",g(P),P);}}}}catch(d){console.warn("[AkashJS] Offline sync failed:",d);}finally{i.set(false);}}return {items:()=>r(),get(e){return r().find(s=>g(s)===e)},put:w,add:w,update(e,s){let d=r().find(f=>g(f)===e);d&&w({...d,...s});},remove:I,clear(){r.set([]),n.set([]),o&&(p(o,"items"),p(o,"pending"));},pending:b,syncing:()=>i(),online:()=>l$1(),sync:v,dispose(){T=true,m$1&&clearInterval(m$1),o?.close();}}}export{A as a};//# sourceMappingURL=chunk-5NJYYK3Q.js.map
2
+ //# sourceMappingURL=chunk-5NJYYK3Q.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/offline.ts"],"names":["openDB","name","version","resolve","reject","request","db","err","idbGetAll","store","req","idbPut","key","value","tx","idbDelete","idbClear","createOfflineStore","options","keyField","items","signal","pendingOps","syncing","online","pending","computed","syncTimer","disposed","syncNow","init","stored","ops","initPromise","interval","getKey","item","put","list","idx","i","next","queueOp","remove","op","fetchFn","serverResponse","serverItems","partial","existing"],"mappings":"sCAuFA,eAAeA,CAAAA,CAAOC,EAAcC,CAAAA,CAAU,CAAA,CAAyB,CACrE,OAAI,OAAO,UAAc,GAAA,CAChB,OAAA,CAAQ,OAAO,IAAI,KAAA,CAAM,yBAAyB,CAAC,CAAA,CAErD,IAAI,OAAA,CAAQ,CAACC,CAAAA,CAASC,CAAAA,GAAW,CACtC,GAAI,CACF,IAAMC,CAAAA,CAAU,UAAU,IAAA,CAAKJ,CAAAA,CAAMC,CAAO,CAAA,CAC5CG,CAAAA,CAAQ,gBAAkB,IAAM,CAC9B,IAAMC,CAAAA,CAAKD,CAAAA,CAAQ,OACdC,CAAAA,CAAG,gBAAA,CAAiB,SAAS,OAAO,CAAA,EACvCA,CAAAA,CAAG,iBAAA,CAAkB,OAAO,CAAA,CAEzBA,EAAG,gBAAA,CAAiB,QAAA,CAAS,SAAS,CAAA,EACzCA,CAAAA,CAAG,kBAAkB,SAAA,CAAW,CAAE,cAAe,CAAA,CAAK,CAAC,EAE3D,CAAA,CACAD,CAAAA,CAAQ,UAAY,IAAMF,CAAAA,CAAQE,EAAQ,MAAM,CAAA,CAChDA,CAAAA,CAAQ,OAAA,CAAU,IAAMD,CAAAA,CAAOC,EAAQ,KAAA,EAAS,IAAI,MAAM,uBAAuB,CAAC,EACpF,CAAA,MAASE,CAAAA,CAAK,CACZH,CAAAA,CAAOG,CAAG,EACZ,CACF,CAAC,CACH,CAEA,eAAeC,EAAaF,CAAAA,CAAiBG,CAAAA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,CACA,OAAQ,CACNvB,CAAAA,CAAM,IAAI,EAAE,EACZE,CAAAA,CAAW,GAAA,CAAI,EAAE,CAAA,CACbhB,IACFU,CAAAA,CAASV,CAAAA,CAAI,OAAO,CAAA,CACpBU,CAAAA,CAASV,CAAAA,CAAI,SAAS,CAAA,EAE1B,CAAA,CACA,QAAAmB,CAAAA,CACA,OAAA,CAAS,IAAMF,CAAAA,EAAQ,CACvB,OAAQ,IAAMC,CAAAA,EAAO,CACrB,IAAA,CAAMK,CAAAA,CACN,OAAA,EAAU,CACRD,CAAAA,CAAW,IAAA,CACPD,GAAW,aAAA,CAAcA,CAAS,EACtCrB,CAAAA,EAAI,KAAA,GACN,CACF,CACF","file":"chunk-UKDME6Q2.js","sourcesContent":["/**\n * Offline-first store with IndexedDB persistence and background sync.\n *\n * Data persists across page reloads. Changes made offline queue up\n * and sync automatically when connection returns. Conflict resolution\n * via configurable strategies (last-write-wins, merge, custom).\n *\n * ```ts\n * const todos = createOfflineStore('todos', {\n * sync: { url: '/api/todos', strategy: 'last-write-wins' },\n * });\n *\n * todos.add({ id: '1', text: 'Buy milk', done: false });\n * todos.items(); // reactive list\n * todos.syncing(); // boolean\n * todos.pending(); // number of unsynced changes\n * ```\n */\n\nimport { signal, computed } from './signals.js';\nimport type { Signal, ReadonlySignal } from './signals.js';\n\n// =========================================================================\n// Types\n// =========================================================================\n\nexport type ConflictStrategy = 'last-write-wins' | 'client-wins' | 'server-wins' | 'manual';\n\nexport interface OfflineStoreOptions<T> {\n /** Sync configuration */\n sync?: {\n /** Server URL for sync */\n url: string;\n /** Conflict resolution strategy (default: 'last-write-wins') */\n strategy?: ConflictStrategy;\n /** Sync interval in ms (default: 30000) */\n interval?: number;\n /** Custom fetch */\n fetch?: typeof globalThis.fetch;\n /** Auth headers */\n headers?: Record<string, string>;\n };\n /** Key field for items (default: 'id') */\n keyField?: string;\n /** Version for schema migrations */\n version?: number;\n}\n\nexport interface OfflineStore<T extends Record<string, unknown>> {\n /** All items (reactive) */\n items: ReadonlySignal<T[]>;\n /** Get a single item by key */\n get(key: string): T | undefined;\n /** Add or update an item */\n put(item: T): void;\n /** Add a new item */\n add(item: T): void;\n /** Update an existing item */\n update(key: string, partial: Partial<T>): void;\n /** Remove an item by key */\n remove(key: string): void;\n /** Clear all items */\n clear(): void;\n /** Number of unsynced changes */\n pending: ReadonlySignal<number>;\n /** Whether sync is in progress */\n syncing: ReadonlySignal<boolean>;\n /** Whether online */\n online: ReadonlySignal<boolean>;\n /** Force a sync now */\n sync(): Promise<void>;\n /** Dispose the store (stop sync, close DB) */\n dispose(): void;\n}\n\n/** An operation in the change queue */\ninterface PendingOp<T> {\n type: 'put' | 'delete';\n key: string;\n value?: T;\n timestamp: number;\n}\n\n// =========================================================================\n// IndexedDB wrapper\n// =========================================================================\n\nasync function openDB(name: string, version = 1): Promise<IDBDatabase> {\n if (typeof indexedDB === 'undefined') {\n return Promise.reject(new Error('IndexedDB not available'));\n }\n return new Promise((resolve, reject) => {\n try {\n const request = indexedDB.open(name, version);\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains('items')) {\n db.createObjectStore('items');\n }\n if (!db.objectStoreNames.contains('pending')) {\n db.createObjectStore('pending', { autoIncrement: true });\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error ?? new Error('IndexedDB open failed'));\n } catch (err) {\n reject(err);\n }\n });\n}\n\nasync function idbGetAll<T>(db: IDBDatabase, store: string): Promise<T[]> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(store, 'readonly');\n const req = tx.objectStore(store).getAll();\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nasync function idbPut(db: IDBDatabase, store: string, key: string, value: unknown): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(store, 'readwrite');\n tx.objectStore(store).put(value, key);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n}\n\nasync function idbDelete(db: IDBDatabase, store: string, key: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(store, 'readwrite');\n tx.objectStore(store).delete(key);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n}\n\nasync function idbClear(db: IDBDatabase, store: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(store, 'readwrite');\n tx.objectStore(store).clear();\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n}\n\n// =========================================================================\n// createOfflineStore\n// =========================================================================\n\n/**\n * Create an offline-first store backed by IndexedDB.\n */\nexport function createOfflineStore<T extends Record<string, unknown>>(\n name: string,\n options: OfflineStoreOptions<T> = {},\n): OfflineStore<T> {\n const keyField = options.keyField ?? 'id';\n const items = signal<T[]>([]);\n const pendingOps = signal<PendingOp<T>[]>([]);\n const syncing = signal(false);\n const online = signal(typeof navigator !== 'undefined' ? navigator.onLine : true);\n const pending = computed(() => pendingOps().length);\n\n let db: IDBDatabase | null = null;\n let syncTimer: ReturnType<typeof setInterval> | null = null;\n let disposed = false;\n\n // Online/offline tracking\n if (typeof window !== 'undefined') {\n window.addEventListener('online', () => {\n online.set(true);\n syncNow();\n });\n window.addEventListener('offline', () => online.set(false));\n }\n\n // Initialize — load from IndexedDB\n async function init(): Promise<void> {\n if (typeof indexedDB === 'undefined') return;\n try {\n db = await openDB(`akash-offline-${name}`, options.version ?? 1);\n const stored = await idbGetAll<T>(db, 'items');\n items.set(stored);\n const ops = await idbGetAll<PendingOp<T>>(db, 'pending');\n pendingOps.set(ops);\n } catch (err) { console.error('[AkashJS] Offline store init failed:', err); }\n }\n\n const initPromise = init();\n\n // Start periodic sync\n if (options.sync) {\n const interval = options.sync.interval ?? 30000;\n syncTimer = setInterval(() => {\n if (online() && pending() > 0 && !syncing()) {\n syncNow();\n }\n }, interval);\n }\n\n function getKey(item: T): string {\n return String((item as any)[keyField]);\n }\n\n function put(item: T): void {\n const key = getKey(item);\n items.update((list) => {\n const idx = list.findIndex((i) => getKey(i) === key);\n if (idx !== -1) {\n const next = [...list];\n next[idx] = item;\n return next;\n }\n return [...list, item];\n });\n\n queueOp({ type: 'put', key, value: item, timestamp: Date.now() });\n if (db) idbPut(db, 'items', key, item);\n }\n\n function remove(key: string): void {\n items.update((list) => list.filter((i) => getKey(i) !== key));\n queueOp({ type: 'delete', key, timestamp: Date.now() });\n if (db) idbDelete(db, 'items', key);\n }\n\n function queueOp(op: PendingOp<T>): void {\n pendingOps.update((ops) => [...ops, op]);\n if (db) {\n const tx = db.transaction('pending', 'readwrite');\n tx.objectStore('pending').add(op);\n }\n }\n\n async function syncNow(): Promise<void> {\n await initPromise;\n if (!options.sync || syncing() || disposed) return;\n const ops = pendingOps();\n if (ops.length === 0) return;\n\n syncing.set(true);\n const fetchFn = options.sync.fetch ?? globalThis.fetch.bind(globalThis);\n\n try {\n const response = await fetchFn(options.sync.url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...options.sync.headers,\n },\n body: JSON.stringify({ ops }),\n });\n\n if (response.ok) {\n pendingOps.set([]);\n if (db) await idbClear(db, 'pending');\n\n // Fetch latest server state\n const serverResponse = await fetchFn(options.sync.url, {\n headers: options.sync.headers,\n });\n if (serverResponse.ok) {\n const serverItems = await serverResponse.json() as T[];\n items.set(serverItems);\n // Update IndexedDB\n if (db) {\n await idbClear(db, 'items');\n for (const item of serverItems) {\n await idbPut(db, 'items', getKey(item), item);\n }\n }\n }\n }\n } catch (err) { console.warn('[AkashJS] Offline sync failed:', err); }\n finally {\n syncing.set(false);\n }\n }\n\n return {\n items: () => items(),\n get(key: string) { return items().find((i) => getKey(i) === key); },\n put,\n add: put,\n update(key: string, partial: Partial<T>) {\n const existing = items().find((i) => getKey(i) === key);\n if (existing) put({ ...existing, ...partial });\n },\n remove,\n clear() {\n items.set([]);\n pendingOps.set([]);\n if (db) {\n idbClear(db, 'items');\n idbClear(db, 'pending');\n }\n },\n pending,\n syncing: () => syncing(),\n online: () => online(),\n sync: syncNow,\n dispose() {\n disposed = true;\n if (syncTimer) clearInterval(syncTimer);\n db?.close();\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/offline.ts"],"names":["openDB","name","version","resolve","reject","request","db","err","idbGetAll","store","req","idbPut","key","value","tx","idbDelete","idbClear","createOfflineStore","options","keyField","items","signal","pendingOps","syncing","online","pending","computed","syncTimer","disposed","syncNow","init","stored","ops","initPromise","interval","getKey","item","put","list","idx","i","next","queueOp","remove","op","fetchFn","serverResponse","serverItems","partial","existing"],"mappings":"sCAuFA,eAAeA,CAAAA,CAAOC,EAAcC,CAAAA,CAAU,CAAA,CAAyB,CACrE,OAAI,OAAO,UAAc,GAAA,CAChB,OAAA,CAAQ,OAAO,IAAI,KAAA,CAAM,yBAAyB,CAAC,CAAA,CAErD,IAAI,OAAA,CAAQ,CAACC,CAAAA,CAASC,CAAAA,GAAW,CACtC,GAAI,CACF,IAAMC,CAAAA,CAAU,UAAU,IAAA,CAAKJ,CAAAA,CAAMC,CAAO,CAAA,CAC5CG,CAAAA,CAAQ,gBAAkB,IAAM,CAC9B,IAAMC,CAAAA,CAAKD,CAAAA,CAAQ,OACdC,CAAAA,CAAG,gBAAA,CAAiB,SAAS,OAAO,CAAA,EACvCA,CAAAA,CAAG,iBAAA,CAAkB,OAAO,CAAA,CAEzBA,EAAG,gBAAA,CAAiB,QAAA,CAAS,SAAS,CAAA,EACzCA,CAAAA,CAAG,kBAAkB,SAAA,CAAW,CAAE,cAAe,CAAA,CAAK,CAAC,EAE3D,CAAA,CACAD,CAAAA,CAAQ,UAAY,IAAMF,CAAAA,CAAQE,EAAQ,MAAM,CAAA,CAChDA,CAAAA,CAAQ,OAAA,CAAU,IAAMD,CAAAA,CAAOC,EAAQ,KAAA,EAAS,IAAI,MAAM,uBAAuB,CAAC,EACpF,CAAA,MAASE,CAAAA,CAAK,CACZH,CAAAA,CAAOG,CAAG,EACZ,CACF,CAAC,CACH,CAEA,eAAeC,EAAaF,CAAAA,CAAiBG,CAAAA,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CACA,OAAQ,CACNvB,CAAAA,CAAM,IAAI,EAAE,EACZE,CAAAA,CAAW,GAAA,CAAI,EAAE,CAAA,CACbhB,IACFU,CAAAA,CAASV,CAAAA,CAAI,OAAO,CAAA,CACpBU,CAAAA,CAASV,CAAAA,CAAI,SAAS,CAAA,EAE1B,CAAA,CACA,QAAAmB,CAAAA,CACA,OAAA,CAAS,IAAMF,CAAAA,EAAQ,CACvB,OAAQ,IAAMC,GAAAA,EAAO,CACrB,IAAA,CAAMK,CAAAA,CACN,OAAA,EAAU,CACRD,CAAAA,CAAW,IAAA,CACPD,KAAW,aAAA,CAAcA,GAAS,EACtCrB,CAAAA,EAAI,KAAA,GACN,CACF,CACF","file":"chunk-5NJYYK3Q.js","sourcesContent":["/**\n * Offline-first store with IndexedDB persistence and background sync.\n *\n * Data persists across page reloads. Changes made offline queue up\n * and sync automatically when connection returns. Conflict resolution\n * via configurable strategies (last-write-wins, merge, custom).\n *\n * ```ts\n * const todos = createOfflineStore('todos', {\n * sync: { url: '/api/todos', strategy: 'last-write-wins' },\n * });\n *\n * todos.add({ id: '1', text: 'Buy milk', done: false });\n * todos.items(); // reactive list\n * todos.syncing(); // boolean\n * todos.pending(); // number of unsynced changes\n * ```\n */\n\nimport { signal, computed } from './signals.js';\nimport type { Signal, ReadonlySignal } from './signals.js';\n\n// =========================================================================\n// Types\n// =========================================================================\n\nexport type ConflictStrategy = 'last-write-wins' | 'client-wins' | 'server-wins' | 'manual';\n\nexport interface OfflineStoreOptions<T> {\n /** Sync configuration */\n sync?: {\n /** Server URL for sync */\n url: string;\n /** Conflict resolution strategy (default: 'last-write-wins') */\n strategy?: ConflictStrategy;\n /** Sync interval in ms (default: 30000) */\n interval?: number;\n /** Custom fetch */\n fetch?: typeof globalThis.fetch;\n /** Auth headers */\n headers?: Record<string, string>;\n };\n /** Key field for items (default: 'id') */\n keyField?: string;\n /** Version for schema migrations */\n version?: number;\n}\n\nexport interface OfflineStore<T extends Record<string, unknown>> {\n /** All items (reactive) */\n items: ReadonlySignal<T[]>;\n /** Get a single item by key */\n get(key: string): T | undefined;\n /** Add or update an item */\n put(item: T): void;\n /** Add a new item */\n add(item: T): void;\n /** Update an existing item */\n update(key: string, partial: Partial<T>): void;\n /** Remove an item by key */\n remove(key: string): void;\n /** Clear all items */\n clear(): void;\n /** Number of unsynced changes */\n pending: ReadonlySignal<number>;\n /** Whether sync is in progress */\n syncing: ReadonlySignal<boolean>;\n /** Whether online */\n online: ReadonlySignal<boolean>;\n /** Force a sync now */\n sync(): Promise<void>;\n /** Dispose the store (stop sync, close DB) */\n dispose(): void;\n}\n\n/** An operation in the change queue */\ninterface PendingOp<T> {\n type: 'put' | 'delete';\n key: string;\n value?: T;\n timestamp: number;\n}\n\n// =========================================================================\n// IndexedDB wrapper\n// =========================================================================\n\nasync function openDB(name: string, version = 1): Promise<IDBDatabase> {\n if (typeof indexedDB === 'undefined') {\n return Promise.reject(new Error('IndexedDB not available'));\n }\n return new Promise((resolve, reject) => {\n try {\n const request = indexedDB.open(name, version);\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains('items')) {\n db.createObjectStore('items');\n }\n if (!db.objectStoreNames.contains('pending')) {\n db.createObjectStore('pending', { autoIncrement: true });\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error ?? new Error('IndexedDB open failed'));\n } catch (err) {\n reject(err);\n }\n });\n}\n\nasync function idbGetAll<T>(db: IDBDatabase, store: string): Promise<T[]> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(store, 'readonly');\n const req = tx.objectStore(store).getAll();\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nasync function idbPut(db: IDBDatabase, store: string, key: string, value: unknown): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(store, 'readwrite');\n tx.objectStore(store).put(value, key);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n}\n\nasync function idbDelete(db: IDBDatabase, store: string, key: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(store, 'readwrite');\n tx.objectStore(store).delete(key);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n}\n\nasync function idbClear(db: IDBDatabase, store: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(store, 'readwrite');\n tx.objectStore(store).clear();\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n}\n\n// =========================================================================\n// createOfflineStore\n// =========================================================================\n\n/**\n * Create an offline-first store backed by IndexedDB.\n */\nexport function createOfflineStore<T extends Record<string, unknown>>(\n name: string,\n options: OfflineStoreOptions<T> = {},\n): OfflineStore<T> {\n const keyField = options.keyField ?? 'id';\n const items = signal<T[]>([]);\n const pendingOps = signal<PendingOp<T>[]>([]);\n const syncing = signal(false);\n const online = signal(typeof navigator !== 'undefined' ? navigator.onLine : true);\n const pending = computed(() => pendingOps().length);\n\n let db: IDBDatabase | null = null;\n let syncTimer: ReturnType<typeof setInterval> | null = null;\n let disposed = false;\n\n // Online/offline tracking\n if (typeof window !== 'undefined') {\n window.addEventListener('online', () => {\n online.set(true);\n syncNow();\n });\n window.addEventListener('offline', () => online.set(false));\n }\n\n // Initialize — load from IndexedDB\n async function init(): Promise<void> {\n if (typeof indexedDB === 'undefined') return;\n try {\n db = await openDB(`akash-offline-${name}`, options.version ?? 1);\n const stored = await idbGetAll<T>(db, 'items');\n items.set(stored);\n const ops = await idbGetAll<PendingOp<T>>(db, 'pending');\n pendingOps.set(ops);\n } catch (err) { console.error('[AkashJS] Offline store init failed:', err); }\n }\n\n const initPromise = init();\n\n // Start periodic sync\n if (options.sync) {\n const interval = options.sync.interval ?? 30000;\n syncTimer = setInterval(() => {\n if (online() && pending() > 0 && !syncing()) {\n syncNow();\n }\n }, interval);\n }\n\n function getKey(item: T): string {\n return String((item as any)[keyField]);\n }\n\n function put(item: T): void {\n const key = getKey(item);\n items.update((list) => {\n const idx = list.findIndex((i) => getKey(i) === key);\n if (idx !== -1) {\n const next = [...list];\n next[idx] = item;\n return next;\n }\n return [...list, item];\n });\n\n queueOp({ type: 'put', key, value: item, timestamp: Date.now() });\n if (db) idbPut(db, 'items', key, item);\n }\n\n function remove(key: string): void {\n items.update((list) => list.filter((i) => getKey(i) !== key));\n queueOp({ type: 'delete', key, timestamp: Date.now() });\n if (db) idbDelete(db, 'items', key);\n }\n\n function queueOp(op: PendingOp<T>): void {\n pendingOps.update((ops) => [...ops, op]);\n if (db) {\n const tx = db.transaction('pending', 'readwrite');\n tx.objectStore('pending').add(op);\n }\n }\n\n async function syncNow(): Promise<void> {\n await initPromise;\n if (!options.sync || syncing() || disposed) return;\n const ops = pendingOps();\n if (ops.length === 0) return;\n\n syncing.set(true);\n const fetchFn = options.sync.fetch ?? globalThis.fetch.bind(globalThis);\n\n try {\n const response = await fetchFn(options.sync.url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...options.sync.headers,\n },\n body: JSON.stringify({ ops }),\n });\n\n if (response.ok) {\n pendingOps.set([]);\n if (db) await idbClear(db, 'pending');\n\n // Fetch latest server state\n const serverResponse = await fetchFn(options.sync.url, {\n headers: options.sync.headers,\n });\n if (serverResponse.ok) {\n const serverItems = await serverResponse.json() as T[];\n items.set(serverItems);\n // Update IndexedDB\n if (db) {\n await idbClear(db, 'items');\n for (const item of serverItems) {\n await idbPut(db, 'items', getKey(item), item);\n }\n }\n }\n }\n } catch (err) { console.warn('[AkashJS] Offline sync failed:', err); }\n finally {\n syncing.set(false);\n }\n }\n\n return {\n items: () => items(),\n get(key: string) { return items().find((i) => getKey(i) === key); },\n put,\n add: put,\n update(key: string, partial: Partial<T>) {\n const existing = items().find((i) => getKey(i) === key);\n if (existing) put({ ...existing, ...partial });\n },\n remove,\n clear() {\n items.set([]);\n pendingOps.set([]);\n if (db) {\n idbClear(db, 'items');\n idbClear(db, 'pending');\n }\n },\n pending,\n syncing: () => syncing(),\n online: () => online(),\n sync: syncNow,\n dispose() {\n disposed = true;\n if (syncTimer) clearInterval(syncTimer);\n db?.close();\n },\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkMWEB7QDN_cjs=require('./chunk-MWEB7QDN.cjs');var k=[];function v(s){k.push(...s.plugins);}var g=new Map;function x(s,a){return ()=>{if(g.has(s))return g.get(s);let r=a.state(),o=A(s,r,a);return g.set(s,o),o}}function A(s,a,r){let o={},c=Object.keys(a);for(let t of c)o[t]=chunkMWEB7QDN_cjs.c(a[t]);let n={$id:s};for(let t of c)n[t]=o[t];if(r.getters)for(let[t,e]of Object.entries(r.getters))n[t]=chunkMWEB7QDN_cjs.d(()=>e.call(n,o));let l=[...k,...r.plugins??[]];if(r.actions)for(let[t,e]of Object.entries(r.actions))n[t]=(...i)=>{for(let f of l)f.onAction?.(n,t,i);return e.apply(n,i)};n.$reset=()=>{let t=r.state();for(let e of c)o[e].set(t[e]);},n.$patch=t=>{for(let[e,i]of Object.entries(t))e in o&&o[e].set(i);},n.$snapshot=()=>{let t={};for(let e of c)t[e]=o[e]();return t};let u=new Set,S=null;n.$subscribe=t=>{if(u.add(t),!S){let e=true;S=chunkMWEB7QDN_cjs.e(()=>{for(let f of c)o[f]();if(e){e=false;return}let i=n.$snapshot();for(let f of u)f(i);});}return ()=>{u.delete(t),u.size===0&&S&&(S(),S=null);}};for(let t of l)t.init?.(n);return n}function b(){g.clear();}function R(){return g}exports.a=v;exports.b=x;exports.c=b;exports.d=R;//# sourceMappingURL=chunk-HTRGNLQ3.cjs.map
2
- //# sourceMappingURL=chunk-HTRGNLQ3.cjs.map
1
+ 'use strict';var chunkRTJ6UDGV_cjs=require('./chunk-RTJ6UDGV.cjs');var k=[];function v(s){k.push(...s.plugins);}var g=new Map;function x(s,a){return ()=>{if(g.has(s))return g.get(s);let r=a.state(),o=A(s,r,a);return g.set(s,o),o}}function A(s,a,r){let o={},c=Object.keys(a);for(let t of c)o[t]=chunkRTJ6UDGV_cjs.l(a[t]);let n={$id:s};for(let t of c)n[t]=o[t];if(r.getters)for(let[t,e]of Object.entries(r.getters))n[t]=chunkRTJ6UDGV_cjs.m(()=>e.call(n,o));let l=[...k,...r.plugins??[]];if(r.actions)for(let[t,e]of Object.entries(r.actions))n[t]=(...i)=>{for(let f of l)f.onAction?.(n,t,i);return e.apply(n,i)};n.$reset=()=>{let t=r.state();for(let e of c)o[e].set(t[e]);},n.$patch=t=>{for(let[e,i]of Object.entries(t))e in o&&o[e].set(i);},n.$snapshot=()=>{let t={};for(let e of c)t[e]=o[e]();return t};let u=new Set,S=null;n.$subscribe=t=>{if(u.add(t),!S){let e=true;S=chunkRTJ6UDGV_cjs.n(()=>{for(let f of c)o[f]();if(e){e=false;return}let i=n.$snapshot();for(let f of u)f(i);});}return ()=>{u.delete(t),u.size===0&&S&&(S(),S=null);}};for(let t of l)t.init?.(n);return n}function b(){g.clear();}function R(){return g}exports.a=v;exports.b=x;exports.c=b;exports.d=R;//# sourceMappingURL=chunk-A3VPGLBN.cjs.map
2
+ //# sourceMappingURL=chunk-A3VPGLBN.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/store.ts"],"names":["globalPlugins","configureStores","options","storeInstances","defineStore","id","definition","initialState","store","createStoreInstance","stateSignals","stateKeys","key","signal","getterFn","computed","plugins","actionFn","args","plugin","fresh","partial","value","snapshot","subscribers","subscribeEffect","callback","isInitial","effect","cb","clearStores","__getStoreInstances"],"mappings":"mEAoFA,IAAMA,EAA+B,EAAC,CAG/B,SAASC,CAAAA,CAAgBC,EAA2C,CACzEF,CAAAA,CAAc,IAAA,CAAK,GAAGE,EAAQ,OAAO,EACvC,CAIA,IAAMC,EAAiB,IAAI,GAAA,CAQpB,SAASC,CAAAA,CAKdC,EACAC,CAAAA,CACsB,CACtB,OAAO,IAAM,CAEX,GAAIH,CAAAA,CAAe,GAAA,CAAIE,CAAE,EACvB,OAAOF,CAAAA,CAAe,GAAA,CAAIE,CAAE,EAG9B,IAAME,CAAAA,CAAeD,CAAA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,CAAQ,EAEvBF,CAAAA,CAAY,IAAA,GAAS,CAAA,EAAKC,CAAAA,GAC5BA,GAAgB,CAChBA,CAAAA,CAAkB,IAAA,EAEtB,CACF,EAGA,IAAA,IAAWN,CAAAA,IAAUH,CAAAA,CAASG,CAAAA,CAAO,OAAOX,CAAK,CAAA,CAEjD,OAAOA,CACT,CAKO,SAASsB,CAAAA,EAAoB,CAClC3B,CAAAA,CAAe,QACjB,CAGO,SAAS4B,CAAAA,EAAyD,CACvE,OAAO5B,CACT","file":"chunk-HTRGNLQ3.cjs","sourcesContent":["/**\n * Global state management via defineStore().\n *\n * Stores are singleton signal containers that persist across\n * components. They provide shared state, computed getters,\n * and actions — no external library needed.\n *\n * ```ts\n * const useCounterStore = defineStore('counter', {\n * state: () => ({ count: 0, name: 'Counter' }),\n * getters: {\n * doubled: (state) => state.count() * 2,\n * },\n * actions: {\n * increment() { this.count.update(c => c + 1); },\n * reset() { this.count.set(0); },\n * },\n * });\n *\n * // In any component:\n * const store = useCounterStore();\n * store.count(); // 0\n * store.doubled(); // 0\n * store.increment();\n * store.count(); // 1\n * ```\n */\n\nimport { signal, computed, effect } from './signals.js';\nimport type { Signal, ReadonlySignal } from './signals.js';\n\n// --- Types ---\n\ntype StateFactory<S> = () => S;\n\ntype Getters<S, G> = {\n [K in keyof G]: (state: SignalifiedState<S>) => G[K];\n};\n\ntype Actions<A> = {\n [K in keyof A]: A[K] extends (...args: infer P) => infer R\n ? (...args: P) => R\n : never;\n};\n\n/** Maps plain state values to signals */\ntype SignalifiedState<S> = {\n [K in keyof S]: Signal<S[K]>;\n};\n\n/** The store instance returned to consumers */\nexport type Store<S, G, A> = SignalifiedState<S> & {\n [K in keyof G]: ReadonlySignal<G[K]>;\n} & {\n [K in keyof A]: A[K] extends (...args: infer P) => infer R\n ? (...args: P) => R\n : never;\n} & {\n /** Reset all state to initial values */\n $reset(): void;\n /** Merge partial state into the store */\n $patch(partial: Partial<S>): void;\n /** Subscribe to all state changes */\n $subscribe(callback: (state: S) => void): () => void;\n /** Get a plain snapshot of current state */\n $snapshot(): S;\n /** Store ID */\n $id: string;\n};\n\nexport interface StoreDefinition<S, G, A> {\n state: StateFactory<S>;\n getters?: Getters<S, G>;\n actions?: A;\n plugins?: StorePlugin[];\n}\n\n// --- Plugin system ---\n\nexport interface StorePlugin {\n init?(store: Store<any, any, any>): void;\n onAction?(store: Store<any, any, any>, actionName: string, args: unknown[]): void;\n}\n\nconst globalPlugins: StorePlugin[] = [];\n\n/** Register global plugins that apply to all stores */\nexport function configureStores(options: { plugins: StorePlugin[] }): void {\n globalPlugins.push(...options.plugins);\n}\n\n// --- Store registry (singleton) ---\n\nconst storeInstances = new Map<string, Store<any, any, any>>();\n\n// --- defineStore ---\n\n/**\n * Define a global store. Returns a composable function that\n * always returns the same store instance (singleton).\n */\nexport function defineStore<\n S extends Record<string, unknown>,\n G extends Record<string, unknown> = {},\n A extends Record<string, (...args: any[]) => any> = {},\n>(\n id: string,\n definition: StoreDefinition<S, G, A>,\n): () => Store<S, G, A> {\n return () => {\n // Return existing instance if already created\n if (storeInstances.has(id)) {\n return storeInstances.get(id) as Store<S, G, A>;\n }\n\n const initialState = definition.state();\n const store = createStoreInstance(id, initialState, definition);\n storeInstances.set(id, store);\n return store;\n };\n}\n\nfunction createStoreInstance<\n S extends Record<string, unknown>,\n G extends Record<string, unknown>,\n A extends Record<string, (...args: any[]) => any>,\n>(\n id: string,\n initialState: S,\n definition: StoreDefinition<S, G, A>,\n): Store<S, G, A> {\n // Create signals for each state property\n const stateSignals: Record<string, Signal<unknown>> = {};\n const stateKeys = Object.keys(initialState);\n\n for (const key of stateKeys) {\n stateSignals[key] = signal(initialState[key]);\n }\n\n // Build the store object first so getters can reference other getters via `this`\n const store: any = { $id: id };\n\n // Add state signals\n for (const key of stateKeys) {\n store[key] = stateSignals[key];\n }\n\n // Create computed getters — bound to store so `this.otherGetter()` works\n if (definition.getters) {\n for (const [key, getterFn] of Object.entries(definition.getters)) {\n store[key] = computed(() =>\n (getterFn as Function).call(store, stateSignals),\n );\n }\n }\n\n // Collect all plugins (global + per-store)\n const plugins = [...globalPlugins, ...(definition.plugins ?? [])];\n\n // Bind actions with `this` pointing to the full store (state + getters + actions)\n if (definition.actions) {\n for (const [key, actionFn] of Object.entries(definition.actions)) {\n store[key] = (...args: unknown[]) => {\n for (const plugin of plugins) plugin.onAction?.(store, key, args);\n return (actionFn as Function).apply(store, args);\n };\n }\n }\n\n // $reset\n store.$reset = () => {\n const fresh = definition.state();\n for (const key of stateKeys) {\n stateSignals[key].set(fresh[key as keyof S]);\n }\n };\n\n // $patch — merge partial state\n store.$patch = (partial: Partial<S>) => {\n for (const [key, value] of Object.entries(partial)) {\n if (key in stateSignals) {\n stateSignals[key].set(value);\n }\n }\n };\n\n // $snapshot\n store.$snapshot = (): S => {\n const snapshot: Record<string, unknown> = {};\n for (const key of stateKeys) {\n snapshot[key] = stateSignals[key]();\n }\n return snapshot as S;\n };\n\n // $subscribe — watch all state signals and notify on change\n const subscribers = new Set<(state: S) => void>();\n let subscribeEffect: (() => void) | null = null;\n store.$subscribe = (callback: (state: S) => void): (() => void) => {\n subscribers.add(callback);\n // Start watching if this is the first subscriber\n if (!subscribeEffect) {\n let isInitial = true;\n subscribeEffect = effect(() => {\n // Read all state signals to track them\n for (const key of stateKeys) {\n stateSignals[key]();\n }\n // Skip initial run — only notify on actual changes\n if (isInitial) {\n isInitial = false;\n return;\n }\n const snapshot = store.$snapshot();\n for (const cb of subscribers) {\n cb(snapshot);\n }\n });\n }\n return () => {\n subscribers.delete(callback);\n // Dispose effect when no subscribers remain\n if (subscribers.size === 0 && subscribeEffect) {\n subscribeEffect();\n subscribeEffect = null;\n }\n };\n };\n\n // Initialize plugins\n for (const plugin of plugins) plugin.init?.(store);\n\n return store as Store<S, G, A>;\n}\n\n/**\n * Clear all store instances (useful for testing).\n */\nexport function clearStores(): void {\n storeInstances.clear();\n}\n\n/** @internal — exposes store registry for devtools */\nexport function __getStoreInstances(): Map<string, Store<any, any, any>> {\n return storeInstances;\n}\n"]}
1
+ {"version":3,"sources":["../src/store.ts"],"names":["globalPlugins","configureStores","options","storeInstances","defineStore","id","definition","initialState","store","createStoreInstance","stateSignals","stateKeys","key","signal","getterFn","computed","plugins","actionFn","args","plugin","fresh","partial","value","snapshot","subscribers","subscribeEffect","callback","isInitial","effect","cb","clearStores","__getStoreInstances"],"mappings":"mEAoFA,IAAMA,EAA+B,EAAC,CAG/B,SAASC,CAAAA,CAAgBC,EAA2C,CACzEF,CAAAA,CAAc,IAAA,CAAK,GAAGE,EAAQ,OAAO,EACvC,CAIA,IAAMC,EAAiB,IAAI,GAAA,CAQpB,SAASC,CAAAA,CAKdC,EACAC,CAAAA,CACsB,CACtB,OAAO,IAAM,CAEX,GAAIH,CAAAA,CAAe,GAAA,CAAIE,CAAE,EACvB,OAAOF,CAAAA,CAAe,GAAA,CAAIE,CAAE,EAG9B,IAAME,CAAAA,CAAeD,CAAAA,CAAW,KAAA,GAC1BE,CAAAA,CAAQC,CAAAA,CAAoBJ,CAAAA,CAAIE,CAAAA,CAAcD,CAAU,CAAA,CAC9D,OAAAH,CAAAA,CAAe,GAAA,CAAIE,EAAIG,CAAK,CAAA,CACrBA,CACT,CACF,CAEA,SAASC,CAAAA,CAKPJ,CAAAA,CACAE,CAAAA,CACAD,EACgB,CAEhB,IAAMI,CAAAA,CAAgD,GAChDC,CAAAA,CAAY,MAAA,CAAO,IAAA,CAAKJ,CAAY,EAE1C,IAAA,IAAWK,CAAAA,IAAOD,EAChBD,CAAAA,CAAaE,CAAG,EAAIC,mBAAAA,CAAON,CAAAA,CAAaK,CAAG,CAAC,EAI9C,IAAMJ,CAAAA,CAAa,CAAE,GAAA,CAAKH,CAAG,CAAA,CAG7B,IAAA,IAAWO,CAAAA,IAAOD,CAAAA,CAChBH,EAAMI,CAAG,CAAA,CAAIF,CAAAA,CAAaE,CAAG,EAI/B,GAAIN,CAAAA,CAAW,OAAA,CACb,IAAA,GAAW,CAACM,CAA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AEpC,OAAOW,CACT,CAAA,CAGA,IAAMC,CAAAA,CAAc,IAAI,GAAA,CACpBC,CAAAA,CAAuC,KAC3CjB,CAAAA,CAAM,UAAA,CAAckB,GAA+C,CAGjE,GAFAF,CAAAA,CAAY,GAAA,CAAIE,CAAQ,CAAA,CAEpB,CAACD,CAAAA,CAAiB,CACpB,IAAIE,CAAAA,CAAY,IAAA,CAChBF,CAAAA,CAAkBG,mBAAAA,CAAO,IAAM,CAE7B,IAAA,IAAWhB,CAAAA,IAAOD,CAAAA,CAChBD,EAAaE,CAAG,CAAA,EAAE,CAGpB,GAAIe,EAAW,CACbA,CAAAA,CAAY,KAAA,CACZ,MACF,CACA,IAAMJ,CAAAA,CAAWf,CAAAA,CAAM,SAAA,GACvB,IAAA,IAAWqB,CAAAA,IAAML,EACfK,CAAAA,CAAGN,CAAQ,EAEf,CAAC,EACH,CACA,OAAO,IAAM,CACXC,CAAAA,CAAY,MAAA,CAAOE,CAAQ,EAEvBF,CAAAA,CAAY,IAAA,GAAS,CAAA,EAAKC,CAAAA,GAC5BA,GAAgB,CAChBA,CAAAA,CAAkB,IAAA,EAEtB,CACF,EAGA,IAAA,IAAWN,CAAAA,IAAUH,CAAAA,CAASG,CAAAA,CAAO,OAAOX,CAAK,CAAA,CAEjD,OAAOA,CACT,CAKO,SAASsB,CAAAA,EAAoB,CAClC3B,CAAAA,CAAe,QACjB,CAGO,SAAS4B,CAAAA,EAAyD,CACvE,OAAO5B,CACT","file":"chunk-A3VPGLBN.cjs","sourcesContent":["/**\n * Global state management via defineStore().\n *\n * Stores are singleton signal containers that persist across\n * components. They provide shared state, computed getters,\n * and actions — no external library needed.\n *\n * ```ts\n * const useCounterStore = defineStore('counter', {\n * state: () => ({ count: 0, name: 'Counter' }),\n * getters: {\n * doubled: (state) => state.count() * 2,\n * },\n * actions: {\n * increment() { this.count.update(c => c + 1); },\n * reset() { this.count.set(0); },\n * },\n * });\n *\n * // In any component:\n * const store = useCounterStore();\n * store.count(); // 0\n * store.doubled(); // 0\n * store.increment();\n * store.count(); // 1\n * ```\n */\n\nimport { signal, computed, effect } from './signals.js';\nimport type { Signal, ReadonlySignal } from './signals.js';\n\n// --- Types ---\n\ntype StateFactory<S> = () => S;\n\ntype Getters<S, G> = {\n [K in keyof G]: (state: SignalifiedState<S>) => G[K];\n};\n\ntype Actions<A> = {\n [K in keyof A]: A[K] extends (...args: infer P) => infer R\n ? (...args: P) => R\n : never;\n};\n\n/** Maps plain state values to signals */\ntype SignalifiedState<S> = {\n [K in keyof S]: Signal<S[K]>;\n};\n\n/** The store instance returned to consumers */\nexport type Store<S, G, A> = SignalifiedState<S> & {\n [K in keyof G]: ReadonlySignal<G[K]>;\n} & {\n [K in keyof A]: A[K] extends (...args: infer P) => infer R\n ? (...args: P) => R\n : never;\n} & {\n /** Reset all state to initial values */\n $reset(): void;\n /** Merge partial state into the store */\n $patch(partial: Partial<S>): void;\n /** Subscribe to all state changes */\n $subscribe(callback: (state: S) => void): () => void;\n /** Get a plain snapshot of current state */\n $snapshot(): S;\n /** Store ID */\n $id: string;\n};\n\nexport interface StoreDefinition<S, G, A> {\n state: StateFactory<S>;\n getters?: Getters<S, G>;\n actions?: A;\n plugins?: StorePlugin[];\n}\n\n// --- Plugin system ---\n\nexport interface StorePlugin {\n init?(store: Store<any, any, any>): void;\n onAction?(store: Store<any, any, any>, actionName: string, args: unknown[]): void;\n}\n\nconst globalPlugins: StorePlugin[] = [];\n\n/** Register global plugins that apply to all stores */\nexport function configureStores(options: { plugins: StorePlugin[] }): void {\n globalPlugins.push(...options.plugins);\n}\n\n// --- Store registry (singleton) ---\n\nconst storeInstances = new Map<string, Store<any, any, any>>();\n\n// --- defineStore ---\n\n/**\n * Define a global store. Returns a composable function that\n * always returns the same store instance (singleton).\n */\nexport function defineStore<\n S extends Record<string, unknown>,\n G extends Record<string, unknown> = {},\n A extends Record<string, (...args: any[]) => any> = {},\n>(\n id: string,\n definition: StoreDefinition<S, G, A>,\n): () => Store<S, G, A> {\n return () => {\n // Return existing instance if already created\n if (storeInstances.has(id)) {\n return storeInstances.get(id) as Store<S, G, A>;\n }\n\n const initialState = definition.state();\n const store = createStoreInstance(id, initialState, definition);\n storeInstances.set(id, store);\n return store;\n };\n}\n\nfunction createStoreInstance<\n S extends Record<string, unknown>,\n G extends Record<string, unknown>,\n A extends Record<string, (...args: any[]) => any>,\n>(\n id: string,\n initialState: S,\n definition: StoreDefinition<S, G, A>,\n): Store<S, G, A> {\n // Create signals for each state property\n const stateSignals: Record<string, Signal<unknown>> = {};\n const stateKeys = Object.keys(initialState);\n\n for (const key of stateKeys) {\n stateSignals[key] = signal(initialState[key]);\n }\n\n // Build the store object first so getters can reference other getters via `this`\n const store: any = { $id: id };\n\n // Add state signals\n for (const key of stateKeys) {\n store[key] = stateSignals[key];\n }\n\n // Create computed getters — bound to store so `this.otherGetter()` works\n if (definition.getters) {\n for (const [key, getterFn] of Object.entries(definition.getters)) {\n store[key] = computed(() =>\n (getterFn as Function).call(store, stateSignals),\n );\n }\n }\n\n // Collect all plugins (global + per-store)\n const plugins = [...globalPlugins, ...(definition.plugins ?? [])];\n\n // Bind actions with `this` pointing to the full store (state + getters + actions)\n if (definition.actions) {\n for (const [key, actionFn] of Object.entries(definition.actions)) {\n store[key] = (...args: unknown[]) => {\n for (const plugin of plugins) plugin.onAction?.(store, key, args);\n return (actionFn as Function).apply(store, args);\n };\n }\n }\n\n // $reset\n store.$reset = () => {\n const fresh = definition.state();\n for (const key of stateKeys) {\n stateSignals[key].set(fresh[key as keyof S]);\n }\n };\n\n // $patch — merge partial state\n store.$patch = (partial: Partial<S>) => {\n for (const [key, value] of Object.entries(partial)) {\n if (key in stateSignals) {\n stateSignals[key].set(value);\n }\n }\n };\n\n // $snapshot\n store.$snapshot = (): S => {\n const snapshot: Record<string, unknown> = {};\n for (const key of stateKeys) {\n snapshot[key] = stateSignals[key]();\n }\n return snapshot as S;\n };\n\n // $subscribe — watch all state signals and notify on change\n const subscribers = new Set<(state: S) => void>();\n let subscribeEffect: (() => void) | null = null;\n store.$subscribe = (callback: (state: S) => void): (() => void) => {\n subscribers.add(callback);\n // Start watching if this is the first subscriber\n if (!subscribeEffect) {\n let isInitial = true;\n subscribeEffect = effect(() => {\n // Read all state signals to track them\n for (const key of stateKeys) {\n stateSignals[key]();\n }\n // Skip initial run — only notify on actual changes\n if (isInitial) {\n isInitial = false;\n return;\n }\n const snapshot = store.$snapshot();\n for (const cb of subscribers) {\n cb(snapshot);\n }\n });\n }\n return () => {\n subscribers.delete(callback);\n // Dispose effect when no subscribers remain\n if (subscribers.size === 0 && subscribeEffect) {\n subscribeEffect();\n subscribeEffect = null;\n }\n };\n };\n\n // Initialize plugins\n for (const plugin of plugins) plugin.init?.(store);\n\n return store as Store<S, G, A>;\n}\n\n/**\n * Clear all store instances (useful for testing).\n */\nexport function clearStores(): void {\n storeInstances.clear();\n}\n\n/** @internal — exposes store registry for devtools */\nexport function __getStoreInstances(): Map<string, Store<any, any, any>> {\n return storeInstances;\n}\n"]}
@@ -1,2 +1,2 @@
1
- import {c}from'./chunk-JGHHEF7H.js';var g=class{entry;constructor(e,n){this.entry={value:e,timestamp:Date.now(),peerId:n};}get value(){return this.entry.value}get timestamp(){return this.entry.timestamp}set(e,n){let s=Date.now();return n===this.entry.peerId||s>this.entry.timestamp||s===this.entry.timestamp&&n>this.entry.peerId?(this.entry={value:e,timestamp:Math.max(s,this.entry.timestamp+1),peerId:n},true):false}merge(e){return e.timestamp>this.entry.timestamp||e.timestamp===this.entry.timestamp&&e.peerId>this.entry.peerId?(this.entry=e,true):false}toEntry(){return {...this.entry}}};function I(i){let e=null,n=[],s=[];return {send(t){e?.send(JSON.stringify({type:"op",room:i.room,...t}));},onReceive(t){n.push(t);let o=false;return ()=>{if(o)return;o=true;let c=n.indexOf(t);c!==-1&&n.splice(c,1);}},onPresence(t){return s.push(t),()=>{let o=s.indexOf(t);o!==-1&&s.splice(o,1);}},sendPresence(t){e?.send(JSON.stringify({type:"presence",room:i.room,data:t}));},connect(){e=new WebSocket(i.url,i.protocols),e.onmessage=t=>{try{let o=JSON.parse(t.data);if(o.type==="op")for(let c of n)c(o);else if(o.type==="presence")for(let c of s)c(o.peerId,o.data);}catch{}},e.onopen=()=>{e?.send(JSON.stringify({type:"join",room:i.room}));};},disconnect(){e?.close(),e=null;}}}function h(){let i=[];return {send(e){for(let n of i)n(e);},onReceive(e){i.push(e);let n=false;return ()=>{if(n)return;n=true;let s=i.indexOf(e);s!==-1&&i.splice(s,1);}},connect(){},disconnect(){}}}var w=0;function O(i,e,n={}){let s=n.peerId??`peer-${++w}-${Date.now()}`,t=n.transport??h(),o=new Map,c$1={};for(let[r,a]of Object.entries(e))o.set(r,new g(a,s)),c$1[r]=c(a);let l={};for(let r of Object.keys(e)){let a=c$1[r],y=o.get(r),p=(()=>a());p.set=u=>{y.set(u,s),a.set(u),t.send({type:"set",key:r,value:u,timestamp:y.timestamp,peerId:s});},p.update=u=>{p.set(u(a()));},p.peek=()=>a.peek(),l[r]=p;}let S=c([]),m=c(false),k=c({}),f=c(new Map),v=t.onReceive(r=>{r.type==="set"&&o.has(r.key)&&o.get(r.key).merge({value:r.value,timestamp:r.timestamp,peerId:r.peerId})&&c$1[r.key].set(r.value);}),T=t.onPresence?.((r,a)=>{f.update(y=>{let p=new Map(y);return p.set(r,a),p});});return {state:l,peers:()=>S(),presence:k,peerPresence:()=>f(),peerId:s,connected:()=>m(),connect(){t.connect(),m.set(true);},disconnect(){t.disconnect(),m.set(false);},dispose(){v(),T?.(),t.disconnect();}}}export{g as a,I as b,h as c,O as d};//# sourceMappingURL=chunk-QSDVJOXO.js.map
2
- //# sourceMappingURL=chunk-QSDVJOXO.js.map
1
+ import {l}from'./chunk-TWA4T6PX.js';var g=class{entry;constructor(e,n){this.entry={value:e,timestamp:Date.now(),peerId:n};}get value(){return this.entry.value}get timestamp(){return this.entry.timestamp}set(e,n){let s=Date.now();return n===this.entry.peerId||s>this.entry.timestamp||s===this.entry.timestamp&&n>this.entry.peerId?(this.entry={value:e,timestamp:Math.max(s,this.entry.timestamp+1),peerId:n},true):false}merge(e){return e.timestamp>this.entry.timestamp||e.timestamp===this.entry.timestamp&&e.peerId>this.entry.peerId?(this.entry=e,true):false}toEntry(){return {...this.entry}}};function I(i){let e=null,n=[],s=[];return {send(t){e?.send(JSON.stringify({type:"op",room:i.room,...t}));},onReceive(t){n.push(t);let o=false;return ()=>{if(o)return;o=true;let c=n.indexOf(t);c!==-1&&n.splice(c,1);}},onPresence(t){return s.push(t),()=>{let o=s.indexOf(t);o!==-1&&s.splice(o,1);}},sendPresence(t){e?.send(JSON.stringify({type:"presence",room:i.room,data:t}));},connect(){e=new WebSocket(i.url,i.protocols),e.onmessage=t=>{try{let o=JSON.parse(t.data);if(o.type==="op")for(let c of n)c(o);else if(o.type==="presence")for(let c of s)c(o.peerId,o.data);}catch{}},e.onopen=()=>{e?.send(JSON.stringify({type:"join",room:i.room}));};},disconnect(){e?.close(),e=null;}}}function h(){let i=[];return {send(e){for(let n of i)n(e);},onReceive(e){i.push(e);let n=false;return ()=>{if(n)return;n=true;let s=i.indexOf(e);s!==-1&&i.splice(s,1);}},connect(){},disconnect(){}}}var w=0;function O(i,e,n={}){let s=n.peerId??`peer-${++w}-${Date.now()}`,t=n.transport??h(),o=new Map,c={};for(let[r,a]of Object.entries(e))o.set(r,new g(a,s)),c[r]=l(a);let l$1={};for(let r of Object.keys(e)){let a=c[r],y=o.get(r),p=(()=>a());p.set=u=>{y.set(u,s),a.set(u),t.send({type:"set",key:r,value:u,timestamp:y.timestamp,peerId:s});},p.update=u=>{p.set(u(a()));},p.peek=()=>a.peek(),l$1[r]=p;}let S=l([]),m=l(false),k=l({}),f=l(new Map),v=t.onReceive(r=>{r.type==="set"&&o.has(r.key)&&o.get(r.key).merge({value:r.value,timestamp:r.timestamp,peerId:r.peerId})&&c[r.key].set(r.value);}),T=t.onPresence?.((r,a)=>{f.update(y=>{let p=new Map(y);return p.set(r,a),p});});return {state:l$1,peers:()=>S(),presence:k,peerPresence:()=>f(),peerId:s,connected:()=>m(),connect(){t.connect(),m.set(true);},disconnect(){t.disconnect(),m.set(false);},dispose(){v(),T?.(),t.disconnect();}}}export{g as a,I as b,h as c,O as d};//# sourceMappingURL=chunk-CEJF44LZ.js.map
2
+ //# sourceMappingURL=chunk-CEJF44LZ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sync.ts"],"names":["LWWRegister","initialValue","peerId","value","ts","remote","createWebSocketTransport","options","ws","opHandlers","presenceHandlers","op","handler","removed","i","data","e","msg","h","createLocalTransport","peerIdCounter","createSync","roomId","initialState","transport","registers","stateSignals","key","signal","state","original","register","proxy","fn","peers","connected","presence","peerPresenceMap","unsubOps","unsubPresence","remotePeerId","map","next"],"mappings":"oCAqCO,IAAMA,EAAN,KAAqB,CAClB,KAAA,CAER,WAAA,CAAYC,EAAiBC,CAAAA,CAAgB,CAC3C,IAAA,CAAK,KAAA,CAAQ,CAAE,KAAA,CAAOD,CAAAA,CAAc,SAAA,CAAW,IAAA,CAAK,KAAI,CAAG,MAAA,CAAAC,CAAO,EACpE,CAEA,IAAI,KAAA,EAAW,CACb,OAAO,KAAK,KAAA,CAAM,KACpB,CAEA,IAAI,WAAoB,CACtB,OAAO,IAAA,CAAK,KAAA,CAAM,SACpB,CAEA,GAAA,CAAIC,CAAAA,CAAUD,CAAAA,CAAyB,CACrC,IAAME,CAAAA,CAAK,IAAA,CAAK,GAAA,GAGhB,OACEF,CAAAA,GAAW,IAAA,CAAK,KAAA,CAAM,QACtBE,CAAAA,CAAK,IAAA,CAAK,KAAA,CAAM,SAAA,EACfA,IAAO,IAAA,CAAK,KAAA,CAAM,SAAA,EAAaF,CAAAA,CAAS,KAAK,KAAA,CAAM,MAAA,EAEpD,IAAA,CAAK,KAAA,CAAQ,CAAE,KAAA,CAAAC,CAAAA,CAAO,SAAA,CAAW,IAAA,CAAK,IAAIC,CAAAA,CAAI,IAAA,CAAK,KAAA,CAAM,SAAA,CAAY,CAAC,CA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CAAID,CAAG,EACxB,OAAAC,CAAAA,CAAK,GAAA,CAAIF,CAAAA,CAAczB,CAAI,CAAA,CACpB2B,CACT,CAAC,EACH,CAAC,CAAA,CAED,OAAO,CACL,KAAA,CAAAb,EACA,KAAA,CAAO,IAAMK,CAAAA,EAAM,CACnB,SAAAE,CAAAA,CACA,YAAA,CAAc,IAAMC,CAAAA,GACpB,MAAA,CAAAnC,CAAAA,CACA,SAAA,CAAW,IAAMiC,GAAU,CAC3B,OAAA,EAAU,CACRX,CAAAA,CAAU,SAAQ,CAClBW,CAAAA,CAAU,GAAA,CAAI,IAAI,EACpB,CAAA,CACA,UAAA,EAAa,CACXX,CAAAA,CAAU,YAAW,CACrBW,CAAAA,CAAU,GAAA,CAAI,KAAK,EACrB,CAAA,CACA,OAAA,EAAU,CACRG,CAAAA,GACAC,CAAAA,IAAgB,CAChBf,EAAU,UAAA,GACZ,CACF,CACF","file":"chunk-QSDVJOXO.js","sourcesContent":["/**\n * Collaborative signals with CRDT.\n *\n * Make any signal multiplayer with one line. Multiple users can\n * edit the same state simultaneously with automatic conflict\n * resolution via Last-Writer-Wins Register and Operation-based CRDTs.\n *\n * ```ts\n * const doc = createSync('doc-123', {\n * title: '',\n * blocks: [],\n * cursor: { x: 0, y: 0 },\n * });\n *\n * doc.state.title.set('Hello'); // syncs to all peers\n * doc.peers(); // list of connected users\n * doc.presence.set({ cursor: { x: 10, y: 20 } });\n * ```\n */\n\nimport { signal, computed } from './signals.js';\nimport type { Signal, ReadonlySignal } from './signals.js';\n\n// =========================================================================\n// CRDT — Last-Writer-Wins Register\n// =========================================================================\n\nexport interface LWWEntry<T> {\n value: T;\n timestamp: number;\n peerId: string;\n}\n\n/**\n * Last-Writer-Wins Register — simplest CRDT for single values.\n * The write with the highest timestamp wins on conflict.\n */\nexport class LWWRegister<T> {\n private entry: LWWEntry<T>;\n\n constructor(initialValue: T, peerId: string) {\n this.entry = { value: initialValue, timestamp: Date.now(), peerId };\n }\n\n get value(): T {\n return this.entry.value;\n }\n\n get timestamp(): number {\n return this.entry.timestamp;\n }\n\n set(value: T, peerId: string): boolean {\n const ts = Date.now();\n // Local writes always succeed (same peer always advances its own state).\n // Cross-peer conflicts resolve by highest timestamp, then peerId tiebreak.\n if (\n peerId === this.entry.peerId ||\n ts > this.entry.timestamp ||\n (ts === this.entry.timestamp && peerId > this.entry.peerId)\n ) {\n this.entry = { value, timestamp: Math.max(ts, this.entry.timestamp + 1), peerId };\n return true;\n }\n return false;\n }\n\n merge(remote: LWWEntry<T>): boolean {\n if (\n remote.timestamp > this.entry.timestamp ||\n (remote.timestamp === this.entry.timestamp && remote.peerId > this.entry.peerId)\n ) {\n this.entry = remote;\n return true;\n }\n return false;\n }\n\n toEntry(): LWWEntry<T> {\n return { ...this.entry };\n }\n}\n\n// =========================================================================\n// Operation log for list CRDTs\n// =========================================================================\n\nexport type SyncOp =\n | { type: 'set'; key: string; value: unknown; timestamp: number; peerId: string }\n | { type: 'insert'; key: string; index: number; value: unknown; timestamp: number; peerId: string }\n | { type: 'delete'; key: string; index: number; timestamp: number; peerId: string };\n\n// =========================================================================\n// Sync transport interface\n// =========================================================================\n\nexport interface SyncTransport {\n /** Send an operation to peers */\n send(op: SyncOp): void;\n /** Listen for operations from peers */\n onReceive(handler: (op: SyncOp) => void): () => void;\n /** Listen for peer presence updates */\n onPresence?(handler: (peerId: string, data: unknown) => void): () => void;\n /** Send presence data */\n sendPresence?(data: unknown): void;\n /** Connect to the sync channel */\n connect(): void;\n /** Disconnect */\n disconnect(): void;\n}\n\n// =========================================================================\n// WebSocket transport\n// =========================================================================\n\nexport interface WebSocketTransportOptions {\n url: string;\n room: string;\n protocols?: string | string[];\n}\n\nexport function createWebSocketTransport(options: WebSocketTransportOptions): SyncTransport {\n let ws: WebSocket | null = null;\n const opHandlers: Array<(op: SyncOp) => void> = [];\n const presenceHandlers: Array<(peerId: string, data: unknown) => void> = [];\n\n return {\n send(op: SyncOp) {\n ws?.send(JSON.stringify({ type: 'op', room: options.room, ...op }));\n },\n onReceive(handler) {\n opHandlers.push(handler);\n let removed = false;\n return () => {\n if (removed) return;\n removed = true;\n const i = opHandlers.indexOf(handler);\n if (i !== -1) opHandlers.splice(i, 1);\n };\n },\n onPresence(handler) {\n presenceHandlers.push(handler);\n return () => {\n const i = presenceHandlers.indexOf(handler);\n if (i !== -1) presenceHandlers.splice(i, 1);\n };\n },\n sendPresence(data) {\n ws?.send(JSON.stringify({ type: 'presence', room: options.room, data }));\n },\n connect() {\n ws = new WebSocket(options.url, options.protocols);\n ws.onmessage = (e) => {\n try {\n const msg = JSON.parse(e.data);\n if (msg.type === 'op') {\n for (const h of opHandlers) h(msg);\n } else if (msg.type === 'presence') {\n for (const h of presenceHandlers) h(msg.peerId, msg.data);\n }\n } catch { /* ignore parse errors */ }\n };\n ws.onopen = () => {\n ws?.send(JSON.stringify({ type: 'join', room: options.room }));\n };\n },\n disconnect() {\n ws?.close();\n ws = null;\n },\n };\n}\n\n// =========================================================================\n// In-memory transport (for testing / single-tab)\n// =========================================================================\n\nexport function createLocalTransport(): SyncTransport {\n const opHandlers: Array<(op: SyncOp) => void> = [];\n return {\n send(op) {\n for (const h of opHandlers) h(op);\n },\n onReceive(handler) {\n opHandlers.push(handler);\n let removed = false;\n return () => {\n if (removed) return;\n removed = true;\n const i = opHandlers.indexOf(handler);\n if (i !== -1) opHandlers.splice(i, 1);\n };\n },\n connect() {},\n disconnect() {},\n };\n}\n\n// =========================================================================\n// createSync — the main API\n// =========================================================================\n\nexport interface SyncOptions {\n /** Transport for sending/receiving operations */\n transport?: SyncTransport;\n /** Unique peer ID (default: random) */\n peerId?: string;\n}\n\nexport interface SyncDoc<T extends Record<string, unknown>> {\n /** Reactive synced state — each key is a Signal */\n state: { [K in keyof T]: Signal<T[K]> };\n /** Connected peers (reactive) */\n peers: ReadonlySignal<PeerInfo[]>;\n /** Local presence data */\n presence: Signal<Record<string, unknown>>;\n /** Peer presence map (reactive) */\n peerPresence: ReadonlySignal<Map<string, unknown>>;\n /** This peer's ID */\n peerId: string;\n /** Whether connected */\n connected: ReadonlySignal<boolean>;\n /** Connect to the sync channel */\n connect(): void;\n /** Disconnect */\n disconnect(): void;\n /** Dispose the sync doc */\n dispose(): void;\n}\n\nexport interface PeerInfo {\n id: string;\n joinedAt: number;\n}\n\nlet peerIdCounter = 0;\n\n/**\n * Create a collaborative synced document.\n *\n * ```ts\n * const doc = createSync('room-1', { title: '', count: 0 }, {\n * transport: createWebSocketTransport({ url: 'wss://sync.example.com', room: 'room-1' }),\n * });\n *\n * doc.state.title.set('Hello'); // auto-syncs to all peers\n * doc.peers(); // connected users\n * ```\n */\nexport function createSync<T extends Record<string, unknown>>(\n roomId: string,\n initialState: T,\n options: SyncOptions = {},\n): SyncDoc<T> {\n const peerId = options.peerId ?? `peer-${++peerIdCounter}-${Date.now()}`;\n const transport = options.transport ?? createLocalTransport();\n\n // Create CRDT registers and signals for each state key\n const registers = new Map<string, LWWRegister<unknown>>();\n const stateSignals: Record<string, Signal<unknown>> = {};\n\n for (const [key, value] of Object.entries(initialState)) {\n registers.set(key, new LWWRegister(value, peerId));\n stateSignals[key] = signal(value);\n }\n\n // Intercept signal.set to broadcast operations\n const state = {} as { [K in keyof T]: Signal<T[K]> };\n for (const key of Object.keys(initialState)) {\n const original = stateSignals[key];\n const register = registers.get(key)!;\n\n const proxy: Signal<any> = (() => original()) as any;\n proxy.set = (value: any) => {\n register.set(value, peerId);\n original.set(value);\n transport.send({\n type: 'set',\n key,\n value,\n timestamp: register.timestamp,\n peerId,\n });\n };\n proxy.update = (fn: (prev: any) => any) => {\n proxy.set(fn(original()));\n };\n proxy.peek = () => original.peek();\n\n (state as any)[key] = proxy;\n }\n\n // Peers\n const peers = signal<PeerInfo[]>([]);\n const connected = signal(false);\n const presence = signal<Record<string, unknown>>({});\n const peerPresenceMap = signal(new Map<string, unknown>());\n\n // Listen for remote operations\n const unsubOps = transport.onReceive((op) => {\n if (op.type === 'set' && registers.has(op.key)) {\n const register = registers.get(op.key)!;\n const merged = register.merge({\n value: op.value,\n timestamp: op.timestamp,\n peerId: op.peerId,\n });\n if (merged) {\n stateSignals[op.key].set(op.value);\n }\n }\n });\n\n // Listen for presence\n const unsubPresence = transport.onPresence?.((remotePeerId, data) => {\n peerPresenceMap.update((map) => {\n const next = new Map(map);\n next.set(remotePeerId, data);\n return next;\n });\n });\n\n return {\n state,\n peers: () => peers(),\n presence,\n peerPresence: () => peerPresenceMap(),\n peerId,\n connected: () => connected(),\n connect() {\n transport.connect();\n connected.set(true);\n },\n disconnect() {\n transport.disconnect();\n connected.set(false);\n },\n dispose() {\n unsubOps();\n unsubPresence?.();\n transport.disconnect();\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/sync.ts"],"names":["LWWRegister","initialValue","peerId","value","ts","remote","createWebSocketTransport","options","ws","opHandlers","presenceHandlers","op","handler","removed","i","data","e","msg","h","createLocalTransport","peerIdCounter","createSync","roomId","initialState","transport","registers","stateSignals","key","signal","state","original","register","proxy","fn","peers","connected","presence","peerPresenceMap","unsubOps","unsubPresence","remotePeerId","map","next"],"mappings":"oCAqCO,IAAMA,EAAN,KAAqB,CAClB,KAAA,CAER,WAAA,CAAYC,EAAiBC,CAAAA,CAAgB,CAC3C,IAAA,CAAK,KAAA,CAAQ,CAAE,KAAA,CAAOD,CAAAA,CAAc,SAAA,CAAW,IAAA,CAAK,KAAI,CAAG,MAAA,CAAAC,CAAO,EACpE,CAEA,IAAI,KAAA,EAAW,CACb,OAAO,KAAK,KAAA,CAAM,KACpB,CAEA,IAAI,WAAoB,CACtB,OAAO,IAAA,CAAK,KAAA,CAAM,SACpB,CAEA,GAAA,CAAIC,CAAAA,CAAUD,CAAAA,CAAyB,CACrC,IAAME,CAAAA,CAAK,IAAA,CAAK,GAAA,GAGhB,OACEF,CAAAA,GAAW,IAAA,CAAK,KAAA,CAAM,QACtBE,CAAAA,CAAK,IAAA,CAAK,KAAA,CAAM,SAAA,EACfA,IAAO,IAAA,CAAK,KAAA,CAAM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CAAAA,CAAG,KAAK,EAGvC,CAAC,CAAA,CAGK4B,CAAAA,CAAgBf,EAAU,UAAA,GAAa,CAACgB,CAAAA,CAAczB,CAAAA,GAAS,CACnEsB,CAAAA,CAAgB,MAAA,CAAQI,CAAAA,EAAQ,CAC9B,IAAMC,CAAAA,CAAO,IAAI,GAAA,CAAID,CAAG,EACxB,OAAAC,CAAAA,CAAK,GAAA,CAAIF,CAAAA,CAAczB,CAAI,CAAA,CACpB2B,CACT,CAAC,EACH,CAAC,CAAA,CAED,OAAO,CACL,KAAA,CAAAb,IACA,KAAA,CAAO,IAAMK,CAAAA,EAAM,CACnB,SAAAE,CAAAA,CACA,YAAA,CAAc,IAAMC,CAAAA,GACpB,MAAA,CAAAnC,CAAAA,CACA,SAAA,CAAW,IAAMiC,GAAU,CAC3B,OAAA,EAAU,CACRX,CAAAA,CAAU,SAAQ,CAClBW,CAAAA,CAAU,GAAA,CAAI,IAAI,EACpB,CAAA,CACA,UAAA,EAAa,CACXX,CAAAA,CAAU,YAAW,CACrBW,CAAAA,CAAU,GAAA,CAAI,KAAK,EACrB,CAAA,CACA,OAAA,EAAU,CACRG,CAAAA,GACAC,CAAAA,IAAgB,CAChBf,EAAU,UAAA,GACZ,CACF,CACF","file":"chunk-CEJF44LZ.js","sourcesContent":["/**\n * Collaborative signals with CRDT.\n *\n * Make any signal multiplayer with one line. Multiple users can\n * edit the same state simultaneously with automatic conflict\n * resolution via Last-Writer-Wins Register and Operation-based CRDTs.\n *\n * ```ts\n * const doc = createSync('doc-123', {\n * title: '',\n * blocks: [],\n * cursor: { x: 0, y: 0 },\n * });\n *\n * doc.state.title.set('Hello'); // syncs to all peers\n * doc.peers(); // list of connected users\n * doc.presence.set({ cursor: { x: 10, y: 20 } });\n * ```\n */\n\nimport { signal, computed } from './signals.js';\nimport type { Signal, ReadonlySignal } from './signals.js';\n\n// =========================================================================\n// CRDT — Last-Writer-Wins Register\n// =========================================================================\n\nexport interface LWWEntry<T> {\n value: T;\n timestamp: number;\n peerId: string;\n}\n\n/**\n * Last-Writer-Wins Register — simplest CRDT for single values.\n * The write with the highest timestamp wins on conflict.\n */\nexport class LWWRegister<T> {\n private entry: LWWEntry<T>;\n\n constructor(initialValue: T, peerId: string) {\n this.entry = { value: initialValue, timestamp: Date.now(), peerId };\n }\n\n get value(): T {\n return this.entry.value;\n }\n\n get timestamp(): number {\n return this.entry.timestamp;\n }\n\n set(value: T, peerId: string): boolean {\n const ts = Date.now();\n // Local writes always succeed (same peer always advances its own state).\n // Cross-peer conflicts resolve by highest timestamp, then peerId tiebreak.\n if (\n peerId === this.entry.peerId ||\n ts > this.entry.timestamp ||\n (ts === this.entry.timestamp && peerId > this.entry.peerId)\n ) {\n this.entry = { value, timestamp: Math.max(ts, this.entry.timestamp + 1), peerId };\n return true;\n }\n return false;\n }\n\n merge(remote: LWWEntry<T>): boolean {\n if (\n remote.timestamp > this.entry.timestamp ||\n (remote.timestamp === this.entry.timestamp && remote.peerId > this.entry.peerId)\n ) {\n this.entry = remote;\n return true;\n }\n return false;\n }\n\n toEntry(): LWWEntry<T> {\n return { ...this.entry };\n }\n}\n\n// =========================================================================\n// Operation log for list CRDTs\n// =========================================================================\n\nexport type SyncOp =\n | { type: 'set'; key: string; value: unknown; timestamp: number; peerId: string }\n | { type: 'insert'; key: string; index: number; value: unknown; timestamp: number; peerId: string }\n | { type: 'delete'; key: string; index: number; timestamp: number; peerId: string };\n\n// =========================================================================\n// Sync transport interface\n// =========================================================================\n\nexport interface SyncTransport {\n /** Send an operation to peers */\n send(op: SyncOp): void;\n /** Listen for operations from peers */\n onReceive(handler: (op: SyncOp) => void): () => void;\n /** Listen for peer presence updates */\n onPresence?(handler: (peerId: string, data: unknown) => void): () => void;\n /** Send presence data */\n sendPresence?(data: unknown): void;\n /** Connect to the sync channel */\n connect(): void;\n /** Disconnect */\n disconnect(): void;\n}\n\n// =========================================================================\n// WebSocket transport\n// =========================================================================\n\nexport interface WebSocketTransportOptions {\n url: string;\n room: string;\n protocols?: string | string[];\n}\n\nexport function createWebSocketTransport(options: WebSocketTransportOptions): SyncTransport {\n let ws: WebSocket | null = null;\n const opHandlers: Array<(op: SyncOp) => void> = [];\n const presenceHandlers: Array<(peerId: string, data: unknown) => void> = [];\n\n return {\n send(op: SyncOp) {\n ws?.send(JSON.stringify({ type: 'op', room: options.room, ...op }));\n },\n onReceive(handler) {\n opHandlers.push(handler);\n let removed = false;\n return () => {\n if (removed) return;\n removed = true;\n const i = opHandlers.indexOf(handler);\n if (i !== -1) opHandlers.splice(i, 1);\n };\n },\n onPresence(handler) {\n presenceHandlers.push(handler);\n return () => {\n const i = presenceHandlers.indexOf(handler);\n if (i !== -1) presenceHandlers.splice(i, 1);\n };\n },\n sendPresence(data) {\n ws?.send(JSON.stringify({ type: 'presence', room: options.room, data }));\n },\n connect() {\n ws = new WebSocket(options.url, options.protocols);\n ws.onmessage = (e) => {\n try {\n const msg = JSON.parse(e.data);\n if (msg.type === 'op') {\n for (const h of opHandlers) h(msg);\n } else if (msg.type === 'presence') {\n for (const h of presenceHandlers) h(msg.peerId, msg.data);\n }\n } catch { /* ignore parse errors */ }\n };\n ws.onopen = () => {\n ws?.send(JSON.stringify({ type: 'join', room: options.room }));\n };\n },\n disconnect() {\n ws?.close();\n ws = null;\n },\n };\n}\n\n// =========================================================================\n// In-memory transport (for testing / single-tab)\n// =========================================================================\n\nexport function createLocalTransport(): SyncTransport {\n const opHandlers: Array<(op: SyncOp) => void> = [];\n return {\n send(op) {\n for (const h of opHandlers) h(op);\n },\n onReceive(handler) {\n opHandlers.push(handler);\n let removed = false;\n return () => {\n if (removed) return;\n removed = true;\n const i = opHandlers.indexOf(handler);\n if (i !== -1) opHandlers.splice(i, 1);\n };\n },\n connect() {},\n disconnect() {},\n };\n}\n\n// =========================================================================\n// createSync — the main API\n// =========================================================================\n\nexport interface SyncOptions {\n /** Transport for sending/receiving operations */\n transport?: SyncTransport;\n /** Unique peer ID (default: random) */\n peerId?: string;\n}\n\nexport interface SyncDoc<T extends Record<string, unknown>> {\n /** Reactive synced state — each key is a Signal */\n state: { [K in keyof T]: Signal<T[K]> };\n /** Connected peers (reactive) */\n peers: ReadonlySignal<PeerInfo[]>;\n /** Local presence data */\n presence: Signal<Record<string, unknown>>;\n /** Peer presence map (reactive) */\n peerPresence: ReadonlySignal<Map<string, unknown>>;\n /** This peer's ID */\n peerId: string;\n /** Whether connected */\n connected: ReadonlySignal<boolean>;\n /** Connect to the sync channel */\n connect(): void;\n /** Disconnect */\n disconnect(): void;\n /** Dispose the sync doc */\n dispose(): void;\n}\n\nexport interface PeerInfo {\n id: string;\n joinedAt: number;\n}\n\nlet peerIdCounter = 0;\n\n/**\n * Create a collaborative synced document.\n *\n * ```ts\n * const doc = createSync('room-1', { title: '', count: 0 }, {\n * transport: createWebSocketTransport({ url: 'wss://sync.example.com', room: 'room-1' }),\n * });\n *\n * doc.state.title.set('Hello'); // auto-syncs to all peers\n * doc.peers(); // connected users\n * ```\n */\nexport function createSync<T extends Record<string, unknown>>(\n roomId: string,\n initialState: T,\n options: SyncOptions = {},\n): SyncDoc<T> {\n const peerId = options.peerId ?? `peer-${++peerIdCounter}-${Date.now()}`;\n const transport = options.transport ?? createLocalTransport();\n\n // Create CRDT registers and signals for each state key\n const registers = new Map<string, LWWRegister<unknown>>();\n const stateSignals: Record<string, Signal<unknown>> = {};\n\n for (const [key, value] of Object.entries(initialState)) {\n registers.set(key, new LWWRegister(value, peerId));\n stateSignals[key] = signal(value);\n }\n\n // Intercept signal.set to broadcast operations\n const state = {} as { [K in keyof T]: Signal<T[K]> };\n for (const key of Object.keys(initialState)) {\n const original = stateSignals[key];\n const register = registers.get(key)!;\n\n const proxy: Signal<any> = (() => original()) as any;\n proxy.set = (value: any) => {\n register.set(value, peerId);\n original.set(value);\n transport.send({\n type: 'set',\n key,\n value,\n timestamp: register.timestamp,\n peerId,\n });\n };\n proxy.update = (fn: (prev: any) => any) => {\n proxy.set(fn(original()));\n };\n proxy.peek = () => original.peek();\n\n (state as any)[key] = proxy;\n }\n\n // Peers\n const peers = signal<PeerInfo[]>([]);\n const connected = signal(false);\n const presence = signal<Record<string, unknown>>({});\n const peerPresenceMap = signal(new Map<string, unknown>());\n\n // Listen for remote operations\n const unsubOps = transport.onReceive((op) => {\n if (op.type === 'set' && registers.has(op.key)) {\n const register = registers.get(op.key)!;\n const merged = register.merge({\n value: op.value,\n timestamp: op.timestamp,\n peerId: op.peerId,\n });\n if (merged) {\n stateSignals[op.key].set(op.value);\n }\n }\n });\n\n // Listen for presence\n const unsubPresence = transport.onPresence?.((remotePeerId, data) => {\n peerPresenceMap.update((map) => {\n const next = new Map(map);\n next.set(remotePeerId, data);\n return next;\n });\n });\n\n return {\n state,\n peers: () => peers(),\n presence,\n peerPresence: () => peerPresenceMap(),\n peerId,\n connected: () => connected(),\n connect() {\n transport.connect();\n connected.set(true);\n },\n disconnect() {\n transport.disconnect();\n connected.set(false);\n },\n dispose() {\n unsubOps();\n unsubPresence?.();\n transport.disconnect();\n },\n };\n}\n"]}