export const TOKEN_STORAGE_KEY = "thtuanit_auth_token"; export const LEGACY_TOKEN_STORAGE_KEY = "hf_auth_token"; export function getBackendOrigin(): string { if (typeof window !== "undefined") { if (window.location.port === "3000") { return `${window.location.protocol}//${window.location.hostname}:8080`; } return window.location.origin; } return process.env.BACKEND_URL || "http://127.0.0.1:8080"; } export class ApiClientError extends Error { status: number; code?: string; constructor(message: string, status: number, code?: string) { super(message); this.name = "ApiClientError"; this.status = status; this.code = code; } } export interface ApiRequestOptions extends Omit { token?: string | null; body?: BodyInit | Record | null; } export async function apiRequest( path: string, options: ApiRequestOptions = {}, ): Promise { const { token, headers, body, ...rest } = options; const finalHeaders = new Headers(headers); if (token) { finalHeaders.set("Authorization", `Bearer ${token}`); } let finalBody: BodyInit | undefined; if (body instanceof FormData || body instanceof Blob || typeof body === "string") { finalBody = body; } else if (body && typeof body === "object") { finalHeaders.set("Content-Type", "application/json"); finalBody = JSON.stringify(body); } const response = await fetch(`${getBackendOrigin()}${path}`, { ...rest, headers: finalHeaders, body: finalBody, credentials: "include", }); const text = await response.text(); let parsed: Record | null = null; if (text) { try { parsed = JSON.parse(text) as Record; } catch { parsed = null; } } if (!response.ok) { const message = (parsed?.detail as string) || (parsed?.error as string) || response.statusText || `HTTP ${response.status}`; throw new ApiClientError( message, response.status, typeof parsed?.error === "string" ? parsed.error : undefined, ); } return (parsed ?? {}) as T; } export function buildDownloadUrl( path: string, token: string | null, inline = false, ): string { const params = new URLSearchParams({ path }); if (token) params.set("token", token); if (inline) params.set("inline", "1"); return `${getBackendOrigin()}/api/download?${params.toString()}`; } export function buildSharePageUrl(shareId: string): string { if (typeof window !== "undefined") { return `${window.location.origin}/share?id=${encodeURIComponent(shareId)}`; } return `/share?id=${encodeURIComponent(shareId)}`; } export function buildPublicShareDownloadUrl( shareId: string, visitorToken: string, inline = false, ): string { const params = new URLSearchParams({ id: shareId }); if (visitorToken) params.set("visitor_token", visitorToken); if (inline) params.set("inline", "1"); return `${getBackendOrigin()}/api/public/share/download?${params.toString()}`; }