class r{static instance;window;idCounter;pendingCalls;pendingRejects;timeout;instanceId;constructor(t){this.window=t,this.idCounter=1,this.pendingCalls={},this.pendingRejects={},this.timeout=1e3*60*5,this.instanceId=`proxy-${Math.random().toString(10)}`,t.addEventListener("message",this.handleMessage.bind(this))}static getInstance(t){return r.instance||(r.instance=new r(t)),r.instance}cachedProxy=null;getProxy(){return this.cachedProxy?this.cachedProxy:(this.cachedProxy=new Proxy(this,{get:(t,i)=>(...e)=>new Promise((a,n)=>{const s=this.idCounter++;this.pendingCalls[s]=a,this.pendingRejects[s]=n;const c=JSON.parse(JSON.stringify({type:"KAI_FROM_PAGE",id:s,functionName:i,args:e,instanceId:this.instanceId}));this.window.postMessage(c),setTimeout(()=>{this.pendingCalls[s]&&(delete this.pendingCalls[s],delete this.pendingRejects[s],n(new Error("Timeout")))},this.timeout)})}),this.cachedProxy)}handleMessage(t){try{const{type:i,id:e,data:a,error:n,message:s,instanceId:c}=t.data;if(t.data.source)return;i==="KAI_TO_PAGE"&&e!==null&&c===this.instanceId&&this.pendingCalls[e]&&(n?(s?.includes("Extension context invalidated")&&(window.__kaptionNeedsReload=!0),this.pendingRejects[e](s)):this.pendingCalls[e](a),delete this.pendingCalls[e],delete this.pendingRejects[e])}catch(i){const e={};try{Error.captureStackTrace(e)}catch{}setTimeout(()=>{const a={message:i.message,originalStack:i.stack,fullStackTrace:e?.stack,eventData:JSON.stringify(t.data),event:JSON.stringify(t),eventOrigin:t.origin,eventSource:t.source?"exists":"null"},n=new Error(`${i.message} - Metadata: ${JSON.stringify(a)}`);throw n.stack=e?.stack,n},0)}}}export{r as W};
