@akashjs/runtime 0.1.28 → 0.1.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-TYDY46CL.js → chunk-367DJVST.js} +3 -3
- package/dist/{chunk-TYDY46CL.js.map → chunk-367DJVST.js.map} +1 -1
- package/dist/chunk-5NJYYK3Q.js +2 -0
- package/dist/{chunk-WEPYZZSS.js.map → chunk-5NJYYK3Q.js.map} +1 -1
- package/dist/{chunk-JMPZTCEE.js → chunk-CEJF44LZ.js} +2 -2
- package/dist/{chunk-JMPZTCEE.js.map → chunk-CEJF44LZ.js.map} +1 -1
- package/dist/chunk-DZGRBVSY.js +2 -0
- package/dist/chunk-DZGRBVSY.js.map +1 -0
- package/dist/{chunk-NIA62JQ5.cjs → chunk-JSBB2VV3.cjs} +2 -2
- package/dist/{chunk-NIA62JQ5.cjs.map → chunk-JSBB2VV3.cjs.map} +1 -1
- package/dist/{chunk-QEA2QRNB.cjs → chunk-OCBLY4E4.cjs} +2 -2
- package/dist/chunk-OCBLY4E4.cjs.map +1 -0
- package/dist/chunk-RTJ6UDGV.cjs +13 -0
- package/dist/chunk-RTJ6UDGV.cjs.map +1 -0
- package/dist/{chunk-Y6NQXWYS.cjs → chunk-TBCX5WQQ.cjs} +3 -3
- package/dist/{chunk-Y6NQXWYS.cjs.map → chunk-TBCX5WQQ.cjs.map} +1 -1
- package/dist/{chunk-NEVUOTBQ.js → chunk-TS5UKZTG.js} +2 -2
- package/dist/{chunk-NEVUOTBQ.js.map → chunk-TS5UKZTG.js.map} +1 -1
- package/dist/chunk-TWA4T6PX.js +13 -0
- package/dist/chunk-TWA4T6PX.js.map +1 -0
- package/dist/{chunk-H4LBIF5X.cjs → chunk-VBAO65QP.cjs} +2 -2
- package/dist/{chunk-H4LBIF5X.cjs.map → chunk-VBAO65QP.cjs.map} +1 -1
- package/dist/{chunk-6ZQNSNL4.js → chunk-WG5GKD3B.js} +3 -3
- package/dist/{chunk-6ZQNSNL4.js.map → chunk-WG5GKD3B.js.map} +1 -1
- package/dist/{chunk-XLHWCP6E.cjs → chunk-YIVBLM2A.cjs} +3 -3
- package/dist/{chunk-XLHWCP6E.cjs.map → chunk-YIVBLM2A.cjs.map} +1 -1
- package/dist/{chunk-VBLTST4K.cjs → chunk-YN2TQLVA.cjs} +2 -2
- package/dist/{chunk-VBLTST4K.cjs.map → chunk-YN2TQLVA.cjs.map} +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/index.cjs +10 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +10 -21
- package/dist/index.js.map +1 -1
- package/dist/machine.cjs +1 -1
- package/dist/machine.js +1 -1
- package/dist/offline.cjs +1 -1
- package/dist/offline.js +1 -1
- package/dist/pwa.cjs +1 -1
- package/dist/pwa.js +1 -1
- package/dist/ssr.cjs +1 -1
- package/dist/ssr.js +1 -1
- package/dist/store.cjs +1 -1
- package/dist/store.js +1 -1
- package/dist/sync.cjs +1 -1
- package/dist/sync.js +1 -1
- package/dist/test.cjs +1 -1
- package/dist/test.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-JBHFILMZ.js +0 -2
- package/dist/chunk-JBHFILMZ.js.map +0 -1
- package/dist/chunk-L4DNCDUA.cjs +0 -2
- package/dist/chunk-L4DNCDUA.cjs.map +0 -1
- package/dist/chunk-LR2QY7QP.js +0 -2
- package/dist/chunk-LR2QY7QP.js.map +0 -1
- package/dist/chunk-QEA2QRNB.cjs.map +0 -1
- package/dist/chunk-WEPYZZSS.js +0 -2
package/dist/machine.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkVBAO65QP_cjs=require('./chunk-VBAO65QP.cjs');require('./chunk-RTJ6UDGV.cjs');Object.defineProperty(exports,"createMachine",{enumerable:true,get:function(){return chunkVBAO65QP_cjs.a}});//# sourceMappingURL=machine.cjs.map
|
|
2
2
|
//# sourceMappingURL=machine.cjs.map
|
package/dist/machine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as createMachine}from'./chunk-
|
|
1
|
+
export{a as createMachine}from'./chunk-TS5UKZTG.js';import'./chunk-TWA4T6PX.js';//# sourceMappingURL=machine.js.map
|
|
2
2
|
//# sourceMappingURL=machine.js.map
|
package/dist/offline.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkJSBB2VV3_cjs=require('./chunk-JSBB2VV3.cjs');require('./chunk-RTJ6UDGV.cjs');Object.defineProperty(exports,"createOfflineStore",{enumerable:true,get:function(){return chunkJSBB2VV3_cjs.a}});//# sourceMappingURL=offline.cjs.map
|
|
2
2
|
//# sourceMappingURL=offline.cjs.map
|
package/dist/offline.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as createOfflineStore}from'./chunk-
|
|
1
|
+
export{a as createOfflineStore}from'./chunk-5NJYYK3Q.js';import'./chunk-TWA4T6PX.js';//# sourceMappingURL=offline.js.map
|
|
2
2
|
//# sourceMappingURL=offline.js.map
|
package/dist/pwa.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkTBCX5WQQ_cjs=require('./chunk-TBCX5WQQ.cjs');require('./chunk-RTJ6UDGV.cjs');Object.defineProperty(exports,"generateSWScript",{enumerable:true,get:function(){return chunkTBCX5WQQ_cjs.b}});Object.defineProperty(exports,"registerServiceWorker",{enumerable:true,get:function(){return chunkTBCX5WQQ_cjs.a}});Object.defineProperty(exports,"subscribePush",{enumerable:true,get:function(){return chunkTBCX5WQQ_cjs.c}});//# sourceMappingURL=pwa.cjs.map
|
|
2
2
|
//# sourceMappingURL=pwa.cjs.map
|
package/dist/pwa.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as generateSWScript,a as registerServiceWorker,c as subscribePush}from'./chunk-
|
|
1
|
+
export{b as generateSWScript,a as registerServiceWorker,c as subscribePush}from'./chunk-WG5GKD3B.js';import'./chunk-TWA4T6PX.js';//# sourceMappingURL=pwa.js.map
|
|
2
2
|
//# sourceMappingURL=pwa.js.map
|
package/dist/ssr.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunk2X7GUBTG_cjs=require('./chunk-2X7GUBTG.cjs');require('./chunk-
|
|
1
|
+
'use strict';var chunk2X7GUBTG_cjs=require('./chunk-2X7GUBTG.cjs');require('./chunk-RTJ6UDGV.cjs');Object.defineProperty(exports,"escapeHtml",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.a}});Object.defineProperty(exports,"isServerRendering",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.b}});Object.defineProperty(exports,"nodeToHtml",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.i}});Object.defineProperty(exports,"renderNodes",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.j}});Object.defineProperty(exports,"renderToStream",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.e}});Object.defineProperty(exports,"renderToString",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.c}});Object.defineProperty(exports,"renderToStringSync",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.d}});Object.defineProperty(exports,"ssrElement",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.f}});Object.defineProperty(exports,"ssrRaw",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.h}});Object.defineProperty(exports,"ssrText",{enumerable:true,get:function(){return chunk2X7GUBTG_cjs.g}});//# sourceMappingURL=ssr.cjs.map
|
|
2
2
|
//# sourceMappingURL=ssr.cjs.map
|
package/dist/ssr.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as escapeHtml,b as isServerRendering,i as nodeToHtml,j as renderNodes,e as renderToStream,c as renderToString,d as renderToStringSync,f as ssrElement,h as ssrRaw,g as ssrText}from'./chunk-3HWR5MIF.js';import'./chunk-
|
|
1
|
+
export{a as escapeHtml,b as isServerRendering,i as nodeToHtml,j as renderNodes,e as renderToStream,c as renderToString,d as renderToStringSync,f as ssrElement,h as ssrRaw,g as ssrText}from'./chunk-3HWR5MIF.js';import'./chunk-TWA4T6PX.js';//# sourceMappingURL=ssr.js.map
|
|
2
2
|
//# sourceMappingURL=ssr.js.map
|
package/dist/store.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkOCBLY4E4_cjs=require('./chunk-OCBLY4E4.cjs');require('./chunk-RTJ6UDGV.cjs');Object.defineProperty(exports,"__getStoreInstances",{enumerable:true,get:function(){return chunkOCBLY4E4_cjs.d}});Object.defineProperty(exports,"clearStores",{enumerable:true,get:function(){return chunkOCBLY4E4_cjs.c}});Object.defineProperty(exports,"configureStores",{enumerable:true,get:function(){return chunkOCBLY4E4_cjs.a}});Object.defineProperty(exports,"defineStore",{enumerable:true,get:function(){return chunkOCBLY4E4_cjs.b}});//# sourceMappingURL=store.cjs.map
|
|
2
2
|
//# sourceMappingURL=store.cjs.map
|
package/dist/store.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{d as __getStoreInstances,c as clearStores,a as configureStores,b as defineStore}from'./chunk-
|
|
1
|
+
export{d as __getStoreInstances,c as clearStores,a as configureStores,b as defineStore}from'./chunk-DZGRBVSY.js';import'./chunk-TWA4T6PX.js';//# sourceMappingURL=store.js.map
|
|
2
2
|
//# sourceMappingURL=store.js.map
|
package/dist/sync.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkYN2TQLVA_cjs=require('./chunk-YN2TQLVA.cjs');require('./chunk-RTJ6UDGV.cjs');Object.defineProperty(exports,"LWWRegister",{enumerable:true,get:function(){return chunkYN2TQLVA_cjs.a}});Object.defineProperty(exports,"createLocalTransport",{enumerable:true,get:function(){return chunkYN2TQLVA_cjs.c}});Object.defineProperty(exports,"createSync",{enumerable:true,get:function(){return chunkYN2TQLVA_cjs.d}});Object.defineProperty(exports,"createWebSocketTransport",{enumerable:true,get:function(){return chunkYN2TQLVA_cjs.b}});//# sourceMappingURL=sync.cjs.map
|
|
2
2
|
//# sourceMappingURL=sync.cjs.map
|
package/dist/sync.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as LWWRegister,c as createLocalTransport,d as createSync,b as createWebSocketTransport}from'./chunk-
|
|
1
|
+
export{a as LWWRegister,c as createLocalTransport,d as createSync,b as createWebSocketTransport}from'./chunk-CEJF44LZ.js';import'./chunk-TWA4T6PX.js';//# sourceMappingURL=sync.js.map
|
|
2
2
|
//# sourceMappingURL=sync.js.map
|
package/dist/test.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkYIVBLM2A_cjs=require('./chunk-YIVBLM2A.cjs');require('./chunk-RTJ6UDGV.cjs');function M(e,n){let t=document.createElement("div");t.setAttribute("data-akash-test-root","");let l=n?.props??{},o=n?.provide,a;return o&&o.size>0?a=chunkYIVBLM2A_cjs.B(()=>{for(let[i,d]of o)chunkYIVBLM2A_cjs.h(i,d);return ()=>e(l)})({}):a=e(l),t.appendChild(a),document.body.appendChild(t),{container:t,unmount(){t.remove();},getByText(r){let i=m(t,r);if(!i)throw new Error(`[AkashJS Test] Could not find element with text: "${r}"
|
|
2
2
|
Container HTML: ${t.innerHTML.slice(0,200)}`);return i},getByRole(r){let i=t.querySelector(`[role="${r}"]`)??p(t,r);if(!i)throw new Error(`[AkashJS Test] Could not find element with role: "${r}"
|
|
3
3
|
Container HTML: ${t.innerHTML.slice(0,200)}`);return i},getByTestId(r){let i=t.querySelector(`[data-testid="${r}"]`);if(!i)throw new Error(`[AkashJS Test] Could not find element with data-testid: "${r}"
|
|
4
4
|
Container HTML: ${t.innerHTML.slice(0,200)}`);return i},queryAll(r){return Array.from(t.querySelectorAll(r))},query(r){return t.querySelector(r)}}}var y={async click(e){e.dispatchEvent(new MouseEvent("click",{bubbles:true,cancelable:true})),await s();},async input(e,n){let t=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;t?t.call(e,n):e.value=n,e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true})),await s();},async submit(e){e.dispatchEvent(new Event("submit",{bubbles:true,cancelable:true})),await s();},async focus(e){e.focus(),e.dispatchEvent(new FocusEvent("focus",{bubbles:true})),await s();},async blur(e){e.blur(),e.dispatchEvent(new FocusEvent("blur",{bubbles:true})),await s();},async keyDown(e,n,t){e.dispatchEvent(new KeyboardEvent("keydown",{key:n,bubbles:true,...t})),await s();},async keyUp(e,n,t){e.dispatchEvent(new KeyboardEvent("keyup",{key:n,bubbles:true,...t})),await s();}};function s(){return new Promise(e=>queueMicrotask(e))}function m(e,n){let t=null,l=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT),o=l.nextNode();for(;o;)o instanceof HTMLElement&&o.textContent?.includes(n)&&(t=o),o=l.nextNode();return !t&&e.textContent?.includes(n)&&(t=e),t}var E={button:["button"],a:["link"],input:["textbox","checkbox","radio","spinbutton","slider"],select:["combobox","listbox"],textarea:["textbox"],img:["img"],form:["form"],nav:["navigation"],main:["main"],header:["banner"],footer:["contentinfo"],aside:["complementary"],section:["region"],article:["article"],ul:["list"],ol:["list"],li:["listitem"],table:["table"],th:["columnheader"],td:["cell"],h1:["heading"],h2:["heading"],h3:["heading"],h4:["heading"],h5:["heading"],h6:["heading"]};function p(e,n){let t=[];for(let[o,a]of Object.entries(E))a.includes(n)&&t.push(o);if(t.length===0)return null;let l=t.join(", ");return e.querySelector(l)}exports.fireEvent=y;exports.mount=M;//# sourceMappingURL=test.cjs.map
|
package/dist/test.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {B,h}from'./chunk-
|
|
1
|
+
import {B,h}from'./chunk-367DJVST.js';import'./chunk-TWA4T6PX.js';function M(e,n){let t=document.createElement("div");t.setAttribute("data-akash-test-root","");let l=n?.props??{},o=n?.provide,a;return o&&o.size>0?a=B(()=>{for(let[i,d]of o)h(i,d);return ()=>e(l)})({}):a=e(l),t.appendChild(a),document.body.appendChild(t),{container:t,unmount(){t.remove();},getByText(r){let i=m(t,r);if(!i)throw new Error(`[AkashJS Test] Could not find element with text: "${r}"
|
|
2
2
|
Container HTML: ${t.innerHTML.slice(0,200)}`);return i},getByRole(r){let i=t.querySelector(`[role="${r}"]`)??p(t,r);if(!i)throw new Error(`[AkashJS Test] Could not find element with role: "${r}"
|
|
3
3
|
Container HTML: ${t.innerHTML.slice(0,200)}`);return i},getByTestId(r){let i=t.querySelector(`[data-testid="${r}"]`);if(!i)throw new Error(`[AkashJS Test] Could not find element with data-testid: "${r}"
|
|
4
4
|
Container HTML: ${t.innerHTML.slice(0,200)}`);return i},queryAll(r){return Array.from(t.querySelectorAll(r))},query(r){return t.querySelector(r)}}}var y={async click(e){e.dispatchEvent(new MouseEvent("click",{bubbles:true,cancelable:true})),await s();},async input(e,n){let t=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;t?t.call(e,n):e.value=n,e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true})),await s();},async submit(e){e.dispatchEvent(new Event("submit",{bubbles:true,cancelable:true})),await s();},async focus(e){e.focus(),e.dispatchEvent(new FocusEvent("focus",{bubbles:true})),await s();},async blur(e){e.blur(),e.dispatchEvent(new FocusEvent("blur",{bubbles:true})),await s();},async keyDown(e,n,t){e.dispatchEvent(new KeyboardEvent("keydown",{key:n,bubbles:true,...t})),await s();},async keyUp(e,n,t){e.dispatchEvent(new KeyboardEvent("keyup",{key:n,bubbles:true,...t})),await s();}};function s(){return new Promise(e=>queueMicrotask(e))}function m(e,n){let t=null,l=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT),o=l.nextNode();for(;o;)o instanceof HTMLElement&&o.textContent?.includes(n)&&(t=o),o=l.nextNode();return !t&&e.textContent?.includes(n)&&(t=e),t}var E={button:["button"],a:["link"],input:["textbox","checkbox","radio","spinbutton","slider"],select:["combobox","listbox"],textarea:["textbox"],img:["img"],form:["form"],nav:["navigation"],main:["main"],header:["banner"],footer:["contentinfo"],aside:["complementary"],section:["region"],article:["article"],ul:["list"],ol:["list"],li:["listitem"],table:["table"],th:["columnheader"],td:["cell"],h1:["heading"],h2:["heading"],h3:["heading"],h4:["heading"],h5:["heading"],h6:["heading"]};function p(e,n){let t=[];for(let[o,a]of Object.entries(E))a.includes(n)&&t.push(o);if(t.length===0)return null;let l=t.join(", ");return e.querySelector(l)}export{y as fireEvent,M as mount};//# sourceMappingURL=test.js.map
|
package/package.json
CHANGED
package/dist/chunk-JBHFILMZ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var c=new Set,i=new Set,d=false,a=0,S=3,h=100;function l(){if(d)return;d=true;let e=new Map,r=false,n=0;for(;(c.size>0||i.size>0)&&n<h;){if(n++,c.size>0){let t=[...c].sort(w);c.clear();for(let o of t){let u=(e.get(o)??0)+1;if(e.set(o,u),u>S){r=true;continue}o.run();}}if(i.size>0){let t=[...i].sort(w);i.clear();for(let o of t){let u=(e.get(o)??0)+1;if(e.set(o,u),u>S){r=true;continue}o.run();}}if(r&&c.size===0&&i.size===0)break}(r||n>=h)&&(c.clear(),i.clear(),console.error("[AkashJS] Circular dependency detected between effects. Two or more effects are writing to each other's dependencies. The cycle has been broken after "+n+" iterations.")),d=false;}function y(e){e.isRender?c.add(e):i.add(e),a===0&&!d&&l();}function g(e){a++;try{e();}finally{a--,a===0&&l();}}function k(){a++;}function m(){a--,a===0&&l();}function w(e,r){return (e.depth??0)-(r.depth??0)}function D(){l();}var q=typeof process>"u"||process.env?.NODE_ENV!=="production";var s=null;function V(e,r){let n={value:e,subscribers:new Set,equals:r?.equals??Object.is},t=()=>(R(n),n.value);return t.set=o=>{q&&s&&s._tag==="computed"&&console.warn("[AkashJS] Writing to a signal inside computed() is not allowed. The write will be lost on the next evaluation."),!n.equals(n.value,o)&&(n.value=o,g(()=>{v(n);}));},t.update=o=>{t.set(o(n.value));},t.peek=()=>n.value,t}function B(e,r){let n={_tag:"computed",fn:e,value:void 0,state:1,subscribers:new Set,sources:new Set,equals:r?.equals??Object.is};return ()=>(s&&(n.subscribers.add(s),"sources"in s&&s.sources.add(n)),n.state!==0&&N(n),n.value)}var b=new Set;function N(e){if(b.has(e))throw new Error("[AkashJS] Circular dependency detected between computed values.");b.add(e),k();for(let n of e.sources)n.subscribers.delete(e);e.sources.clear();let r=s;s=e;try{let n=e.fn(),t=e.value===void 0||!e.equals(e.value,n);e.value=n,e.state=0,t&&v(e);}finally{b.delete(e),s=r,m();}}function F(e,r){let n={_tag:"effect",fn:e,cleanup:null,sources:new Set,disposed:false,isRender:r?.render??false,run(){E(n);}};return E(n),()=>{n.disposed=true,C(n);for(let t of n.sources)t.subscribers.delete(n);n.sources.clear();}}function E(e){if(e.disposed)return;if(e.sources.size>0){let t=false;for(let o of e.sources)if("_tag"in o&&o._tag==="computed"){if(o.state===1){let u=o.value;N(o),o.equals(u,o.value)||(t=true);}}else t=true;if(!t)return}C(e);let r=new Set(e.sources);for(let t of e.sources)t.subscribers.delete(e);e.sources.clear();let n=s;s=e;try{let t=e.fn();typeof t=="function"&&(e.cleanup=t);}catch(t){for(let o of r)o.subscribers.add(e),e.sources.add(o);console.error("[AkashJS] Error in effect (will retry on next signal change):",t);}finally{s=n;}}function C(e){if(e.cleanup){try{e.cleanup();}catch(r){console.error("[AkashJS] Error in effect cleanup (ignored):",r);}e.cleanup=null;}}function A(e){let r=s;s=null;try{return e()}finally{s=r;}}function K(e,r,n){let t=Array.isArray(e),o=t?e:[e],u,T=true;return ()=>{let f=o.map(x=>x());if(T&&(T=false,u=f.slice(),n?.defer!==false))return;let p=u;return u=f.slice(),A(()=>r(t?f:f[0],p?t?p:p[0]:void 0))}}function R(e){s&&(e.subscribers.add(s),"sources"in s&&s.sources.add(e));}function v(e){let r=[...e.subscribers];for(let n of r)n._tag==="computed"?(n.state=1,v(n)):n._tag==="effect"&&y(n);}export{g as a,D as b,V as c,B as d,F as e,A as f,K as g};//# sourceMappingURL=chunk-JBHFILMZ.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-JBHFILMZ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/scheduler.ts","../src/signals.ts"],"names":["pendingRender","pendingUser","flushing","batchDepth","MAX_EFFECT_RUNS","MAX_FLUSH_ITERATIONS","flush","runCounts","circularDetected","iterations","queue","byDepth","fx","count","scheduleEffect","batch","fn","enterBatch","exitBatch","a","b","flushSync","__DEV__","currentSubscriber","signal","initialValue","options","node","read","trackSubscriber","value","notifySubscribers","computed","recompute","computingSet","source","prevSubscriber","newValue","changed","effect","runEffect","cleanupEffect","anyChanged","oldValue","prevSources","result","err","untrack","prev","on","deps","isArray","depArray","prevValues","isFirst","values","d","subs","sub"],"mappings":"AAcA,IAAMA,CAAAA,CAAgB,IAAI,GAAA,CACpBC,CAAAA,CAAc,IAAI,GAAA,CACpBC,CAAAA,CAAW,MACXC,CAAAA,CAAa,CAAA,CAGXC,CAAAA,CAAkB,EAClBC,CAAAA,CAAuB,IAE7B,SAASC,CAAAA,EAAc,CACrB,GAAIJ,CAAAA,CAAU,OACdA,CAAAA,CAAW,IACM,CAGjB,IAAMK,CAAAA,CAAY,IAAI,IAClBC,CAAAA,CAAmB,KAAA,CAInBC,EAAa,CAAA,CACjB,KAAA,CAAQT,EAAc,IAAA,CAAO,CAAA,EAAKC,EAAY,IAAA,CAAO,CAAA,GAAMQ,EAAaJ,CAAAA,EAAsB,CAI5F,GAHAI,CAAAA,EAAAA,CAGIT,CAAAA,CAAc,IAAA,CAAO,EAAG,CAC1B,IAAMU,EAAQ,CAAC,GAAGV,CAAa,CAAA,CAAE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Microtask-based effect scheduler with priority levels and deduplication.\n *\n * Render effects (DOM bindings) run before user effects to ensure\n * DOM is consistent before user-side effects execute.\n */\n\nexport interface ScheduledEffect {\n run(): void;\n isRender: boolean;\n /** Depth in the dependency graph (0 = root). Lower depth runs first. */\n depth?: number;\n}\n\nconst pendingRender = new Set<ScheduledEffect>();\nconst pendingUser = new Set<ScheduledEffect>();\nlet flushing = false;\nlet batchDepth = 0;\nlet flushScheduled = false;\n\nconst MAX_EFFECT_RUNS = 3;\nconst MAX_FLUSH_ITERATIONS = 100;\n\nfunction flush(): void {\n if (flushing) return;\n flushing = true;\n flushScheduled = false;\n\n // Fresh per-effect run counter for THIS flush — reset every time\n const runCounts = new Map<ScheduledEffect, number>();\n let circularDetected = false;\n\n // Process render effects first, then user effects.\n // Effects may enqueue more effects during flush, so loop until empty.\n let iterations = 0;\n while ((pendingRender.size > 0 || pendingUser.size > 0) && iterations < MAX_FLUSH_ITERATIONS) {\n iterations++;\n\n // Drain render effects (sorted by depth — parents before children)\n if (pendingRender.size > 0) {\n const queue = [...pendingRender].sort(byDepth);\n pendingRender.clear();\n for (const fx of queue) {\n const count = (runCounts.get(fx) ?? 0) + 1;\n runCounts.set(fx, count);\n if (count > MAX_EFFECT_RUNS) {\n circularDetected = true;\n continue; // skip this effect — it's in a cycle\n }\n fx.run();\n }\n }\n\n // Drain user effects (sorted by depth)\n if (pendingUser.size > 0) {\n const queue = [...pendingUser].sort(byDepth);\n pendingUser.clear();\n for (const fx of queue) {\n const count = (runCounts.get(fx) ?? 0) + 1;\n runCounts.set(fx, count);\n if (count > MAX_EFFECT_RUNS) {\n circularDetected = true;\n continue; // skip this effect — it's in a cycle\n }\n fx.run();\n }\n }\n\n // If all remaining effects were skipped due to cycle detection, break\n if (circularDetected && pendingRender.size === 0 && pendingUser.size === 0) {\n break;\n }\n }\n\n if (circularDetected || iterations >= MAX_FLUSH_ITERATIONS) {\n pendingRender.clear();\n pendingUser.clear();\n console.error(\n '[AkashJS] Circular dependency detected between effects. ' +\n 'Two or more effects are writing to each other\\'s dependencies. ' +\n 'The cycle has been broken after ' + iterations + ' iterations.'\n );\n }\n\n flushing = false;\n}\n\nexport function scheduleEffect(fx: ScheduledEffect): void {\n if (fx.isRender) {\n pendingRender.add(fx);\n } else {\n pendingUser.add(fx);\n }\n\n if (batchDepth === 0 && !flushing) {\n flush();\n }\n}\n\n/**\n * Batch multiple signal writes — subscribers are notified only once\n * at the end of the batch.\n */\nexport function batch(fn: () => void): void {\n batchDepth++;\n try {\n fn();\n } finally {\n batchDepth--;\n if (batchDepth === 0) {\n flush();\n }\n }\n}\n\n/** Enter/exit batch depth — used by computed recompute to prevent mid-evaluation flush */\nexport function enterBatch(): void { batchDepth++; }\nexport function exitBatch(): void {\n batchDepth--;\n if (batchDepth === 0) flush();\n}\n\n/** Sort effects by depth (lower depth first = parents before children) */\nfunction byDepth(a: ScheduledEffect, b: ScheduledEffect): number {\n return (a.depth ?? 0) - (b.depth ?? 0);\n}\n\n/** Synchronously flush all pending effects. Useful for testing. */\nexport function flushSync(): void {\n flush();\n}\n","/**\n * Fine-grained reactivity system.\n *\n * Inspired by SolidJS/Preact Signals. Provides signal(), computed(),\n * effect(), and untrack() primitives with automatic dependency tracking\n * and glitch-free diamond dependency resolution.\n */\n\nimport { scheduleEffect, batch, enterBatch, exitBatch, type ScheduledEffect } from './scheduler.js';\n\nconst __DEV__ = typeof process === 'undefined' || process.env?.NODE_ENV !== 'production';\n\n/** Depth counter to defer effect scheduling until all notifications complete (glitch-free) */\nlet notifyDepth = 0;\n\n// --- Tracking scope ---\n\ntype Subscriber = EffectNode | ComputedNode<unknown>;\n\nlet currentSubscriber: Subscriber | null = null;\n\n// --- Signal ---\n\nexport interface Signal<T> {\n /** Read the current value (tracks dependency if inside a reactive scope) */\n (): T;\n /** Set a new value */\n set(value: T): void;\n /** Update the value using the previous value */\n update(fn: (prev: T) => T): void;\n /** Read without tracking (no dependency registered) */\n peek(): T;\n}\n\nexport type ReadonlySignal<T> = () => T;\n\ninterface SignalNode<T> {\n value: T;\n subscribers: Set<Subscriber>;\n equals: (a: T, b: T) => boolean;\n}\n\nexport function signal<T>(\n initialValue: T,\n options?: { equals?: (a: T, b: T) => boolean },\n): Signal<T> {\n const node: SignalNode<T> = {\n value: initialValue,\n subscribers: new Set(),\n equals: options?.equals ?? Object.is,\n };\n\n const read = (): T => {\n trackSubscriber(node);\n return node.value;\n };\n\n read.set = (value: T): void => {\n if (__DEV__ && currentSubscriber && currentSubscriber._tag === 'computed') {\n console.warn('[AkashJS] Writing to a signal inside computed() is not allowed. The write will be lost on the next evaluation.');\n }\n if (node.equals(node.value, value)) return;\n node.value = value;\n // Use batch to defer flush until all notifications complete (glitch-free)\n batch(() => { notifySubscribers(node); });\n };\n\n read.update = (fn: (prev: T) => T): void => {\n read.set(fn(node.value));\n };\n\n read.peek = (): T => node.value;\n\n return read;\n}\n\n// --- Computed ---\n\nconst enum ComputedState {\n Clean = 0,\n Dirty = 1,\n}\n\ninterface ComputedNode<T> {\n _tag: 'computed';\n fn: () => T;\n value: T | undefined;\n state: ComputedState;\n subscribers: Set<Subscriber>;\n sources: Set<SignalNode<unknown> | ComputedNode<unknown>>;\n equals: (a: T, b: T) => boolean;\n}\n\nexport function computed<T>(\n fn: () => T,\n options?: { equals?: (a: T, b: T) => boolean },\n): ReadonlySignal<T> {\n const node: ComputedNode<T> = {\n _tag: 'computed',\n fn,\n value: undefined,\n state: ComputedState.Dirty,\n subscribers: new Set(),\n sources: new Set(),\n equals: options?.equals ?? Object.is,\n };\n\n const read = (): T => {\n // Track this computed as a dependency of the current subscriber\n if (currentSubscriber) {\n node.subscribers.add(currentSubscriber);\n if ('sources' in currentSubscriber) {\n currentSubscriber.sources.add(node);\n }\n }\n\n if (node.state !== ComputedState.Clean) {\n recompute(node);\n }\n\n return node.value as T;\n };\n\n return read;\n}\n\nconst computingSet = new Set<ComputedNode<unknown>>();\n\nfunction recompute<T>(node: ComputedNode<T>): void {\n // Detect circular computed dependencies — only if THIS node is already being computed\n if (computingSet.has(node as ComputedNode<unknown>)) {\n throw new Error('[AkashJS] Circular dependency detected between computed values.');\n }\n computingSet.add(node as ComputedNode<unknown>);\n\n // Prevent effects from flushing while computed is evaluating.\n // Without this, a computed that reads other dirty computeds can trigger\n // notifySubscribers → scheduleEffect → flush → re-enter recompute on\n // a node still in computingSet (false circular detection).\n enterBatch();\n\n // Clean up old source subscriptions\n for (const source of node.sources) {\n source.subscribers.delete(node);\n }\n node.sources.clear();\n\n const prevSubscriber = currentSubscriber;\n currentSubscriber = node;\n\n try {\n const newValue = node.fn();\n const changed =\n node.value === undefined || !node.equals(node.value, newValue);\n node.value = newValue;\n node.state = ComputedState.Clean;\n\n // Only propagate if value actually changed.\n if (changed) {\n notifySubscribers(node);\n }\n } finally {\n computingSet.delete(node as ComputedNode<unknown>);\n currentSubscriber = prevSubscriber;\n exitBatch();\n }\n}\n\n// --- Effect ---\n\ninterface EffectNode extends ScheduledEffect {\n _tag: 'effect';\n fn: () => void | (() => void);\n cleanup: (() => void) | null;\n sources: Set<SignalNode<unknown> | ComputedNode<unknown>>;\n disposed: boolean;\n isRender: boolean;\n}\n\nexport function effect(\n fn: () => void | (() => void),\n options?: { render?: boolean },\n): () => void {\n const node: EffectNode = {\n _tag: 'effect',\n fn,\n cleanup: null,\n sources: new Set(),\n disposed: false,\n isRender: options?.render ?? false,\n run() {\n runEffect(node);\n },\n };\n\n // Run immediately to establish dependencies\n runEffect(node);\n\n // Return dispose function\n return () => {\n node.disposed = true;\n cleanupEffect(node);\n for (const source of node.sources) {\n source.subscribers.delete(node);\n }\n node.sources.clear();\n };\n}\n\nfunction runEffect(node: EffectNode): void {\n if (node.disposed) return;\n\n // Before re-running, check if any dirty computed source actually changed.\n // If all computed sources resolved to the same value, skip the re-run.\n if (node.sources.size > 0) {\n let anyChanged = false;\n for (const source of node.sources) {\n if ('_tag' in source && source._tag === 'computed') {\n if (source.state === ComputedState.Dirty) {\n const oldValue = source.value;\n recompute(source);\n if (!source.equals(oldValue as never, source.value as never)) {\n anyChanged = true;\n }\n }\n } else {\n // Plain signal source — if we got scheduled, something changed\n anyChanged = true;\n }\n }\n if (!anyChanged) return;\n }\n\n // Clean up previous run\n cleanupEffect(node);\n\n // Save old sources in case the effect throws — we need to re-subscribe\n const prevSources = new Set(node.sources);\n\n // Clean up old source subscriptions\n for (const source of node.sources) {\n source.subscribers.delete(node);\n }\n node.sources.clear();\n\n const prevSubscriber = currentSubscriber;\n currentSubscriber = node;\n\n try {\n const result = node.fn();\n if (typeof result === 'function') {\n node.cleanup = result;\n }\n } catch (err) {\n // Re-subscribe to previous sources so the effect can recover on next change\n for (const source of prevSources) {\n source.subscribers.add(node);\n node.sources.add(source);\n }\n console.error('[AkashJS] Error in effect (will retry on next signal change):', err);\n } finally {\n currentSubscriber = prevSubscriber;\n }\n}\n\nfunction cleanupEffect(node: EffectNode): void {\n if (node.cleanup) {\n try {\n node.cleanup();\n } catch (err) {\n console.error('[AkashJS] Error in effect cleanup (ignored):', err);\n }\n node.cleanup = null;\n }\n}\n\n// --- Untrack ---\n\n/** Execute a function without tracking any signal reads */\nexport function untrack<T>(fn: () => T): T {\n const prev = currentSubscriber;\n currentSubscriber = null;\n try {\n return fn();\n } finally {\n currentSubscriber = prev;\n }\n}\n\n// --- on() helper ---\n\n/**\n * Create an effect callback that only tracks specific signals.\n * All other signal reads inside the callback are untracked.\n *\n * ```ts\n * effect(on(url, (currentUrl, prevUrl) => {\n * fetch(currentUrl, options()); // options() not tracked\n * }));\n *\n * effect(on([url, page], ([u, p], prev) => {\n * fetch(`${u}?page=${p}`);\n * }));\n * ```\n */\nexport function on<T>(\n dep: () => T,\n fn: (value: T, prev: T | undefined) => void | (() => void),\n options?: { defer?: boolean },\n): () => void | (() => void);\nexport function on<T extends readonly (() => unknown)[]>(\n deps: [...T],\n fn: (values: { [K in keyof T]: ReturnType<T[K]> }, prev: { [K in keyof T]: ReturnType<T[K]> } | undefined) => void | (() => void),\n options?: { defer?: boolean },\n): () => void | (() => void);\nexport function on(\n deps: (() => unknown) | (() => unknown)[],\n fn: (values: unknown, prev: unknown) => void | (() => void),\n options?: { defer?: boolean },\n): () => void | (() => void) {\n const isArray = Array.isArray(deps);\n const depArray = isArray ? deps : [deps];\n let prevValues: unknown[] | undefined;\n let isFirst = true;\n\n return () => {\n // Track only the specified deps\n const values = depArray.map(d => d());\n\n // Skip the initial effect run — only fire on actual changes\n // (pass { defer: false } to opt out and run immediately)\n if (isFirst) {\n isFirst = false;\n prevValues = values.slice();\n if (options?.defer !== false) return;\n }\n\n const prev = prevValues;\n prevValues = values.slice();\n\n // Run fn without tracking so reads inside don't create subscriptions\n return untrack(() => fn(\n isArray ? values : values[0],\n prev ? (isArray ? prev : prev[0]) : undefined,\n ));\n };\n}\n\n// --- Internal helpers ---\n\nfunction trackSubscriber(\n node: SignalNode<unknown> | ComputedNode<unknown>,\n): void {\n if (currentSubscriber) {\n node.subscribers.add(currentSubscriber);\n\n if ('sources' in currentSubscriber) {\n currentSubscriber.sources.add(node);\n }\n }\n}\n\nfunction notifySubscribers(\n node: SignalNode<unknown> | ComputedNode<unknown>,\n): void {\n // Snapshot subscribers before iterating. Effects that run synchronously\n // during flush() will delete and re-add themselves to the Set, and JS\n // Set iterators visit newly added entries — causing an infinite loop\n // without the snapshot.\n const subs = [...node.subscribers];\n for (const sub of subs) {\n if (sub._tag === 'computed') {\n // Mark dirty. The computed will re-evaluate lazily when read.\n sub.state = ComputedState.Dirty;\n // Propagate through the computed chain to reach effects.\n // The effects will re-read the computed, triggering recompute,\n // and only update DOM if the value actually changed.\n notifySubscribers(sub);\n } else if (sub._tag === 'effect') {\n scheduleEffect(sub);\n }\n }\n}\n"]}
|
package/dist/chunk-L4DNCDUA.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var c=new Set,i=new Set,d=false,a=0,S=3,h=100;function l(){if(d)return;d=true;let e=new Map,r=false,n=0;for(;(c.size>0||i.size>0)&&n<h;){if(n++,c.size>0){let t=[...c].sort(w);c.clear();for(let o of t){let u=(e.get(o)??0)+1;if(e.set(o,u),u>S){r=true;continue}o.run();}}if(i.size>0){let t=[...i].sort(w);i.clear();for(let o of t){let u=(e.get(o)??0)+1;if(e.set(o,u),u>S){r=true;continue}o.run();}}if(r&&c.size===0&&i.size===0)break}(r||n>=h)&&(c.clear(),i.clear(),console.error("[AkashJS] Circular dependency detected between effects. Two or more effects are writing to each other's dependencies. The cycle has been broken after "+n+" iterations.")),d=false;}function y(e){e.isRender?c.add(e):i.add(e),a===0&&!d&&l();}function g(e){a++;try{e();}finally{a--,a===0&&l();}}function k(){a++;}function m(){a--,a===0&&l();}function w(e,r){return (e.depth??0)-(r.depth??0)}function D(){l();}var q=typeof process>"u"||process.env?.NODE_ENV!=="production";var s=null;function V(e,r){let n={value:e,subscribers:new Set,equals:r?.equals??Object.is},t=()=>(R(n),n.value);return t.set=o=>{q&&s&&s._tag==="computed"&&console.warn("[AkashJS] Writing to a signal inside computed() is not allowed. The write will be lost on the next evaluation."),!n.equals(n.value,o)&&(n.value=o,g(()=>{v(n);}));},t.update=o=>{t.set(o(n.value));},t.peek=()=>n.value,t}function B(e,r){let n={_tag:"computed",fn:e,value:void 0,state:1,subscribers:new Set,sources:new Set,equals:r?.equals??Object.is};return ()=>(s&&(n.subscribers.add(s),"sources"in s&&s.sources.add(n)),n.state!==0&&N(n),n.value)}var b=new Set;function N(e){if(b.has(e))throw new Error("[AkashJS] Circular dependency detected between computed values.");b.add(e),k();for(let n of e.sources)n.subscribers.delete(e);e.sources.clear();let r=s;s=e;try{let n=e.fn(),t=e.value===void 0||!e.equals(e.value,n);e.value=n,e.state=0,t&&v(e);}finally{b.delete(e),s=r,m();}}function F(e,r){let n={_tag:"effect",fn:e,cleanup:null,sources:new Set,disposed:false,isRender:r?.render??false,run(){E(n);}};return E(n),()=>{n.disposed=true,C(n);for(let t of n.sources)t.subscribers.delete(n);n.sources.clear();}}function E(e){if(e.disposed)return;if(e.sources.size>0){let t=false;for(let o of e.sources)if("_tag"in o&&o._tag==="computed"){if(o.state===1){let u=o.value;N(o),o.equals(u,o.value)||(t=true);}}else t=true;if(!t)return}C(e);let r=new Set(e.sources);for(let t of e.sources)t.subscribers.delete(e);e.sources.clear();let n=s;s=e;try{let t=e.fn();typeof t=="function"&&(e.cleanup=t);}catch(t){for(let o of r)o.subscribers.add(e),e.sources.add(o);console.error("[AkashJS] Error in effect (will retry on next signal change):",t);}finally{s=n;}}function C(e){if(e.cleanup){try{e.cleanup();}catch(r){console.error("[AkashJS] Error in effect cleanup (ignored):",r);}e.cleanup=null;}}function A(e){let r=s;s=null;try{return e()}finally{s=r;}}function K(e,r,n){let t=Array.isArray(e),o=t?e:[e],u,T=true;return ()=>{let f=o.map(x=>x());if(T&&(T=false,u=f.slice(),n?.defer!==false))return;let p=u;return u=f.slice(),A(()=>r(t?f:f[0],p?t?p:p[0]:void 0))}}function R(e){s&&(e.subscribers.add(s),"sources"in s&&s.sources.add(e));}function v(e){let r=[...e.subscribers];for(let n of r)n._tag==="computed"?(n.state=1,v(n)):n._tag==="effect"&&y(n);}exports.a=g;exports.b=D;exports.c=V;exports.d=B;exports.e=F;exports.f=A;exports.g=K;//# sourceMappingURL=chunk-L4DNCDUA.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-L4DNCDUA.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/scheduler.ts","../src/signals.ts"],"names":["pendingRender","pendingUser","flushing","batchDepth","MAX_EFFECT_RUNS","MAX_FLUSH_ITERATIONS","flush","runCounts","circularDetected","iterations","queue","byDepth","fx","count","scheduleEffect","batch","fn","enterBatch","exitBatch","a","b","flushSync","__DEV__","currentSubscriber","signal","initialValue","options","node","read","trackSubscriber","value","notifySubscribers","computed","recompute","computingSet","source","prevSubscriber","newValue","changed","effect","runEffect","cleanupEffect","anyChanged","oldValue","prevSources","result","err","untrack","prev","on","deps","isArray","depArray","prevValues","isFirst","values","d","sub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KAAA,CACtC,CAAC,CACH,CACF,CAIA,SAASnB,CAAAA,CACPF,CAAAA,CACM,CACFJ,CAAAA,GACFI,CAAAA,CAAK,YAAY,GAAA,CAAIJ,CAAiB,EAElC,SAAA,GAAaA,CAAAA,EACfA,EAAkB,OAAA,CAAQ,GAAA,CAAII,CAAI,CAAA,EAGxC,CAEA,SAASI,CAAAA,CACPJ,CAAAA,CACM,CAKN,IAAM8B,CAAAA,CAAO,CAAC,GAAG9B,CAAAA,CAAK,WAAW,EACjC,IAAA,IAAW+B,CAAAA,IAAOD,CAAAA,CACZC,CAAAA,CAAI,IAAA,GAAS,UAAA,EAEfA,EAAI,KAAA,CAAQ,CAAA,CAIZ3B,EAAkB2B,CAAG,CAAA,EACZA,EAAI,IAAA,GAAS,QAAA,EACtB5C,CAAAA,CAAe4C,CAAG,EAGxB","file":"chunk-L4DNCDUA.cjs","sourcesContent":["/**\n * Microtask-based effect scheduler with priority levels and deduplication.\n *\n * Render effects (DOM bindings) run before user effects to ensure\n * DOM is consistent before user-side effects execute.\n */\n\nexport interface ScheduledEffect {\n run(): void;\n isRender: boolean;\n /** Depth in the dependency graph (0 = root). Lower depth runs first. */\n depth?: number;\n}\n\nconst pendingRender = new Set<ScheduledEffect>();\nconst pendingUser = new Set<ScheduledEffect>();\nlet flushing = false;\nlet batchDepth = 0;\nlet flushScheduled = false;\n\nconst MAX_EFFECT_RUNS = 3;\nconst MAX_FLUSH_ITERATIONS = 100;\n\nfunction flush(): void {\n if (flushing) return;\n flushing = true;\n flushScheduled = false;\n\n // Fresh per-effect run counter for THIS flush — reset every time\n const runCounts = new Map<ScheduledEffect, number>();\n let circularDetected = false;\n\n // Process render effects first, then user effects.\n // Effects may enqueue more effects during flush, so loop until empty.\n let iterations = 0;\n while ((pendingRender.size > 0 || pendingUser.size > 0) && iterations < MAX_FLUSH_ITERATIONS) {\n iterations++;\n\n // Drain render effects (sorted by depth — parents before children)\n if (pendingRender.size > 0) {\n const queue = [...pendingRender].sort(byDepth);\n pendingRender.clear();\n for (const fx of queue) {\n const count = (runCounts.get(fx) ?? 0) + 1;\n runCounts.set(fx, count);\n if (count > MAX_EFFECT_RUNS) {\n circularDetected = true;\n continue; // skip this effect — it's in a cycle\n }\n fx.run();\n }\n }\n\n // Drain user effects (sorted by depth)\n if (pendingUser.size > 0) {\n const queue = [...pendingUser].sort(byDepth);\n pendingUser.clear();\n for (const fx of queue) {\n const count = (runCounts.get(fx) ?? 0) + 1;\n runCounts.set(fx, count);\n if (count > MAX_EFFECT_RUNS) {\n circularDetected = true;\n continue; // skip this effect — it's in a cycle\n }\n fx.run();\n }\n }\n\n // If all remaining effects were skipped due to cycle detection, break\n if (circularDetected && pendingRender.size === 0 && pendingUser.size === 0) {\n break;\n }\n }\n\n if (circularDetected || iterations >= MAX_FLUSH_ITERATIONS) {\n pendingRender.clear();\n pendingUser.clear();\n console.error(\n '[AkashJS] Circular dependency detected between effects. ' +\n 'Two or more effects are writing to each other\\'s dependencies. ' +\n 'The cycle has been broken after ' + iterations + ' iterations.'\n );\n }\n\n flushing = false;\n}\n\nexport function scheduleEffect(fx: ScheduledEffect): void {\n if (fx.isRender) {\n pendingRender.add(fx);\n } else {\n pendingUser.add(fx);\n }\n\n if (batchDepth === 0 && !flushing) {\n flush();\n }\n}\n\n/**\n * Batch multiple signal writes — subscribers are notified only once\n * at the end of the batch.\n */\nexport function batch(fn: () => void): void {\n batchDepth++;\n try {\n fn();\n } finally {\n batchDepth--;\n if (batchDepth === 0) {\n flush();\n }\n }\n}\n\n/** Enter/exit batch depth — used by computed recompute to prevent mid-evaluation flush */\nexport function enterBatch(): void { batchDepth++; }\nexport function exitBatch(): void {\n batchDepth--;\n if (batchDepth === 0) flush();\n}\n\n/** Sort effects by depth (lower depth first = parents before children) */\nfunction byDepth(a: ScheduledEffect, b: ScheduledEffect): number {\n return (a.depth ?? 0) - (b.depth ?? 0);\n}\n\n/** Synchronously flush all pending effects. Useful for testing. */\nexport function flushSync(): void {\n flush();\n}\n","/**\n * Fine-grained reactivity system.\n *\n * Inspired by SolidJS/Preact Signals. Provides signal(), computed(),\n * effect(), and untrack() primitives with automatic dependency tracking\n * and glitch-free diamond dependency resolution.\n */\n\nimport { scheduleEffect, batch, enterBatch, exitBatch, type ScheduledEffect } from './scheduler.js';\n\nconst __DEV__ = typeof process === 'undefined' || process.env?.NODE_ENV !== 'production';\n\n/** Depth counter to defer effect scheduling until all notifications complete (glitch-free) */\nlet notifyDepth = 0;\n\n// --- Tracking scope ---\n\ntype Subscriber = EffectNode | ComputedNode<unknown>;\n\nlet currentSubscriber: Subscriber | null = null;\n\n// --- Signal ---\n\nexport interface Signal<T> {\n /** Read the current value (tracks dependency if inside a reactive scope) */\n (): T;\n /** Set a new value */\n set(value: T): void;\n /** Update the value using the previous value */\n update(fn: (prev: T) => T): void;\n /** Read without tracking (no dependency registered) */\n peek(): T;\n}\n\nexport type ReadonlySignal<T> = () => T;\n\ninterface SignalNode<T> {\n value: T;\n subscribers: Set<Subscriber>;\n equals: (a: T, b: T) => boolean;\n}\n\nexport function signal<T>(\n initialValue: T,\n options?: { equals?: (a: T, b: T) => boolean },\n): Signal<T> {\n const node: SignalNode<T> = {\n value: initialValue,\n subscribers: new Set(),\n equals: options?.equals ?? Object.is,\n };\n\n const read = (): T => {\n trackSubscriber(node);\n return node.value;\n };\n\n read.set = (value: T): void => {\n if (__DEV__ && currentSubscriber && currentSubscriber._tag === 'computed') {\n console.warn('[AkashJS] Writing to a signal inside computed() is not allowed. The write will be lost on the next evaluation.');\n }\n if (node.equals(node.value, value)) return;\n node.value = value;\n // Use batch to defer flush until all notifications complete (glitch-free)\n batch(() => { notifySubscribers(node); });\n };\n\n read.update = (fn: (prev: T) => T): void => {\n read.set(fn(node.value));\n };\n\n read.peek = (): T => node.value;\n\n return read;\n}\n\n// --- Computed ---\n\nconst enum ComputedState {\n Clean = 0,\n Dirty = 1,\n}\n\ninterface ComputedNode<T> {\n _tag: 'computed';\n fn: () => T;\n value: T | undefined;\n state: ComputedState;\n subscribers: Set<Subscriber>;\n sources: Set<SignalNode<unknown> | ComputedNode<unknown>>;\n equals: (a: T, b: T) => boolean;\n}\n\nexport function computed<T>(\n fn: () => T,\n options?: { equals?: (a: T, b: T) => boolean },\n): ReadonlySignal<T> {\n const node: ComputedNode<T> = {\n _tag: 'computed',\n fn,\n value: undefined,\n state: ComputedState.Dirty,\n subscribers: new Set(),\n sources: new Set(),\n equals: options?.equals ?? Object.is,\n };\n\n const read = (): T => {\n // Track this computed as a dependency of the current subscriber\n if (currentSubscriber) {\n node.subscribers.add(currentSubscriber);\n if ('sources' in currentSubscriber) {\n currentSubscriber.sources.add(node);\n }\n }\n\n if (node.state !== ComputedState.Clean) {\n recompute(node);\n }\n\n return node.value as T;\n };\n\n return read;\n}\n\nconst computingSet = new Set<ComputedNode<unknown>>();\n\nfunction recompute<T>(node: ComputedNode<T>): void {\n // Detect circular computed dependencies — only if THIS node is already being computed\n if (computingSet.has(node as ComputedNode<unknown>)) {\n throw new Error('[AkashJS] Circular dependency detected between computed values.');\n }\n computingSet.add(node as ComputedNode<unknown>);\n\n // Prevent effects from flushing while computed is evaluating.\n // Without this, a computed that reads other dirty computeds can trigger\n // notifySubscribers → scheduleEffect → flush → re-enter recompute on\n // a node still in computingSet (false circular detection).\n enterBatch();\n\n // Clean up old source subscriptions\n for (const source of node.sources) {\n source.subscribers.delete(node);\n }\n node.sources.clear();\n\n const prevSubscriber = currentSubscriber;\n currentSubscriber = node;\n\n try {\n const newValue = node.fn();\n const changed =\n node.value === undefined || !node.equals(node.value, newValue);\n node.value = newValue;\n node.state = ComputedState.Clean;\n\n // Only propagate if value actually changed.\n if (changed) {\n notifySubscribers(node);\n }\n } finally {\n computingSet.delete(node as ComputedNode<unknown>);\n currentSubscriber = prevSubscriber;\n exitBatch();\n }\n}\n\n// --- Effect ---\n\ninterface EffectNode extends ScheduledEffect {\n _tag: 'effect';\n fn: () => void | (() => void);\n cleanup: (() => void) | null;\n sources: Set<SignalNode<unknown> | ComputedNode<unknown>>;\n disposed: boolean;\n isRender: boolean;\n}\n\nexport function effect(\n fn: () => void | (() => void),\n options?: { render?: boolean },\n): () => void {\n const node: EffectNode = {\n _tag: 'effect',\n fn,\n cleanup: null,\n sources: new Set(),\n disposed: false,\n isRender: options?.render ?? false,\n run() {\n runEffect(node);\n },\n };\n\n // Run immediately to establish dependencies\n runEffect(node);\n\n // Return dispose function\n return () => {\n node.disposed = true;\n cleanupEffect(node);\n for (const source of node.sources) {\n source.subscribers.delete(node);\n }\n node.sources.clear();\n };\n}\n\nfunction runEffect(node: EffectNode): void {\n if (node.disposed) return;\n\n // Before re-running, check if any dirty computed source actually changed.\n // If all computed sources resolved to the same value, skip the re-run.\n if (node.sources.size > 0) {\n let anyChanged = false;\n for (const source of node.sources) {\n if ('_tag' in source && source._tag === 'computed') {\n if (source.state === ComputedState.Dirty) {\n const oldValue = source.value;\n recompute(source);\n if (!source.equals(oldValue as never, source.value as never)) {\n anyChanged = true;\n }\n }\n } else {\n // Plain signal source — if we got scheduled, something changed\n anyChanged = true;\n }\n }\n if (!anyChanged) return;\n }\n\n // Clean up previous run\n cleanupEffect(node);\n\n // Save old sources in case the effect throws — we need to re-subscribe\n const prevSources = new Set(node.sources);\n\n // Clean up old source subscriptions\n for (const source of node.sources) {\n source.subscribers.delete(node);\n }\n node.sources.clear();\n\n const prevSubscriber = currentSubscriber;\n currentSubscriber = node;\n\n try {\n const result = node.fn();\n if (typeof result === 'function') {\n node.cleanup = result;\n }\n } catch (err) {\n // Re-subscribe to previous sources so the effect can recover on next change\n for (const source of prevSources) {\n source.subscribers.add(node);\n node.sources.add(source);\n }\n console.error('[AkashJS] Error in effect (will retry on next signal change):', err);\n } finally {\n currentSubscriber = prevSubscriber;\n }\n}\n\nfunction cleanupEffect(node: EffectNode): void {\n if (node.cleanup) {\n try {\n node.cleanup();\n } catch (err) {\n console.error('[AkashJS] Error in effect cleanup (ignored):', err);\n }\n node.cleanup = null;\n }\n}\n\n// --- Untrack ---\n\n/** Execute a function without tracking any signal reads */\nexport function untrack<T>(fn: () => T): T {\n const prev = currentSubscriber;\n currentSubscriber = null;\n try {\n return fn();\n } finally {\n currentSubscriber = prev;\n }\n}\n\n// --- on() helper ---\n\n/**\n * Create an effect callback that only tracks specific signals.\n * All other signal reads inside the callback are untracked.\n *\n * ```ts\n * effect(on(url, (currentUrl, prevUrl) => {\n * fetch(currentUrl, options()); // options() not tracked\n * }));\n *\n * effect(on([url, page], ([u, p], prev) => {\n * fetch(`${u}?page=${p}`);\n * }));\n * ```\n */\nexport function on<T>(\n dep: () => T,\n fn: (value: T, prev: T | undefined) => void | (() => void),\n options?: { defer?: boolean },\n): () => void | (() => void);\nexport function on<T extends readonly (() => unknown)[]>(\n deps: [...T],\n fn: (values: { [K in keyof T]: ReturnType<T[K]> }, prev: { [K in keyof T]: ReturnType<T[K]> } | undefined) => void | (() => void),\n options?: { defer?: boolean },\n): () => void | (() => void);\nexport function on(\n deps: (() => unknown) | (() => unknown)[],\n fn: (values: unknown, prev: unknown) => void | (() => void),\n options?: { defer?: boolean },\n): () => void | (() => void) {\n const isArray = Array.isArray(deps);\n const depArray = isArray ? deps : [deps];\n let prevValues: unknown[] | undefined;\n let isFirst = true;\n\n return () => {\n // Track only the specified deps\n const values = depArray.map(d => d());\n\n // Skip the initial effect run — only fire on actual changes\n // (pass { defer: false } to opt out and run immediately)\n if (isFirst) {\n isFirst = false;\n prevValues = values.slice();\n if (options?.defer !== false) return;\n }\n\n const prev = prevValues;\n prevValues = values.slice();\n\n // Run fn without tracking so reads inside don't create subscriptions\n return untrack(() => fn(\n isArray ? values : values[0],\n prev ? (isArray ? prev : prev[0]) : undefined,\n ));\n };\n}\n\n// --- Internal helpers ---\n\nfunction trackSubscriber(\n node: SignalNode<unknown> | ComputedNode<unknown>,\n): void {\n if (currentSubscriber) {\n node.subscribers.add(currentSubscriber);\n\n if ('sources' in currentSubscriber) {\n currentSubscriber.sources.add(node);\n }\n }\n}\n\nfunction notifySubscribers(\n node: SignalNode<unknown> | ComputedNode<unknown>,\n): void {\n // Snapshot subscribers before iterating. Effects that run synchronously\n // during flush() will delete and re-add themselves to the Set, and JS\n // Set iterators visit newly added entries — causing an infinite loop\n // without the snapshot.\n const subs = [...node.subscribers];\n for (const sub of subs) {\n if (sub._tag === 'computed') {\n // Mark dirty. The computed will re-evaluate lazily when read.\n sub.state = ComputedState.Dirty;\n // Propagate through the computed chain to reach effects.\n // The effects will re-read the computed, triggering recompute,\n // and only update DOM if the value actually changed.\n notifySubscribers(sub);\n } else if (sub._tag === 'effect') {\n scheduleEffect(sub);\n }\n }\n}\n"]}
|
package/dist/chunk-LR2QY7QP.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {c,d,e}from'./chunk-JBHFILMZ.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$1=Object.keys(a);for(let t of c$1)o[t]=c(a[t]);let n={$id:s};for(let t of c$1)n[t]=o[t];if(r.getters)for(let[t,e]of Object.entries(r.getters))n[t]=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$1)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$1)t[e]=o[e]();return t};let u=new Set,S=null;n.$subscribe=t=>{if(u.add(t),!S){let e$1=true;S=e(()=>{for(let f of c$1)o[f]();if(e$1){e$1=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}export{v as a,x as b,b as c,R as d};//# sourceMappingURL=chunk-LR2QY7QP.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-LR2QY7QP.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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,GAAAA,CAAY,MAAA,CAAO,IAAA,CAAKJ,CAAY,EAE1C,IAAA,IAAWK,CAAAA,IAAOD,IAChBD,CAAAA,CAAaE,CAAG,EAAIC,CAAAA,CAAON,CAAAA,CAAaK,CAAG,CAAC,EAI9C,IAAMJ,CAAAA,CAAa,CAAE,GAAA,CAAKH,CAAG,CAAA,CAG7B,IAAA,IAAWO,CAAAA,IAAOD,GAAAA,CAChBH,EAAMI,CAAG,CAAA,CAAIF,CAAAA,CAAaE,CAAG,EAI/B,GAAIN,CAA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EAAIF,CAAAA,CAAaE,CAAG,CAAA,EAAE,CAEpC,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,GAAAA,CAAY,IAAA,CAChBF,CAAAA,CAAkBG,CAAAA,CAAO,IAAM,CAE7B,IAAA,IAAWhB,CAAAA,IAAOD,GAAAA,CAChBD,EAAaE,CAAG,CAAA,EAAE,CAGpB,GAAIe,IAAW,CACbA,GAAAA,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-LR2QY7QP.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 +0,0 @@
|
|
|
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,CA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AAY,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-QEA2QRNB.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"]}
|
package/dist/chunk-WEPYZZSS.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {c,d}from'./chunk-JBHFILMZ.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$1=t.keyField??"id",r=c([]),n=c([]),i=c(false),l=c(typeof navigator<"u"?navigator.onLine:true),b=d(()=>n().length),o=null,m=null,T=false;typeof window<"u"&&(window.addEventListener("online",()=>{l.set(true),v();}),window.addEventListener("offline",()=>l.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=setInterval(()=>{l()&&b()>0&&!i()&&v();},e);}function g(e){return String(e[c$1])}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(),sync:v,dispose(){T=true,m&&clearInterval(m),o?.close();}}}export{A as a};//# sourceMappingURL=chunk-WEPYZZSS.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-WEPYZZSS.js.map
|