// @bun
var{defineProperty:W,getOwnPropertyNames:k,getOwnPropertyDescriptor:L}=Object,C=Object.prototype.hasOwnProperty;function b(q){return this[q]}var u=(q)=>{var z=(_??=new WeakMap).get(q),H;if(z)return z;if(z=W({},"__esModule",{value:!0}),q&&typeof q==="object"||typeof q==="function"){for(var J of k(q))if(!C.call(z,J))W(z,J,{get:b.bind(q,J),enumerable:!(H=L(q,J))||H.enumerable})}return _.set(q,z),z},_;var N=(q)=>q;function w(q,z){this[q]=N.bind(null,z)}var h=(q,z)=>{for(var H in z)W(q,H,{get:z[H],enumerable:!0,configurable:!0,set:w.bind(z,H)})};var v=(q,z)=>()=>(q&&(z=q(q=0)),z);var f=import.meta.require;function g(){let q=typeof window<"u"?window.__stx_broadcasting:void 0;return{host:q?.host??(typeof window<"u"?window.location.hostname:"localhost"),port:q?.port??6001,scheme:q?.scheme??"ws"}}function p(q,z={}){let H=g(),J=z.host??H.host,$=z.port??H.port,A=z.scheme??H.scheme,E=z.autoConnect??!0,D=z.autoReconnect??!0,j=z.maxReconnectAttempts??Number.POSITIVE_INFINITY,R=z.reconnectDelay??1000,Q=new Set,K=new Map,G={data:null,event:null,isSubscribed:!1,isConnected:!1,socketId:null},I=null,O=0,P=null,S=!1;function M(){for(let F of Q)F(G)}function x(F,B){let Y=K.get(F);if(Y)for(let V of Y)V(B);let Z=K.get("*");if(Z)for(let V of Z)V(B)}function U(){if(typeof WebSocket>"u")return;S=!1;try{I=new WebSocket(`${A}://${J}:${$}/ws`)}catch{X();return}I.onmessage=(F)=>{try{let B=JSON.parse(F.data);if(B.event==="connection_established"){G={...G,isConnected:!0,socketId:B.data?.socket_id??null},M(),I.send(JSON.stringify({event:"subscribe",channel:q}));return}if(B.event==="subscription_succeeded"&&B.channel===q){G={...G,isSubscribed:!0},O=0,M();return}if(B.event==="subscription_error"&&B.channel===q){console.warn(`[stx] Channel subscription failed: ${q}`,B.data);return}if(B.channel===q&&B.event)G={...G,data:B.data,event:B.event},M(),x(B.event,B.data)}catch{}},I.onclose=()=>{let F=G.isSubscribed;if(G={...G,isConnected:!1,isSubscribed:!1,socketId:null},I=null,M(),!S&&D)X()},I.onerror=()=>{}}function X(){if(O>=j)return;let F=Math.min(R*2**O,30000);O++,P=setTimeout(U,F)}function T(){if(S=!0,P)clearTimeout(P),P=null;if(I){if(G.isSubscribed)try{I.send(JSON.stringify({event:"unsubscribe",channel:q}))}catch{}I.close(),I=null}G={data:null,event:null,isSubscribed:!1,isConnected:!1,socketId:null},M()}if(E)U();return{get:()=>G,subscribe:(F)=>{return Q.add(F),F(G),()=>{Q.delete(F)}},on:(F,B)=>{if(!K.has(F))K.set(F,new Set);return K.get(F).add(B),()=>{K.get(F)?.delete(B)}},close:T,open:U}}export{p as useChannel};
