import{D as e,E as t,U as n,l as r,p as i,z as a}from"./debug-otxXY3j-.js";import{n as o,r as s}from"./analytics-DqMQntaB.js";import{F as c,P as l}from"./git-C0IuvuIy.js";o(),r(),l(),n(),t();function u(e){if(e<6e4)return`${Math.round(e/1e3)}s`;let t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);return n>0?`${t}m ${n}s`:`${t}m`}function d(t){let n=(t.startsWith(`sk-ant-si-`)?t.slice(10):t).split(`.`);if(n.length!==3||!n[1])return null;try{return e(Buffer.from(n[1],`base64url`).toString(`utf8`))}catch{return null}}function f(e){let t=d(e);return typeof t==`object`&&t&&`exp`in t&&typeof t.exp==`number`?t.exp:null}var p=300*1e3,m=1800*1e3,h=3,g=6e4;function _({getAccessToken:e,onRefresh:t,label:n,refreshBufferMs:r=p}){let o=new Map,l=new Map,d=new Map;function _(e){let t=(d.get(e)??0)+1;return d.set(e,t),t}function v(e,t){let a=f(t);if(!a){i(`[${n}:token] Could not decode JWT expiry for sessionId=${e}, token prefix=${t.slice(0,15)}…, keeping existing timer`);return}let s=o.get(e);s&&clearTimeout(s);let c=_(e),l=new Date(a*1e3).toISOString(),d=a*1e3-Date.now()-r;if(d<=0){i(`[${n}:token] Token for sessionId=${e} expires=${l} (past or within buffer), refreshing immediately`),b(e,c);return}i(`[${n}:token] Scheduled token refresh for sessionId=${e} in ${u(d)} (expires=${l}, buffer=${r/1e3}s)`);let p=setTimeout(b,d,e,c);o.set(e,p)}function y(e,t){let a=o.get(e);a&&clearTimeout(a);let s=_(e),c=Math.max(t*1e3-r,3e4);i(`[${n}:token] Scheduled token refresh for sessionId=${e} in ${u(c)} (expires_in=${t}s, buffer=${r/1e3}s)`);let l=setTimeout(b,c,e,s);o.set(e,l)}async function b(r,f){let p;try{p=await e()}catch(e){i(`[${n}:token] getAccessToken threw for sessionId=${r}: ${a(e)}`,{level:`error`})}if(d.get(r)!==f){i(`[${n}:token] doRefresh for sessionId=${r} stale (gen ${f} vs ${d.get(r)}), skipping`);return}if(!p){let e=(l.get(r)??0)+1;if(l.set(r,e),i(`[${n}:token] No OAuth token available for refresh, sessionId=${r} (failure ${e}/${h})`,{level:`error`}),c(`error`,`bridge_token_refresh_no_oauth`),e<h){let e=setTimeout(b,g,r,f);o.set(r,e)}return}l.delete(r),i(`[${n}:token] Refreshing token for sessionId=${r}: new token prefix=${p.slice(0,15)}…`),s(`tengu_bridge_token_refreshed`,{}),t(r,p);let _=setTimeout(b,m,r,f);o.set(r,_),i(`[${n}:token] Scheduled follow-up refresh for sessionId=${r} in ${u(m)}`)}function x(e){_(e);let t=o.get(e);t&&(clearTimeout(t),o.delete(e)),l.delete(e)}function S(){for(let e of d.keys())_(e);for(let e of o.values())clearTimeout(e);o.clear(),l.clear()}return{schedule:v,scheduleFromExpiresIn:y,cancel:x,cancelAll:S}}export{f as n,_ as t};