Spaces:
Paused
Paused
File size: 3,440 Bytes
5eb4857 5df0bfe aba5cde cc4d4a7 aba5cde cc4d4a7 5df0bfe aba5cde cc4d4a7 aba5cde 5eb4857 cc4d4a7 5eb4857 1818cda 3aef1db 1818cda 5eb4857 4640159 5eb4857 4640159 5eb4857 accf280 4640159 5eb4857 b7980f7 4640159 5eb4857 4640159 5eb4857 b7980f7 5eb4857 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | import axios from 'axios';
const rawBaseUrl = import.meta.env.VITE_API_URL ||
(import.meta.env.DEV ? 'http://localhost:8000/api/v1' : '/api/v1');
// Intelligent URL Normalization:
let sanitizedBaseUrl = rawBaseUrl.trim();
// Ensure absolute URLs have a protocol and /api/v1 suffix
if (sanitizedBaseUrl.startsWith('http')) {
if (!sanitizedBaseUrl.includes('/api/')) {
sanitizedBaseUrl = sanitizedBaseUrl.endsWith('/') ? `${sanitizedBaseUrl}api/v1` : `${sanitizedBaseUrl}/api/v1`;
}
}
// Final trailing slash for clean joins
const BASE_URL = sanitizedBaseUrl.endsWith('/') ? sanitizedBaseUrl : `${sanitizedBaseUrl}/`;
// Logging for Frontend Debugging
console.log(`[API_CLIENT] Initializing...`);
console.log(`[API_CLIENT] Raw URL: ${rawBaseUrl}`);
console.log(`[API_CLIENT] Sanitized BASE_URL: ${BASE_URL}`);
export const api = axios.create({
baseURL: BASE_URL,
});
/**
* Generates a WebSocket URL based on the current environment and API settings.
* Handles HTTP/S protocol switching and domain resolution for production tunnels.
*/
export const getWsUrl = (path: string) => {
// Use the API's base URL as the source of truth for the domain
// We use window.location.origin as a fallback for relative BASE_URL paths
const apiBase = new URL(BASE_URL, window.location.origin);
const protocol = apiBase.protocol === 'https:' ? 'wss:' : 'ws:';
// WebSockets are served from the root of the API server (no /api/v1 prefix)
const host = apiBase.host;
// Clean forward slash concatenation
const cleanPath = path.startsWith('/') ? path : `/${path}`;
return `${protocol}//${host}${cleanPath}`;
};
let portalType: 'customer' | 'internal' | null = null;
/**
* Returns a portal-scoped storage key to prevent session collision
* when hosting multiple portals on the same domain (e.g. Hugging Face Spaces).
*/
export const getStorageKey = (key: string) => {
return portalType ? `${portalType}_${key}` : key;
};
export const setPortalType = (type: 'customer' | 'internal') => {
portalType = type;
console.log(`[API_CLIENT] Portal Context: ${type}`);
};
api.interceptors.request.use((config) => {
// Ensure trailing slash on all endpoints to prevent 307 redirects (Mixed Content prevention)
if (config.url && !config.url.endsWith('/') && !config.url.includes('?')) {
config.url = `${config.url}/`;
}
const token = localStorage.getItem(getStorageKey('token'));
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
if (portalType) {
config.headers['X-Nexus-Portal'] = portalType;
}
return config;
});
api.interceptors.response.use(
(response) => response,
(error) => {
const status = error.response?.status;
if (status === 401) {
const prevToken = localStorage.getItem(getStorageKey('token'));
if (prevToken) {
localStorage.removeItem(getStorageKey('token'));
localStorage.removeItem(getStorageKey('refresh_token'));
localStorage.removeItem(getStorageKey('user'));
// Portal-agnostic reload: just refresh the current page
// The App.tsx will see the lack of token and show the LoginCard
window.location.reload();
}
}
if (status === 429) {
const retryAfter = error.response?.data?.retry_after_seconds || 60;
console.warn(`[API_CLIENT] Rate limited. Retry after ${retryAfter}s`);
}
return Promise.reject(error);
}
);
export default api;
|