function h(n,e=[]){return Object.entries(n).reduce((r,[s,t])=>((t||e.includes(s))&&(r[s]=t),r),{})}function a(n){return new Promise(e=>setTimeout(e,n))}function l(n,e){const r=Math.floor(Math.random()*(e-n+1))+n;return a(r)}class u{role;listeners;constructor(e){this.role=e,this.listeners=new Map,chrome.runtime.onMessage.addListener((r,s,t)=>{if(r?.type&&this.listeners.has(r.type))return this.listeners.get(r.type)(r.payload,s,t),!0})}on(e,r){this.listeners.set(e,r)}send(e,r,s){const t={from:this.role,to:e,type:r,payload:s};(this.role==="popup"||this.role==="content")&&chrome.runtime.sendMessage(t),this.role==="background"&&(e==="content"?chrome.tabs.query({active:!0,currentWindow:!0},o=>{o[0]?.id&&chrome.tabs.sendMessage(o[0].id,t,()=>{chrome.runtime.lastError&&console.warn("Không gửi được tới content script:",chrome.runtime.lastError.message)})}):e==="popup"&&chrome.runtime.sendMessage(t,()=>{chrome.runtime.lastError&&console.warn("Không gửi được tới popup:",chrome.runtime.lastError.message)}))}sendToTab(e,r,s){if(this.role!=="background")throw new Error("sendToTab chỉ được gọi từ background");const t={from:this.role,to:"content",type:r,payload:s};chrome.tabs.sendMessage(e,t,()=>{chrome.runtime.lastError&&console.warn(`Không gửi được tới content script ở tab ${e}:`,chrome.runtime.lastError.message)})}waitForMessage(e,r=3e4){return new Promise((s,t)=>{let o;const i=c=>{clearTimeout(o),this.off(e,i),s(c)};o=setTimeout(()=>{this.off(e,i),t(new Error(`Timeout khi chờ message: ${e}`))},r),this.on(e,i)})}off(e,r){this.listeners.get(e)===r&&this.listeners.delete(e)}}export{u as M,l as a,a as d,h as r};
