import type { FileMemoryItem, FileMemoryItemVersion, } from "@/types/file-memory"; import { BINARY_FILE_ACCEPT, base64ContentBlob, binaryMediaTypeForPath, bytesToBase64, } from "@/lib/binary-content"; import { MAX_FILE_CONTENT_BYTES } from "./file-editor"; export const FILE_MEMORY_BINARY_ACCEPT = BINARY_FILE_ACCEPT; interface FileMemoryBinaryUpload { name: string; size: number; arrayBuffer: () => Promise; } type BinaryFileMemoryContent = Pick< FileMemoryItem, "contentBase64" | "mediaType" >; export function fileMemoryBinaryMediaType(path: string): string | undefined { return binaryMediaTypeForPath(path); } export function fileMemoryBinaryAcceptForPath(path: string): string { return binaryMediaTypeForPath(path) ?? FILE_MEMORY_BINARY_ACCEPT; } export function isFileMemoryBinary( item: Pick | undefined, ): boolean { return Boolean(item?.mediaType?.trim()); } export function isSameFileMemoryBinaryFormat( path: string, fileName: string, ): boolean { const expected = fileMemoryBinaryMediaType(path); return Boolean(expected && expected === fileMemoryBinaryMediaType(fileName)); } export async function readFileMemoryBinary( file: FileMemoryBinaryUpload, path = file.name, ): Promise> { const mediaType = fileMemoryBinaryMediaType(path); if (!mediaType || !isSameFileMemoryBinaryFormat(path, file.name)) { throw new Error("UNSUPPORTED_BINARY_FORMAT"); } if (file.size > MAX_FILE_CONTENT_BYTES) { throw new Error("BINARY_TOO_LARGE"); } const bytes = new Uint8Array(await file.arrayBuffer()); if (bytes.byteLength > MAX_FILE_CONTENT_BYTES) { throw new Error("BINARY_TOO_LARGE"); } return { contentBase64: bytesToBase64(bytes), mediaType, }; } export function fileMemoryBinaryErrorKey( error: unknown, ): | "memory.files.binaryFormatMismatch" | "memory.files.binaryTooLarge" | undefined { const message = error instanceof Error ? error.message : String(error); if ( message === "UNSUPPORTED_BINARY_FORMAT" || message === "BINARY_FORMAT_MISMATCH" ) { return "memory.files.binaryFormatMismatch"; } if (message === "BINARY_TOO_LARGE") return "memory.files.binaryTooLarge"; return undefined; } export function downloadFileMemoryBinary( file: Pick< FileMemoryItem | FileMemoryItemVersion, "path" | "contentBase64" | "mediaType" >, ): boolean { if (!file.contentBase64) return false; let objectUrl: string | undefined; try { objectUrl = URL.createObjectURL( base64ContentBlob(file.contentBase64, file.mediaType), ); const anchor = document.createElement("a"); anchor.href = objectUrl; anchor.download = file.path.split("/").at(-1) || "memory-file"; anchor.click(); const completedUrl = objectUrl; setTimeout(() => URL.revokeObjectURL(completedUrl), 0); return true; } catch { if (objectUrl) URL.revokeObjectURL(objectUrl); return false; } }