import{contextStorage,loadContext}from"#context/container.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";async function resolveScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore(),o=resolveConnectionPrincipal(n,r,a);if(a===void 0)return await r.getToken({connection:i,principal:o});let u=principalKey(o),d=readCachedToken(a,n,u);if(d!==void 0)return d;let f=await r.getToken({connection:i,principal:o});return writeCachedToken(a,n,u,f),f}async function evictScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore();if(a===void 0)return;let s;try{s=resolveConnectionPrincipal(n,r,a),evictCachedToken(a,n,principalKey(s))}catch{return}try{await r.evict?.({connection:i,principal:s})}catch{}}async function completeScopedAuthorization(e){let{scope:i,authorization:a,connection:o}=e;if(!supportsInteractiveAuthorization(a))return!1;let s=getAuthorizationResult(i);if(s===void 0)return!1;let u=a,d=loadContext(),f=resolveConnectionPrincipal(i,u,d),p=await u.completeAuthorization({callbackUrl:s.hookUrl,connection:o,principal:f,resume:s.resume,callback:s.callback});return writeCachedToken(d,i,principalKey(f),p),!0}async function startScopedAuthorization(e){let{scope:t,authorization:r,connection:o}=e;if(!supportsInteractiveAuthorization(r))return;let s=getHookUrl(t);if(s===void 0)return;let c=r,l=resolveConnectionPrincipal(t,c),{challenge:u,resume:d}=await c.startAuthorization({callbackUrl:s,connection:o,principal:l});return requestAuthorization([{challenge:u,hookUrl:s,name:t,resume:d}])}export{completeScopedAuthorization,evictScopedToken,resolveScopedToken,startScopedAuthorization};