Open History to see the last commit
1import Mime from "@effect/platform-node/Mime";
2
3export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
4 "image/avif": ".avif",
5 "image/bmp": ".bmp",
6 "image/gif": ".gif",
7 "image/heic": ".heic",
8 "image/heif": ".heif",
9 "image/jpeg": ".jpg",
10 "image/jpg": ".jpg",
11 "image/png": ".png",
12 "image/svg+xml": ".svg",
13 "image/tiff": ".tiff",
14 "image/webp": ".webp",
15};
16
17export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
18 ".avif",
19 ".bmp",
20 ".gif",
21 ".heic",
22 ".heif",
23 ".ico",
24 ".jpeg",
25 ".jpg",
26 ".png",
27 ".svg",
28 ".tiff",
29 ".webp",
30]);
31
32export function parseBase64DataUrl(
33 dataUrl: string,
34): { readonly mimeType: string; readonly base64: string } | null {
35 const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
36 if (!match) return null;
37
38 const headerParts: Array<string> = [];
39 for (const part of (match[1] ?? "").split(";")) {
40 const trimmed = part.trim();
41 if (trimmed.length > 0) {
42 headerParts.push(trimmed);
43 }
44 }
45 if (headerParts.length < 2) {
46 return null;
47 }
48 const trailingToken = headerParts.at(-1)?.toLowerCase();
49 if (trailingToken !== "base64") {
50 return null;
51 }
52
53 const mimeType = headerParts[0]?.toLowerCase();
54 const base64 = match[2]?.replace(/\s+/g, "");
55 if (!mimeType || !base64) return null;
56
57 return { mimeType, base64 };
58}
59
60export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
61 const key = input.mimeType.toLowerCase();
62 const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
63 ? IMAGE_EXTENSION_BY_MIME_TYPE[key]
64 : undefined;
65 if (fromMime) {
66 return fromMime;
67 }
68
69 const fromMimeExtension = Mime.getExtension(input.mimeType);
70 if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {
71 return fromMimeExtension;
72 }
73
74 const fileName = input.fileName?.trim() ?? "";
75 const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
76 const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
77 if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
78 return fileNameExtension;
79 }
80
81 return ".bin";
82}