• Schedules a token refresh before the current token expires

    Sets up an automatic refresh operation that will execute shortly before the current access token expires. The exact timing is controlled by the REFRESH_MARGIN constant, which ensures the token is refreshed with sufficient time to prevent any authentication gaps.

    This function:

    1. Clears any existing refresh timer to prevent multiple refreshes
    2. Calculates the optimal time to refresh (token expiry - safety margin)
    3. Sets up a timer to execute the refresh at the calculated time
    4. Stores the timer reference for future management

    Parameters

    • expiresIn: number

      Number of seconds until the current token expires

    Returns void

    // Schedule a refresh for a token with 1 hour validity
    scheduleTokenRefresh(3600);

    // This will automatically refresh the token 5 minutes before expiry
    // (assuming REFRESH_MARGIN is set to 300 seconds)
    export function scheduleTokenRefresh(expiresIn: number): void {
    // Clear any existing timer
    clearRefreshTimer();

    // Calculate refresh time (token expiry - safety margin)
    const refreshTime = Math.max(0, expiresIn - REFRESH_MARGIN) * 1000;

    // Schedule refresh
    const timer = setTimeout(refreshAccessToken, refreshTime);
    setRefreshTimer(timer);

    saveLog(`Token refresh scheduled in ${refreshTime / 1000} seconds`, "DEBUG");
    }