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 type ApiFetchInit = RequestInit & { pbToken?: string | null } export async function apiFetch( bind: BindPayload | null, path: string, init?: ApiFetchInit, ): Promise { if (!bind) { return Promise.reject(new Error('尚未绑定 PC(请先在「配对」扫码)')) } const { pbToken, ...rest } = init ?? {} const headers = new Headers(rest.headers) if (bind.token?.trim()) { headers.set('Authorization', `Bearer ${bind.token.trim()}`) } if (pbToken?.trim()) { headers.set('X-PB-Token', pbToken.trim()) } return fetch(joinUrl(bind.baseUrl, path), { ...rest, headers }) } export async function apiJson(bind: BindPayload | null, path: string, init?: ApiFetchInit): 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 }