add files
Browse filesFiles changed (3)
- .gitignore+5-2
- frontend/src/lib/api.tsAdded+177
- frontend/src/lib/auth.tsAdded+192
13 unmodified lines141516171819202113 unmodified linesdownloads/eggs/.eggs/lib/lib64/parts/sdist/var/13 unmodified lines141516171819202122232413 unmodified linesdownloads/eggs/.eggs/# Ignore Python lib directories but NOT frontend/src/lib/lib//lib64/venv/lib/venv/lib64/parts/sdist/var/
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177// API client for AnyCoder backend
import axios, { AxiosInstance } from 'axios';import type { Model, AuthStatus, CodeGenerationRequest, DeploymentRequest, DeploymentResponse, Language,} from '@/types';
// Use relative URLs in production (Next.js rewrites will proxy to backend)// In local dev without rewrites, use localhost:8000const API_URL = process.env.NEXT_PUBLIC_API_URL || (typeof window !== 'undefined' && window.location.hostname !== 'localhost' ? '' // Use relative URLs in production (proxied by Next.js) : 'http://localhost:8000'); // Local development
class ApiClient { private client: AxiosInstance; private token: string | null = null;
constructor() { this.client = axios.create({ baseURL: API_URL, headers: { 'Content-Type': 'application/json', }, });
// Add auth token to requests if available this.client.interceptors.request.use((config) => { if (this.token) { config.headers.Authorization = `Bearer ${this.token}`; } return config; });
// Load token from localStorage on client side if (typeof window !== 'undefined') { this.token = localStorage.getItem('hf_oauth_token'); } }
setToken(token: string | null) { this.token = token; // Note: OAuth token is stored by auth.ts, not here // We just keep it in memory for API calls }
getToken(): string | null { return this.token; }
async getModels(): Promise<Model[]> { const response = await this.client.get<Model[]>('/api/models'); return response.data; }
async getLanguages(): Promise<{ languages: Language[] }> { const response = await this.client.get<{ languages: Language[] }>('/api/languages'); return response.data; }
async getAuthStatus(): Promise<AuthStatus> { try { const response = await this.client.get<AuthStatus>('/api/auth/status'); return response.data; } catch (error) { return { authenticated: false, message: 'Not authenticated', }; } }
// Stream-based code generation using EventSource (Server-Sent Events) generateCodeStream( request: CodeGenerationRequest, onChunk: (content: string) => void, onComplete: (code: string) => void, onError: (error: string) => void ): () => void { const url = new URL('/api/generate', API_URL); const eventSource = new EventSource( url.toString() + '?' + new URLSearchParams({ query: request.query, language: request.language, model_id: request.model_id, provider: request.provider, }) );
eventSource.onmessage = (event) => { try { const data = JSON.parse(event.data); if (data.type === 'chunk' && data.content) { onChunk(data.content); } else if (data.type === 'complete' && data.code) { onComplete(data.code); eventSource.close(); } else if (data.type === 'error') { onError(data.message || 'Unknown error occurred'); eventSource.close(); } } catch (error) { console.error('Error parsing SSE data:', error); } };
eventSource.onerror = (error) => { console.error('EventSource error:', error); onError('Connection error occurred'); eventSource.close(); };
// Return cleanup function return () => { eventSource.close(); }; }
// Alternative: WebSocket-based generation generateCodeWebSocket( request: CodeGenerationRequest, onChunk: (content: string) => void, onComplete: (code: string) => void, onError: (error: string) => void ): WebSocket { const wsUrl = API_URL.replace('http', 'ws') + '/ws/generate'; const ws = new WebSocket(wsUrl);
ws.onopen = () => { ws.send(JSON.stringify(request)); };
ws.onmessage = (event) => { try { const data = JSON.parse(event.data); if (data.type === 'chunk' && data.content) { onChunk(data.content); } else if (data.type === 'complete' && data.code) { onComplete(data.code); ws.close(); } else if (data.type === 'error') { onError(data.message || 'Unknown error occurred'); ws.close(); } } catch (error) { console.error('Error parsing WebSocket data:', error); } };
ws.onerror = (error) => { console.error('WebSocket error:', error); onError('Connection error occurred'); };
return ws; }
async deploy(request: DeploymentRequest): Promise<DeploymentResponse> { const response = await this.client.post<DeploymentResponse>('/api/deploy', request); return response.data; }
logout() { this.token = null; }}
// Export singleton instanceexport const apiClient = new ApiClient();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192// HuggingFace OAuth authentication utilitiesimport { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";
const STORAGE_KEY = 'hf_oauth_token';const USER_INFO_KEY = 'hf_user_info';const DEV_MODE_KEY = 'hf_dev_mode';
// Check if we're in development mode (localhost)const isDevelopment = typeof window !== 'undefined' && (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
export interface OAuthUserInfo { id: string; name: string; preferredUsername?: string; avatarUrl?: string;}
export interface OAuthResult { accessToken: string; accessTokenExpiresAt: Date; userInfo: OAuthUserInfo;}
/** * Initialize OAuth and check if user is logged in * Returns OAuth result if user is already logged in */export async function initializeOAuth(): Promise<OAuthResult | null> { try { // In development mode, check for dev mode login first if (isDevelopment && isDevModeEnabled()) { const storedToken = getStoredToken(); const storedUserInfo = getStoredUserInfo(); if (storedToken && storedUserInfo) { return { accessToken: storedToken, accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), userInfo: storedUserInfo, }; } return null; } // Check if we're handling an OAuth redirect const oauthResult = await oauthHandleRedirectIfPresent(); if (oauthResult) { // Store the OAuth result storeOAuthData(oauthResult); return oauthResult; } // Check if we have stored credentials const storedToken = getStoredToken(); const storedUserInfo = getStoredUserInfo(); if (storedToken && storedUserInfo) { return { accessToken: storedToken, accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // Assume 24h userInfo: storedUserInfo, }; } return null; } catch (error) { console.error('OAuth initialization error:', error); return null; }}
/** * Redirect to HuggingFace OAuth login page */export async function loginWithHuggingFace(): Promise<void> { try { const loginUrl = await oauthLoginUrl({ // Redirect back to the current page redirectUrl: window.location.href, // Request scopes - adjust as needed scopes: "openid profile inference-api", }); window.location.href = loginUrl; } catch (error) { console.error('Failed to initiate OAuth login:', error); throw new Error('Failed to start login process'); }}
/** * Logout and clear stored credentials */export function logout(): void { if (typeof window !== 'undefined') { localStorage.removeItem(STORAGE_KEY); localStorage.removeItem(USER_INFO_KEY); localStorage.removeItem(DEV_MODE_KEY); }}
/** * Store OAuth data in localStorage */function storeOAuthData(result: OAuthResult): void { if (typeof window !== 'undefined') { localStorage.setItem(STORAGE_KEY, result.accessToken); localStorage.setItem(USER_INFO_KEY, JSON.stringify(result.userInfo)); }}
/** * Get stored access token */export function getStoredToken(): string | null { if (typeof window !== 'undefined') { return localStorage.getItem(STORAGE_KEY); } return null;}
/** * Get stored user info */export function getStoredUserInfo(): OAuthUserInfo | null { if (typeof window !== 'undefined') { const userInfoStr = localStorage.getItem(USER_INFO_KEY); if (userInfoStr) { try { return JSON.parse(userInfoStr); } catch { return null; } } } return null;}
/** * Check if user is authenticated */export function isAuthenticated(): boolean { return getStoredToken() !== null;}
/** * Development mode login (mock authentication) */export function loginDevMode(username: string): OAuthResult { const mockToken = `dev_token_${username}_${Date.now()}`; const mockUserInfo: OAuthUserInfo = { id: `dev_${Date.now()}`, name: username, preferredUsername: username.toLowerCase().replace(/\s+/g, '_'), avatarUrl: `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=random&size=128`, }; const result: OAuthResult = { accessToken: mockToken, accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), userInfo: mockUserInfo, }; // Store the mock data storeOAuthData(result); // Mark as dev mode if (typeof window !== 'undefined') { localStorage.setItem(DEV_MODE_KEY, 'true'); } return result;}
/** * Check if dev mode is enabled */export function isDevModeEnabled(): boolean { if (typeof window !== 'undefined') { return localStorage.getItem(DEV_MODE_KEY) === 'true'; } return false;}
/** * Check if we're in development environment */export function isDevelopmentMode(): boolean { return isDevelopment;}
.gitignore+5-2
frontend/src/lib/api.tsAdded+177
frontend/src/lib/auth.tsAdded+192