( deviceCode: DeviceCodeResponse, )
| 10 | import type { DeviceCodeResponse } from "./get-device-code" |
| 11 | |
| 12 | export async function pollAccessToken( |
| 13 | deviceCode: DeviceCodeResponse, |
| 14 | ): Promise<string> { |
| 15 | // Interval is in seconds, we need to multiply by 1000 to get milliseconds |
| 16 | // I'm also adding another second, just to be safe |
| 17 | const sleepDuration = (deviceCode.interval + 1) * 1000 |
| 18 | consola.debug(`Polling access token with interval of ${sleepDuration}ms`) |
| 19 | |
| 20 | while (true) { |
| 21 | const response = await fetch( |
| 22 | `${GITHUB_BASE_URL}/login/oauth/access_token`, |
| 23 | { |
| 24 | method: "POST", |
| 25 | headers: standardHeaders(), |
| 26 | body: JSON.stringify({ |
| 27 | client_id: GITHUB_CLIENT_ID, |
| 28 | device_code: deviceCode.device_code, |
| 29 | grant_type: "urn:ietf:params:oauth:grant-type:device_code", |
| 30 | }), |
| 31 | }, |
| 32 | ) |
| 33 | |
| 34 | if (!response.ok) { |
| 35 | await sleep(sleepDuration) |
| 36 | consola.error("Failed to poll access token:", await response.text()) |
| 37 | |
| 38 | continue |
| 39 | } |
| 40 | |
| 41 | const json = await response.json() |
| 42 | consola.debug("Polling access token response:", json) |
| 43 | |
| 44 | const { access_token } = json as AccessTokenResponse |
| 45 | |
| 46 | if (access_token) { |
| 47 | return access_token |
| 48 | } else { |
| 49 | await sleep(sleepDuration) |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | interface AccessTokenResponse { |
| 55 | access_token: string |
no test coverage detected
searching dependent graphs…