import type { PopoConfig } from "./types.js"; import { resolvePopoCredentials } from "./accounts.js"; import { getAccessToken } from "./auth.js"; export type PopoApiResponse = { code: number; message: string; result?: T; }; /** * Make an authenticated API request to POPO. */ export async function popoRequest(params: { cfg: PopoConfig; method: "GET" | "POST" | "PUT" | "DELETE"; path: string; body?: unknown; }): Promise> { const { cfg, method, path, body } = params; const creds = resolvePopoCredentials(cfg); if (!creds) { throw new Error("POPO credentials not configured"); } const accessToken = await getAccessToken(cfg); const url = `${creds.server}${path}`; const headers: Record = { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json", }; const response = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined, }); if (!response.ok) { throw new Error(`POPO API request failed: ${response.status} ${response.statusText}`); } return (await response.json()) as PopoApiResponse; } /** * Make an authenticated multipart form request to POPO (for file uploads). */ export async function popoUploadRequest(params: { cfg: PopoConfig; path: string; formData: FormData; }): Promise> { const { cfg, path, formData } = params; const creds = resolvePopoCredentials(cfg); if (!creds) { throw new Error("POPO credentials not configured"); } const accessToken = await getAccessToken(cfg); const url = `${creds.server}${path}`; const response = await fetch(url, { method: "POST", headers: { Authorization: `Bearer ${accessToken}`, // Don't set Content-Type for FormData - fetch will set it with boundary }, body: formData, }); if (!response.ok) { throw new Error(`POPO upload request failed: ${response.status} ${response.statusText}`); } return (await response.json()) as PopoApiResponse; } /** * Download a file from POPO. */ export async function popoDownloadRequest(params: { cfg: PopoConfig; path: string; }): Promise<{ buffer: Buffer; contentType?: string }> { const { cfg, path } = params; const creds = resolvePopoCredentials(cfg); if (!creds) { throw new Error("POPO credentials not configured"); } const accessToken = await getAccessToken(cfg); const url = `${creds.server}${path}`; const response = await fetch(url, { method: "GET", headers: { Authorization: `Bearer ${accessToken}`, }, }); if (!response.ok) { throw new Error(`POPO download request failed: ${response.status} ${response.statusText}`); } const buffer = Buffer.from(await response.arrayBuffer()); const contentType = response.headers.get("content-type") || undefined; return { buffer, contentType }; }