var I=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function R(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}),r}const m="https://api.feeshield.dev",w=200,_=5e3,l=[];function S(...e){return e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ").slice(0,500)}function f(e,t,...r){const n={ts:new Date().toISOString(),level:e,source:t,msg:S(...r)};l.push(n),l.length>w&&l.shift()}function T(){if(l.length===0)return;const e=l.splice(0,l.length);fetch(`${m}/api/diagnostics`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"console_logs",entries:e})}).catch(()=>{})}setInterval(T,_);const i={log:(...e)=>{f("log","sw",...e)},warn:(...e)=>{f("warn","sw",...e)},error:(...e)=>{f("error","sw",...e)}},a="feeshield_auth_token",c="feeshield_refresh_token",k="feeshield_auth";let u=null;var p;const s=typeof chrome<"u"&&((p=chrome.storage)==null?void 0:p.local);async function b(){return s?new Promise(e=>{chrome.storage.local.get(a,t=>{e(t[a]||null)})}):localStorage.getItem(a)}async function O(){return s?new Promise(e=>{chrome.storage.local.get(c,t=>{e(t[c]||null)})}):localStorage.getItem(c)}async function A(e,t){if(!s){localStorage.setItem(a,e),t&&localStorage.setItem(c,t);return}const r={[a]:e};return t&&(r[c]=t),new Promise(n=>{chrome.storage.local.set(r,()=>{y(!0),n()})})}async function P(){if(!s){localStorage.removeItem(a),localStorage.removeItem(c);return}return new Promise(e=>{chrome.storage.local.remove([a,c,k],()=>{y(!1),e()})})}function y(e){if(!s)return;const t={type:"AUTH_STATE_CHANGED",isAuthenticated:e};chrome.runtime.sendMessage(t,()=>{chrome.runtime.lastError}),chrome.tabs.query({},r=>{for(const n of r)n.id&&chrome.tabs.sendMessage(n.id,t).catch(()=>{})})}function h(){return u||(u=E().finally(()=>{u=null}),u)}async function E(){const e=await O();if(!e)return null;try{const t=await fetch(`${m}/api/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!t.ok)return await P(),null;const r=await t.json();return await A(r.accessToken,r.refreshToken),r.accessToken}catch{return null}}function j(e){try{const t=e.split(".");if(t.length!==3)return null;const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=r+"=".repeat((4-r.length%4)%4),o=JSON.parse(atob(n));return typeof o.exp=="number"?o.exp:null}catch{return null}}async function v(){const e=await b();if(!e)return h();const t=j(e);if(t!==null){const r=Date.now()/1e3;if(t-r<60){i.log(`Token expires in ${Math.round(t-r)}s — proactively refreshing`);const n=await h();return n||(t>r?e:null)}}return e}async function N(e,t){const r=await v();if(!r)return new Response(JSON.stringify({error:"Authentication required"}),{status:401,headers:{"Content-Type":"application/json"}});const n=new Headers(t==null?void 0:t.headers);n.set("Authorization",`Bearer ${r}`);const o=await fetch(e,{...t,headers:n});if(o.status===401){i.log(`401 from ${e} — attempting token refresh`);const g=await h();if(!g)return o;const d=new Headers(t==null?void 0:t.headers);return d.set("Authorization",`Bearer ${g}`),fetch(e,{...t,headers:d})}return o}async function H(e){const t=`${e}_auth_token`;return s?new Promise(r=>{chrome.storage.local.get(t,n=>{r(n[t]||null)})}):localStorage.getItem(t)}async function M(e,t){const r=`${e}_auth_token`;if(!s){localStorage.setItem(r,t);return}return new Promise(n=>{chrome.storage.local.set({[r]:t},()=>{i.log(`${e} token stored`),n()})})}async function C(e){const t=`${e}_auth_token`;if(!s){localStorage.removeItem(t);return}return new Promise(r=>{chrome.storage.local.remove(t,()=>{i.log(`${e} token cleared`),r()})})}export{m as A,$ as a,b,P as c,R as d,i as e,N as f,v as g,H as h,I as i,M as j,C as k,f as r,A as s};
