// lib/directus.ts // Central Directus helpers used by API routes. Minimal hard-coding, robust parsing. const BASE = process.env.DIRECTUS_URL!; const TOKEN_SUBMIT = process.env.DIRECTUS_TOKEN_SUBMIT ?? process.env.DIRECTUS_STATIC_TOKEN ?? process.env.DIRECTUS_TOKEN ?? ""; const PROJECTS_COLLECTION = process.env.DIRECTUS_PROJECTS_COLLECTION || "projects"; if (!BASE) console.warn("[directus] Missing DIRECTUS_URL"); if (!TOKEN_SUBMIT) console.warn("[directus] Missing submit token (DIRECTUS_TOKEN_SUBMIT / DIRECTUS_STATIC_TOKEN / DIRECTUS_TOKEN)"); export function bytesFromMB(mb: number) { return Math.round(mb * 1024 * 1024); } // Read response as text first; parse JSON if present so we never throw // "Unexpected end of JSON input" for empty/HTML bodies. async function parseJsonSafe(res: Response) { const text = await res.text(); let json: any = null; try { json = text ? JSON.parse(text) : null; } catch { // non-JSON body; keep as null and let caller see status if needed } return { json, text }; } /** * directusFetch: * - Adds Authorization + Accept headers * - Parses JSON safely and throws with readable error text on !ok */ export async function directusFetch( path: string, init?: RequestInit ): Promise { const res = await fetch(`${BASE}${path}`, { ...init, headers: { Accept: "application/json", Authorization: `Bearer ${TOKEN_SUBMIT}`, ...(init?.headers || {}), }, cache: "no-store", }); const { json, text } = await parseJsonSafe(res); if (!res.ok) { throw new Error(`Directus error ${res.status}: ${text || res.statusText}`); } return (json ?? {}) as T; } /* ───────────────────────────────────────────────────────────── * Folder lookup (by "path" = "/") with caching. * Requires READ on directus_folders to fully resolve, but gracefully * degrades (returns undefined) if forbidden/not found. * ──────────────────────────────────────────────────────────── */ type FolderItem = { id: string; name: string; parent?: { id?: string; name?: string } | null; }; const folderCache = new Map(); let folderListCache: FolderItem[] | null = null; let folderListCacheAt = 0; async function fetchAllFolders(): Promise { try { const q = `/folders?fields=id,name,parent.id,parent.name&limit=500`; const res = await directusFetch<{ data: FolderItem[] }>(q); return res?.data ?? []; } catch (e: any) { console.warn("[directus] fetchAllFolders failed:", e?.message || e); return null; } } async function getFolderIdByPath(path: string): Promise { if (!path) return undefined; if (folderCache.has(path)) return folderCache.get(path); const now = Date.now(); const freshForMs = 60_000; if (!folderListCache || now - folderListCacheAt > freshForMs) { folderListCache = await fetchAllFolders(); folderListCacheAt = now; } const list = folderListCache; if (!list) { folderCache.set(path, undefined); return undefined; } const parts = path.split("/").map((s) => s.trim()).filter(Boolean); const [parentName, childName] = parts; const eq = (a?: string | null, b?: string | null) => String(a ?? "").toLowerCase() === String(b ?? "").toLowerCase(); let match: FolderItem | undefined; if (parts.length >= 2) { match = list.find( (f) => eq(f.name, childName) && eq(f.parent?.name ?? "", parentName) ); } else { match = list.find((f) => eq(f.name, parts[0])); } const id = match?.id ? String(match.id) : undefined; folderCache.set(path, id); return id; } /** * uploadFile: * Uploads a file and (optionally) sets the folder **at create time** * so we don't need UPDATE permission on directus_files. */ export async function uploadFile( file: Blob | File, filename: string, options?: { folderId?: string; folderNamePath?: string; title?: string } ): Promise<{ id: string }> { const form = new FormData(); form.set("file", file, filename); form.set("filename_download", filename); if (options?.title) form.set("title", options.title); let folderId = options?.folderId; if (!folderId && options?.folderNamePath) { folderId = await getFolderIdByPath(options.folderNamePath); } if (folderId) form.set("folder", folderId); const res = await fetch(`${BASE}/files`, { method: "POST", headers: { Authorization: `Bearer ${TOKEN_SUBMIT}`, Accept: "application/json", }, body: form, }); const { json, text } = await parseJsonSafe(res); if (!res.ok) { throw new Error( `File upload failed: status=${res.status} ${res.statusText} body=${(text || "").slice(0, 400) || ""}` ); } const id = json?.data?.submission_id ?? json?.data?.id ?? json?.submission_id ?? json?.id; if (!id) throw new Error("File upload succeeded but no id returned"); return { id: String(id) }; } /** Create a settings item (used by settings submissions) */ export async function createSettingsItem( collection: string, payload: any ): Promise<{ data: any }> { return directusFetch<{ data: any }>(`/items/${collection}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); } /** Project helpers (used by app/api/submit/project/route.ts) */ export async function createProjectRow( payload: any ): Promise<{ data: any }> { return directusFetch<{ data: any }>(`/items/${PROJECTS_COLLECTION}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); } export async function patchProject( id: string | number, payload: any ): Promise<{ data: any }> { return directusFetch<{ data: any }>(`/items/${PROJECTS_COLLECTION}/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); } // One-time diagnostic: log which role this token maps to (safe in prod) (async () => { if (!BASE || !TOKEN_SUBMIT) return; try { const r = await fetch(`${BASE}/users/me?fields=role.name`, { headers: { Authorization: `Bearer ${TOKEN_SUBMIT}` }, cache: "no-store", }); if (r.ok) { const j = await r.json().catch(() => ({})); console.log(`[directus] using role: ${j?.data?.role?.name ?? "unknown"}`); } else { console.warn(`[directus] whoami failed with ${r.status}`); } } catch (e: any) { console.warn(`[directus] whoami error: ${e?.message ?? e}`); } })();