UNPKG

codebrag

Version:

CLI tool for tracking Claude Code usage and leaderboard participation

64 lines (53 loc) 1.66 kB
import { getValidAccessToken } from '../auth/tokens.js'; import { loadConfig } from './config.js'; import { API_BASE_URL } from './constants.js'; /** * Make an authenticated API request * @param {string} path - API path (e.g., '/api/user/stats') * @param {Object} options - Fetch options * @returns {Promise<Response>} */ export async function authenticatedFetch(path, options = {}) { const config = await loadConfig(); const endpoint = config.endpoint || API_BASE_URL; // Get valid tokens const tokens = await getValidAccessToken(); // Build full URL const url = `${endpoint}${path}`; // Pass OAuth tokens in headers for backend to handle authentication const headers = { ...options.headers, 'Content-Type': 'application/json', 'X-OAuth-Token': tokens.oauth_token, 'X-OAuth-Token-Secret': tokens.oauth_token_secret }; // Make the request const response = await fetch(url, { ...options, headers }); // If we get a 401, authentication failed if (response.status === 401) { throw new Error('Authentication failed. Please run "codebrag auth" to re-authenticate.'); } return response; } /** * Make an API request without authentication * @param {string} path - API path * @param {Object} options - Fetch options * @returns {Promise<Response>} */ export async function apiFetch(path, options = {}) { const config = await loadConfig(); const endpoint = config.endpoint || API_BASE_URL; const url = `${endpoint}${path}`; const headers = { 'Content-Type': 'application/json', ...options.headers }; return fetch(url, { ...options, headers }); }