1+ import { sleep } from "bun"
12import consola from "consola"
23
3- import { ENV } from "~/lib/constants"
4- import { _github } from "~/services/api-instance"
4+ import { GITHUB_CLIENT_ID , GITHUB_BASE_URL } from "~/lib/constants"
55
66interface DeviceCodeResponse {
77 device_code : string
@@ -18,42 +18,52 @@ interface AccessTokenResponse {
1818}
1919
2020export async function getGitHubToken ( ) {
21- const response = await _github < DeviceCodeResponse > ( " /login/device/code" , {
21+ const response = await fetch ( ` ${ GITHUB_BASE_URL } /login/device/code` , {
2222 method : "POST" ,
23- body : {
24- client_id : ENV . GITHUB_CLIENT_ID ,
25- scope : ENV . GITHUB_OAUTH_SCOPES ,
26- } ,
23+ body : JSON . stringify ( {
24+ client_id : GITHUB_CLIENT_ID ,
25+ } ) ,
2726 } )
2827
29- consola . info (
30- `Please enter the code "${ response . user_code } " in ${ response . verification_uri } ` ,
31- )
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 } ` )
3238
3339 while ( true ) {
34- const pollResponse = await _github < AccessTokenResponse > (
35- " /login/oauth/access_token" ,
40+ const response = await fetch (
41+ ` ${ GITHUB_BASE_URL } /login/oauth/access_token` ,
3642 {
3743 method : "POST" ,
38- body : {
39- client_id : ENV . GITHUB_CLIENT_ID ,
40- device_code : response . device_code ,
44+ body : JSON . stringify ( {
45+ client_id : GITHUB_CLIENT_ID ,
46+ device_code,
4147 grant_type : "urn:ietf:params:oauth:grant-type:device_code" ,
42- } ,
48+ } ) ,
4349 } ,
4450 )
4551
46- if ( pollResponse . access_token ) {
47- consola . info (
48- `Got token ${ pollResponse . access_token . replaceAll ( / ./ g, "*" ) } ` ,
49- )
50- return pollResponse
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+ }
60+
61+ const { access_token } = ( await response . json ( ) ) as AccessTokenResponse
62+
63+ if ( access_token ) {
64+ return access_token
5165 } else {
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- await new Promise ( ( resolve ) =>
55- setTimeout ( resolve , ( response . interval + 1 ) * 1000 ) ,
56- )
66+ await sleep ( sleepDuration )
5767 }
5868 }
5969}
0 commit comments