import type { BindPayload } from './types' function joinUrl(base: string, path: string): string { const b = base.replace(/\/$/, '') const p = path.startsWith('/') ? path : `/${path}` return `${b}${p}` } export async function apiFetch( bind: BindPayload | null, path: string, init?: RequestInit, ): Promise { if (!bind) { return Promise.reject(new Error('尚未绑定 PC(请先在「配对」扫码)')) } const headers = new Headers(init?.headers) if (bind.token?.trim()) { headers.set('Authorization', `Bearer ${bind.token.trim()}`) } return fetch(joinUrl(bind.baseUrl, path), { ...init, headers }) } export async function apiJson(bind: BindPayload | null, path: string, init?: RequestInit): Promise { const res = await apiFetch(bind, path, init) if (!res.ok) { const t = await res.text() throw new Error(t || `HTTP ${res.status}`) } return res.json() as Promise }