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 = (match[1] ?? "")
39 .split(";")
40 .map((part) => part.trim())
41 .filter((part) => part.length > 0);
42 if (headerParts.length < 2) {
43 return null;
44 }
45 const trailingToken = headerParts.at(-1)?.toLowerCase();
46 if (trailingToken !== "base64") {
47 return null;
48 }
49
50 const mimeType = headerParts[0]?.toLowerCase();
51 const base64 = match[2]?.replace(/\s+/g, "");
52 if (!mimeType || !base64) return null;
53
54 return { mimeType, base64 };
55}
56
57export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
58 const key = input.mimeType.toLowerCase();
59 const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
60 ? IMAGE_EXTENSION_BY_MIME_TYPE[key]
61 : undefined;
62 if (fromMime) {
63 return fromMime;
64 }
65
66 const fromMimeExtension = Mime.getExtension(input.mimeType);
67 if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {
68 return fromMimeExtension;
69 }
70
71 const fileName = input.fileName?.trim() ?? "";
72 const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
73 const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
74 if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
75 return fileNameExtension;
76 }
77
78 return ".bin";
79}