"use client" import { useEffect, useState } from "react" import { apiClient } from "@/lib/api/client" import { registerCidUrlAliases } from "@/lib/mail-cid" /** Fetches inline attachment blobs and exposes blob: URLs keyed by cid (with or without cid: prefix). */ export function useInlineCidUrls(cidMap: Record | undefined) { const [urls, setUrls] = useState>({}) useEffect(() => { if (!cidMap || Object.keys(cidMap).length === 0) { setUrls({}) return } let cancelled = false const objectUrls: string[] = [] void (async () => { const next: Record = {} const blobByAttachmentId = new Map() for (const [contentId, attachmentId] of Object.entries(cidMap)) { if (!attachmentId) continue let blobUrl = blobByAttachmentId.get(attachmentId) if (!blobUrl) { try { const blob = await apiClient.getBlob( `/mail/attachments/${encodeURIComponent(attachmentId)}/inline` ) blobUrl = URL.createObjectURL(blob) blobByAttachmentId.set(attachmentId, blobUrl) objectUrls.push(blobUrl) } catch { continue } } registerCidUrlAliases(next, contentId, blobUrl) } if (!cancelled) { setUrls(next) } else { for (const u of objectUrls) URL.revokeObjectURL(u) } })() return () => { cancelled = true for (const u of objectUrls) URL.revokeObjectURL(u) } }, [cidMap]) return urls }