@@ -3,6 +3,9 @@ import fs from "node:fs/promises"
33
44import { PATHS } from "~/lib/paths"
55import { getCopilotToken } from "~/services/copilot/get-token/copilot-token"
6+ import { getDeviceCode } from "~/services/github/get-device-code"
7+ import { getGitHubUser } from "~/services/github/get-user/service"
8+ import { pollAccessToken } from "~/services/github/poll-access-token"
69
710import { state } from "./state"
811
@@ -12,7 +15,7 @@ export const readGithubToken = () =>
1215export const writeGithubToken = ( token : string ) =>
1316 fs . writeFile ( PATHS . GITHUB_TOKEN_PATH , token )
1417
15- export const setupCopilotTokenRefresh = async ( ) => {
18+ export const setupCopilotToken = async ( ) => {
1619 const { token, refresh_in } = await getCopilotToken ( )
1720 state . copilotToken = token
1821
@@ -30,40 +33,31 @@ export const setupCopilotTokenRefresh = async () => {
3033 } , refreshInterval )
3134}
3235
33- // Simple token manager with basic encapsulation
34- export const tokenService = {
35- // Private token storage
36- _tokens : {
37- github : undefined as string | undefined ,
38- copilot : undefined as string | undefined ,
39- } ,
36+ export async function setupGitHubToken ( ) : Promise < void > {
37+ const githubToken = await readGithubToken ( )
4038
41- // Get Copilot token
42- getCopilotToken ( ) : string | undefined {
43- return this . _tokens . copilot
44- } ,
39+ if ( githubToken ) {
40+ state . githubToken = githubToken
41+ await logUser ( )
4542
46- // Set Copilot token
47- setCopilotToken ( token : string ) : void {
48- this . _tokens . copilot = token
49- } ,
43+ return
44+ }
5045
51- // Initialize Copilot token with auto-refresh
52- async initCopilotToken ( ) : Promise < void > {
53- const { token, refresh_in } = await getCopilotToken ( )
54- this . setCopilotToken ( token )
46+ consola . info ( "Not logged in, getting new access token" )
47+ const response = await getDeviceCode ( )
5548
56- // Set up refresh timer
57- const refreshInterval = ( refresh_in - 60 ) * 1000
58- setInterval ( async ( ) => {
59- consola . start ( "Refreshing Copilot token" )
60- try {
61- const { token : newToken } = await getCopilotToken ( )
62- this . setCopilotToken ( newToken )
63- consola . success ( "Copilot token refreshed" )
64- } catch ( error ) {
65- consola . error ( "Failed to refresh Copilot token:" , error )
66- }
67- } , refreshInterval )
68- } ,
49+ consola . info (
50+ `Please enter the code "${ response . user_code } " in ${ response . verification_uri } ` ,
51+ )
52+
53+ const token = await pollAccessToken ( response )
54+ await writeGithubToken ( token )
55+ state . githubToken = token
56+
57+ await logUser ( )
58+ }
59+
60+ async function logUser ( ) {
61+ const user = await getGitHubUser ( )
62+ consola . info ( `Logged in as ${ JSON . stringify ( user . login ) } \n` )
6963}
0 commit comments