import * as fs from "node:fs/promises"; import { normalizeAnythingLlmBaseUrl } from "./anythingllmClient.js"; const normalizeApiSecret = (raw: string): string => { const trimmed = raw.trim(); const bearerPrefix = /^Bearer\s+/i; return bearerPrefix.test(trimmed) ? trimmed.replace(bearerPrefix, "").trim() : trimmed; }; const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); export const uploadLocalFileToWorkspace = async ( baseUrl: string, apiKey: string, workspaceSlug: string, absoluteFilePath: string, uploadFileName: string, ): Promise => { const normalized = normalizeAnythingLlmBaseUrl(baseUrl); const key = normalizeApiSecret(apiKey); if (key.length === 0) { throw new Error("ANYTHINGLLM_API_KEY is empty"); } const buf = await fs.readFile(absoluteFilePath); const body = new FormData(); body.append("file", new Blob([buf]), uploadFileName); body.append("addToWorkspaces", workspaceSlug); const url = `${normalized}/api/v1/document/upload`; const response = await fetch(url, { method: "POST", headers: { Authorization: `Bearer ${key}`, }, body, }); const text = await response.text(); let parsed: unknown; try { parsed = JSON.parse(text) as unknown; } catch { throw new Error(`document upload: non-JSON response ${response.status}: ${text.slice(0, 300)}`); } if (!response.ok) { throw new Error(`document upload ${response.status}: ${text.slice(0, 500)}`); } if (!isRecord(parsed)) { throw new Error("document upload: invalid JSON body"); } const success = parsed.success; const err = parsed.error; if (success !== true) { const msg = typeof err === "string" ? err : JSON.stringify(err); throw new Error(`document upload failed: ${msg}`); } };