import { API_BASE } from "./endpoints" import type { ApiResponse, AstrBotApiResponse } from "../types/api" export type ApiTransport = "plugin-bridge" | "direct-fetch" export type ApiMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" const METHOD_OVERRIDE_KEY = "__imagestudio_method" const METHOD_OVERRIDE_BODY_KEY = "__imagestudio_body" export class ApiClientError extends Error { readonly code: string readonly details: Record constructor(code: string, message: string, details: Record = {}) { super(message) this.name = "ApiClientError" this.code = code this.details = details } } export async function getJson(endpoint: string, query?: Record) { return request(endpoint, { method: "GET", query }) } export async function postJson(endpoint: string, body?: unknown) { return request(endpoint, { method: "POST", body }) } export async function putJson(endpoint: string, body?: unknown) { return request(endpoint, { method: "PUT", body }) } export async function patchJson(endpoint: string, body?: unknown) { return request(endpoint, { method: "PATCH", body }) } export async function deleteJson(endpoint: string, body?: unknown) { return request(endpoint, { method: "DELETE", body }) } export function getApiTransport(): ApiTransport { const bridge = typeof window === "undefined" ? undefined : window.AstrBotPluginPage return bridge && (typeof bridge.apiGet === "function" || typeof bridge.apiPost === "function") ? "plugin-bridge" : "direct-fetch" } export async function request( endpoint: string, options: { method?: ApiMethod query?: Record body?: unknown } = {}, ): Promise { const hasPluginBridge = typeof window !== "undefined" && Boolean(window.AstrBotPluginPage) const bridgePayload = await requestViaPluginBridge(endpoint, options) if (hasPluginBridge) { if (bridgePayload === undefined) { throw new ApiClientError("invalid_api_response", "AstrBot Plugin Page bridge returned no response", { endpoint, method: options.method ?? "GET", transport: "plugin-bridge", }) } return unwrapApiResponse(bridgePayload) } const url = buildUrl(endpoint, options.query) let response: Response try { response = await fetch(url, { method: options.method ?? "GET", headers: options.body === undefined ? undefined : { "Content-Type": "application/json" }, body: options.body === undefined ? undefined : JSON.stringify(options.body), }) } catch (err) { throw new ApiClientError("network_unreachable", "无法连接 ImageStudio 后端接口", { endpoint, transport: "direct-fetch", url, reason: err instanceof Error ? err.message : String(err), }) } const payload = await parseResponsePayload(response, endpoint, url) if (!response.ok && !isApiResponse(payload) && !isAstrBotApiResponse(payload)) { throw new ApiClientError("http_error", `接口请求失败(HTTP ${response.status})`, { endpoint, transport: "direct-fetch", url, status: response.status, status_text: response.statusText, }) } return unwrapApiResponse(payload) } async function requestViaPluginBridge( endpoint: string, options: { method?: ApiMethod query?: Record body?: unknown }, ): Promise | AstrBotApiResponse | undefined> { const bridge = window.AstrBotPluginPage if (!bridge) { return undefined } const method = options.method ?? "GET" if (typeof bridge.ready === "function") { await bridge.ready() } if (method === "GET" && typeof bridge.apiGet === "function") { return bridge.apiGet | AstrBotApiResponse>(endpoint, compactQuery(options.query)) } if (method === "POST" && typeof bridge.apiPost === "function") { return bridge.apiPost | AstrBotApiResponse>(endpoint, options.body) } if (method === "PUT" && typeof bridge.apiPut === "function") { return bridge.apiPut | AstrBotApiResponse>(endpoint, options.body) } if (method === "PATCH" && typeof bridge.apiPatch === "function") { return bridge.apiPatch | AstrBotApiResponse>(endpoint, options.body) } if (method === "DELETE" && typeof bridge.apiDelete === "function") { return bridge.apiDelete | AstrBotApiResponse>(endpoint) } if (["PUT", "PATCH", "DELETE"].includes(method) && typeof bridge.apiPost === "function") { return bridge.apiPost | AstrBotApiResponse>(endpoint, { [METHOD_OVERRIDE_KEY]: method, [METHOD_OVERRIDE_BODY_KEY]: method === "DELETE" ? {} : options.body === undefined ? {} : options.body, }) } throw new ApiClientError("bridge_method_unavailable", `AstrBot Plugin Page bridge does not support ${method}`, { endpoint, method, transport: "plugin-bridge", }) } function unwrapApiResponse(payload: T | ApiResponse | AstrBotApiResponse): T { let current: unknown = payload for (let depth = 0; depth < 4; depth += 1) { if (isApiResponse(current)) { if (!current.ok) { throw new ApiClientError(current.error_code, current.message, current.details ?? {}) } current = current.data continue } if (isAstrBotApiResponse(current)) { if (current.status === "error") { if (isApiResponse(current.data)) { current = current.data continue } throw new ApiClientError( current.error_code || "astrbot_bridge_error", current.message || current.error || "AstrBot Plugin Page bridge request failed", current.details ?? bridgeErrorDetails(current.data), ) } current = current.data continue } return current as T } throw new ApiClientError("invalid_api_response", "API response wrapper nesting is too deep") } async function parseResponsePayload( response: Response, endpoint: string, url: string, ): Promise | AstrBotApiResponse> { const contentType = response.headers.get("content-type") ?? "" const isJson = contentType.includes("application/json") || contentType.includes("+json") if (!isJson) { const preview = (await response.text()).slice(0, 240) throw new ApiClientError("invalid_api_response", "接口返回了非 JSON 响应", { endpoint, transport: "direct-fetch", url, status: response.status, status_text: response.statusText, content_type: contentType, preview, }) } try { return (await response.json()) as T | ApiResponse | AstrBotApiResponse } catch (err) { throw new ApiClientError("invalid_api_response", "接口返回格式不正确", { endpoint, transport: "direct-fetch", url, status: response.status, status_text: response.statusText, content_type: contentType, reason: err instanceof Error ? err.message : String(err), }) } } function isApiResponse(payload: unknown): payload is ApiResponse { if (!payload || typeof payload !== "object" || !("ok" in payload) || typeof payload.ok !== "boolean") { return false } return payload.ok ? "data" in payload : "error_code" in payload && "message" in payload } function isAstrBotApiResponse(payload: unknown): payload is AstrBotApiResponse { if (!payload || typeof payload !== "object" || !("status" in payload)) { return false } return payload.status === "error" || (payload.status === "ok" && "data" in payload) } function bridgeErrorDetails(data: unknown): Record { return data && typeof data === "object" ? { bridge_data: data } : {} } function compactQuery(query?: Record): Record | undefined { if (!query) { return undefined } const compacted: Record = {} for (const [key, value] of Object.entries(query)) { if (value !== undefined) { compacted[key] = value } } return compacted } export function buildUrl(endpoint: string, query?: Record) { const trimmed = endpoint.replace(/^\/+/, "") const url = new URL(`${API_BASE}/${trimmed}`, window.location.origin) for (const [key, value] of Object.entries(query ?? {})) { if (value !== undefined) { url.searchParams.set(key, String(value)) } } return `${url.pathname}${url.search}` }