export async function ensureValidToken(): Promise<void> {
ensureCredentialsSet();
// Only refresh if token is invalid or about to expire (within refresh margin)
const now = Date.now();
const tokenTimeRemaining = tokenExpiryTime - now;
const isTokenAboutToExpire =
tokenTimeRemaining > 0 && tokenTimeRemaining < TOKEN_REFRESH_MARGIN * 1000;
if (
!accessToken ||
!tokenExpiryTime ||
tokenExpiryTime <= now ||
isTokenAboutToExpire
) {
if (refreshToken) {
try {
await retryApiCall(async () => {
await refreshAccessToken();
}, 3);
} catch {
throw new Error(
"Access token expired and refresh failed. Re-authorization required.",
);
}
} else {
throw new Error("No valid access token. Authorization required.");
}
}
}
Ensures a valid access token is available, refreshing if necessary