// @bun
var{defineProperty:Y,getOwnPropertyNames:x,getOwnPropertyDescriptor:L}=Object,D=Object.prototype.hasOwnProperty;function R(z){return this[z]}var d=(z)=>{var q=(_??=new WeakMap).get(z),G;if(q)return q;if(q=Y({},"__esModule",{value:!0}),z&&typeof z==="object"||typeof z==="function"){for(var B of x(z))if(!D.call(q,B))Y(q,B,{get:R.bind(z,B),enumerable:!(G=L(z,B))||G.enumerable})}return _.set(z,q),q},_;var C=(z)=>z;function g(z,q){this[z]=C.bind(null,q)}var y=(z,q)=>{for(var G in q)Y(z,G,{get:q[G],enumerable:!0,configurable:!0,set:g.bind(q,G)})};var p=(z,q)=>()=>(z&&(q=z(z=0)),q);var N=import.meta.require;function E(){return typeof window<"u"&&"EventSource"in window}function b(z,q={}){let{withCredentials:G=!1,autoReconnect:B=!0,immediate:$=!0,events:Z=[],onOpen:h,onMessage:w,onError:J}=q,U=new Set,P=new Map,A={status:"closed",data:null,event:null,lastEventId:null,error:null},H=null,T=0,V=!1;function K(){U.forEach((j)=>j(A))}function W(j,F){let I=P.get(j);if(I)I.forEach((Q)=>Q(F))}function M(){if(typeof B==="object")return{retries:B.retries??3,delay:B.delay??1000,onFailed:B.onFailed};return{retries:3,delay:1000,onFailed:void 0}}function X(){if(!E())return;V=!1,A={...A,status:"connecting"},K();try{H=new EventSource(z.toString(),{withCredentials:G}),H.onopen=(j)=>{A={...A,status:"open"},T=0,K(),h?.(j)},H.onmessage=(j)=>{let F;try{F=JSON.parse(j.data)}catch{F=j.data}A={...A,data:F,event:"message",lastEventId:j.lastEventId||null},K(),W("message",j),w?.(j)},H.onerror=(j)=>{if(A={...A,status:"error",error:j},K(),J?.(j),H?.readyState===EventSource.CLOSED){if(A={...A,status:"closed"},K(),B&&!V){let F=M();if(T<F.retries)T++,setTimeout(X,F.delay*T);else F.onFailed?.()}}};for(let j of Z)H.addEventListener(j,(F)=>{let I=F,Q;try{Q=JSON.parse(I.data)}catch{Q=I.data}A={...A,data:Q,event:j,lastEventId:I.lastEventId||null},K(),W(j,I)})}catch(j){A={...A,status:"error",error:j},K()}}function O(){if(V=!0,H)H.close(),H=null,A={...A,status:"closed"},K()}function k(j,F){if(!P.has(j)){if(P.set(j,new Set),H&&!Z.includes(j))H.addEventListener(j,(I)=>{W(j,I)})}return P.get(j).add(F),()=>{P.get(j)?.delete(F)}}if($)X();return{get:()=>A,subscribe:(j)=>{return U.add(j),j(A),()=>{U.delete(j)}},open:X,close:O,eventSource:()=>H,on:k}}function f(z){let q=b(z);return{data:{get:()=>q.get().data,subscribe:(G)=>{return q.subscribe((B)=>G(B.data))}},status:{get:()=>q.get().status,subscribe:(G)=>{return q.subscribe((B)=>G(B.status))}},close:q.close,open:q.open}}export{f as useSSE,b as useEventSource,E as isEventSourceSupported};
