* Execute an OAuth-authenticated request with a single retry on 401. * On 401, attempts token refresh via handleOAuth401Error (same pattern as * withRetry.ts for v1/messages). If refresh succeeds, retries the request * once with the new token. If refresh fails or the retry also returns 401,
(
fn: (accessToken: string) => Promise<{ status: number; data: T }>,
context: string,
)
| 104 | * the 401 response is returned for handleErrorStatus to throw BridgeFatalError. |
| 105 | */ |
| 106 | async function withOAuthRetry<T>( |
| 107 | fn: (accessToken: string) => Promise<{ status: number; data: T }>, |
| 108 | context: string, |
| 109 | ): Promise<{ status: number; data: T }> { |
| 110 | const accessToken = resolveAuth() |
| 111 | const response = await fn(accessToken) |
| 112 | |
| 113 | if (response.status !== 401) { |
| 114 | return response |
| 115 | } |
| 116 | |
| 117 | if (!deps.onAuth401) { |
| 118 | debug(`[bridge:api] ${context}: 401 received, no refresh handler`) |
| 119 | return response |
| 120 | } |
| 121 | |
| 122 | // Attempt token refresh — matches the pattern in withRetry.ts |
| 123 | debug(`[bridge:api] ${context}: 401 received, attempting token refresh`) |
| 124 | const refreshed = await deps.onAuth401(accessToken) |
| 125 | if (refreshed) { |
| 126 | debug(`[bridge:api] ${context}: Token refreshed, retrying request`) |
| 127 | const newToken = resolveAuth() |
| 128 | const retryResponse = await fn(newToken) |
| 129 | if (retryResponse.status !== 401) { |
| 130 | return retryResponse |
| 131 | } |
| 132 | debug(`[bridge:api] ${context}: Retry after refresh also got 401`) |
| 133 | } else { |
| 134 | debug(`[bridge:api] ${context}: Token refresh failed`) |
| 135 | } |
| 136 | |
| 137 | // Refresh failed — return 401 for handleErrorStatus to throw |
| 138 | return response |
| 139 | } |
| 140 | |
| 141 | return { |
| 142 | async registerBridgeEnvironment( |
no test coverage detected