import { randomUUID } from "node:crypto"; import { mkdir, readFile, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; export const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR ?? "./data/uploads"); export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024; const EXTENSIONS: Record = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif", }; export const CONTENT_TYPES: Record = { png: "image/png", jpg: "image/jpeg", webp: "image/webp", gif: "image/gif", }; export const FILE_NAME_PATTERN = /^[a-f0-9-]{36}\.(png|jpg|webp|gif)$/; export function isUpload(value: FormDataEntryValue | null): value is File { return typeof value === "object" && value !== null && value.size > 0; } /** Sparar en uppladdad bild och returnerar filnamnet. Kastar vid fel typ eller storlek. */ export async function saveImage(file: File): Promise { const ext = EXTENSIONS[file.type]; if (!ext) throw new Error("Unsupported image type"); if (file.size > MAX_UPLOAD_BYTES) throw new Error("Image is too large"); await mkdir(UPLOAD_DIR, { recursive: true }); const name = `${randomUUID()}.${ext}`; await writeFile(path.join(UPLOAD_DIR, name), Buffer.from(await file.arrayBuffer())); return name; } export async function deleteImage(name: string | null | undefined) { if (!name || !FILE_NAME_PATTERN.test(name)) return; try { await unlink(path.join(UPLOAD_DIR, name)); } catch { // filen kan redan vara borta } } export function fileUrl(name: string | null | undefined): string | null { return name ? `/api/files/${name}` : null; } /** Bildtyp utifrån filens första bytes (inte filnamnet), eller null om det inte är en tillåten bild. */ export function detectImageExt(bytes: Uint8Array): "png" | "jpg" | "webp" | "gif" | null { const at = (i: number) => bytes[i]; if (bytes.length > 8 && at(0) === 0x89 && at(1) === 0x50 && at(2) === 0x4e && at(3) === 0x47) return "png"; if (bytes.length > 3 && at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) return "jpg"; if (bytes.length > 6 && at(0) === 0x47 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x38) return "gif"; if (bytes.length > 12 && at(0) === 0x52 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x46 && at(8) === 0x57 && at(9) === 0x45 && at(10) === 0x42 && at(11) === 0x50) return "webp"; return null; } /** Sparar en bild som redan ligger i minnet (t.ex. från en importfil). Returnerar filnamnet, eller null om bilden inte duger. */ export async function saveImageBytes(bytes: Uint8Array): Promise { const ext = detectImageExt(bytes); if (!ext || bytes.length > MAX_UPLOAD_BYTES) return null; await mkdir(UPLOAD_DIR, { recursive: true }); const name = `${randomUUID()}.${ext}`; await writeFile(path.join(UPLOAD_DIR, name), bytes); return name; } export async function readImageBytes(name: string | null | undefined): Promise { if (!name || !FILE_NAME_PATTERN.test(name)) return null; try { return await readFile(path.join(UPLOAD_DIR, name)); } catch { return null; } }