import ky, { type KyInstance } from "ky"; import { AuthenticationError } from "../errors.js"; export const DEFAULT_ASSIST_PLATFORM_API_URL = "https://unity.ekuaibao.com/api"; export interface AssistPlatformClientOptions { token: string; baseUrl?: string; hoseAccessToken?: string; timeout?: number; } export function createAssistPlatformClient(options: AssistPlatformClientOptions): KyInstance { if (!options.token || !options.token.trim()) { throw new AuthenticationError("缺少协助平台凭证 Token,请先登录协助平台"); } const baseUrl = options.baseUrl || DEFAULT_ASSIST_PLATFORM_API_URL; const cookieParts: string[] = []; if (options.hoseAccessToken) { cookieParts.push(`hose-access-token=${options.hoseAccessToken}`); } return ky.create({ prefix: baseUrl, timeout: options.timeout ?? 30000, headers: { accept: "application/json", "content-type": "application/json;charset=UTF-8", token: options.token.trim(), referer: "https://unity.ekuaibao.com/platform-charge/index.html", ...(cookieParts.length > 0 ? { cookie: cookieParts.join("; ") } : {}), }, hooks: { afterResponse: [ async ({ response }) => { if (response.status === 401 || response.status === 403) { throw new AuthenticationError("协助平台凭证已过期或无效,请重新登录协助平台"); } const contentType = response.headers.get("content-type"); if (contentType && contentType.includes("application/json")) { try { const clone = response.clone(); const json = (await clone.json()) as any; if ( json?.errorCode === 403 || (typeof json?.errorMessage === "string" && json.errorMessage.includes("token过期")) ) { throw new AuthenticationError( "协助平台凭证已过期或无效,请运行: hose-use assist-platform login 重新扫码登录" ); } } catch (err) { if (err instanceof AuthenticationError) throw err; } } return response; }, ], }, }); }