|
1 | | -import { sleep } from "bun" |
2 | 1 | import consola from "consola" |
3 | 2 |
|
4 | | -import { GITHUB_CLIENT_ID, GITHUB_BASE_URL } from "~/lib/constants" |
5 | | - |
6 | | -interface DeviceCodeResponse { |
7 | | - device_code: string |
8 | | - user_code: string |
9 | | - verification_uri: string |
10 | | - expires_in: number |
11 | | - interval: number |
12 | | -} |
13 | | - |
14 | | -interface AccessTokenResponse { |
15 | | - access_token: string |
16 | | - token_type: string |
17 | | - scope: string |
18 | | -} |
| 3 | +import { getDeviceCode } from "../get-device-code" |
| 4 | +import { pollAccessToken } from "../poll-access-token" |
19 | 5 |
|
20 | 6 | export async function getGitHubToken() { |
21 | | - const response = await fetch(`${GITHUB_BASE_URL}/login/device/code`, { |
22 | | - method: "POST", |
23 | | - body: JSON.stringify({ |
24 | | - client_id: GITHUB_CLIENT_ID, |
25 | | - }), |
26 | | - }) |
27 | | - |
28 | | - if (!response.ok) { |
29 | | - throw new Error("Failed to get device code", { |
30 | | - cause: await response.json(), |
31 | | - }) |
32 | | - } |
33 | | - |
34 | | - const { user_code, verification_uri, device_code, interval } = |
35 | | - (await response.json()) as DeviceCodeResponse |
36 | | - |
37 | | - consola.info(`Please enter the code "${user_code}" in ${verification_uri}`) |
38 | | - |
39 | | - while (true) { |
40 | | - const response = await fetch( |
41 | | - `${GITHUB_BASE_URL}/login/oauth/access_token`, |
42 | | - { |
43 | | - method: "POST", |
44 | | - body: JSON.stringify({ |
45 | | - client_id: GITHUB_CLIENT_ID, |
46 | | - device_code, |
47 | | - grant_type: "urn:ietf:params:oauth:grant-type:device_code", |
48 | | - }), |
49 | | - }, |
50 | | - ) |
51 | | - |
52 | | - // Interval is in seconds, we need to multiply by 1000 to get milliseconds |
53 | | - // I'm also adding another second, just to be safe |
54 | | - const sleepDuration = (interval + 1) * 1000 |
55 | | - |
56 | | - if (!response.ok) { |
57 | | - await sleep(sleepDuration) |
58 | | - continue |
59 | | - } |
| 7 | + const response = await getDeviceCode() |
60 | 8 |
|
61 | | - const { access_token } = (await response.json()) as AccessTokenResponse |
| 9 | + consola.info( |
| 10 | + `Please enter the code "${response.user_code}" in ${response.verification_uri}`, |
| 11 | + ) |
62 | 12 |
|
63 | | - if (access_token) { |
64 | | - return access_token |
65 | | - } else { |
66 | | - await sleep(sleepDuration) |
67 | | - } |
68 | | - } |
| 13 | + return await pollAccessToken(response) |
69 | 14 | } |
0 commit comments