import"./index-DjCrtoJM.js";const y={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},p=Object.values(y);function _(n,l,i,o,c){const a=Math.min(n,l*o**i);return(1-c*Math.random())*a}const v=3e4,D=1e3;function O(n){const{buildUrl:l,eventTypes:i,name:o,crossTab:c=!1}=n,a=new Map,u=c&&typeof BroadcastChannel<"u"&&typeof navigator<"u"&&typeof navigator.locks<"u";if(u&&!o)throw new Error("createSSESubscription: `name` is required when crossTab");function d(e,t){e.bootDone=!0;for(const s of e.handlers)try{s(t)}catch{}}function h(e){for(const t of e.reconnectHandlers)try{t()}catch{}}function E(e){const t=new EventSource(l(e.key));e.es=t,t.onopen=()=>{e.reconnectAttempt=0,e.bootDone&&(h(e),e.channel?.postMessage({kind:"reconnect"})),e.bootDone=!0},t.onerror=()=>{e.es===t&&t.readyState===EventSource.CLOSED&&C(e)};const s=r=>{e.channel?.postMessage({kind:"event",type:r.type,data:r.data}),d(e,r)};for(const r of i)t.addEventListener(r,s)}function C(e){if(e.refCount<=0||e.reconnectTimer)return;const t=_(v,D,e.reconnectAttempt,2,0);e.reconnectAttempt++,e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=null,!(e.refCount<=0||!e.isLeader)&&(e.es?.close(),E(e))},t)}function T(e){if(e.refCount<=0){e.releaseLeadership?.(),e.releaseLeadership=null;return}e.isLeader=!0,E(e)}function m(e){if(!u){T(e);return}e.lockAbort=new AbortController,navigator.locks.request(`sse-leader:${o}:${e.key}`,{signal:e.lockAbort.signal},()=>new Promise(t=>{e.releaseLeadership=t,T(e)})).catch(()=>{})}function L(e,t){t.kind==="event"?d(e,new MessageEvent(t.type,{data:t.data})):t.kind==="reconnect"&&h(e)}function A(e){const t=a.get(e);if(t)return t;const s={key:e,refCount:0,handlers:new Set,reconnectHandlers:new Set,bootDone:!1,es:null,isLeader:!1,reconnectAttempt:0,reconnectTimer:null,channel:null,lockAbort:null,releaseLeadership:null};if(a.set(e,s),u){const r=new BroadcastChannel(`sse:${o}:${e}`);r.onmessage=f=>L(s,f.data),s.channel=r}return m(s),s}function k(e){e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null),e.es?.close(),e.es=null,e.releaseLeadership?.(),e.releaseLeadership=null,e.lockAbort?.abort(),e.lockAbort=null,e.channel?.close(),e.channel=null,a.delete(e.key)}return{subscribe(e,t,s){const r=A(e);r.refCount++,r.handlers.add(t),s&&r.reconnectHandlers.add(s);let f=!1;return()=>{f||(f=!0,r.handlers.delete(t),s&&r.reconnectHandlers.delete(s),r.refCount--,r.refCount<=0&&k(r))}}}}function w(n,l){const i=new Set(l);return{subscribe(o,c,a){const u=d=>{i.has(d.type)&&c(d)};return n.subscribe(o,u,a)}}}const b=["workflow.execution.created","workflow.execution.resumed","workflow.step.execute","workflow.step.completed"],g=[...p,"workflow.*"],M=[...p,...b],S=O({name:"watch",buildUrl:n=>`/api/${encodeURIComponent(n)}/watch?types=${g.join(",")}`,eventTypes:M,crossTab:!0}),H=w(S,[...p]),P=w(S,b);export{y as D,H as d,_ as e,P as w};
