Open History to see the last commit
1import * as Option from "effect/Option";
2import * as Mime from "effect/http/Mime";
3
4const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
5 "image/avif": ".avif",
6 "image/bmp": ".bmp",
7 "image/gif": ".gif",
8 "image/heic": ".heic",
9 "image/heif": ".heif",
10 "image/jpeg": ".jpg",
11 "image/jpg": ".jpg",
12 "image/png": ".png",
13 "image/svg+xml": ".svg",
14 "image/tiff": ".tiff",
15 "image/webp": ".webp",
16};
17
18export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
19 ".avif",
20 ".bmp",
21 ".gif",
22 ".heic",
23 ".heif",
24 ".ico",
25 ".jpeg",
26 ".jpg",
27 ".png",
28 ".svg",
29 ".tiff",
30 ".webp",
31]);
32
33function isBase64Char(code: number): boolean {
34 return (
35 (code >= 0x61 && code <= 0x7a) ||
36 (code >= 0x41 && code <= 0x5a) ||
37 (code >= 0x30 && code <= 0x39) ||
38 code === 0x2b ||
39 code === 0x2f ||
40 code === 0x3d
41 );
42}
43
44function isBase64Whitespace(code: number): boolean {
45 return code === 0x0d || code === 0x0a || code === 0x20;
46}
47
48// Data URLs carry the full image payload, so this parser must never run a
49// regex across the payload: V8's regex engine borrows the JS call stack, and
50// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
51// execution) throws "Maximum call stack size exceeded".
52export function parseBase64DataUrl(
53 dataUrl: string,
54): { readonly mimeType: string; readonly base64: string } | null {
55 const trimmed = dataUrl.trim();
56 if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
57
58 const commaIndex = trimmed.indexOf(",");
59 if (commaIndex === -1) return null;
60 const header = trimmed.slice(5, commaIndex);
61 if (header.length === 0) return null;
62
63 const headerParts: Array<string> = [];
64 for (const part of header.split(";")) {
65 const partTrimmed = part.trim();
66 if (partTrimmed.length > 0) {
67 headerParts.push(partTrimmed);
68 }
69 }
70 if (headerParts.length < 2) {
71 return null;
72 }
73 const trailingToken = headerParts.at(-1)?.toLowerCase();
74 if (trailingToken !== "base64") {
75 return null;
76 }
77
78 const mimeType = headerParts[0]?.toLowerCase();
79 if (!mimeType) return null;
80
81 const payload = trimmed.slice(commaIndex + 1);
82 const runs: Array<string> = [];
83 let runStart = -1;
84 for (let index = 0; index < payload.length; index += 1) {
85 const code = payload.charCodeAt(index);
86 if (isBase64Char(code)) {
87 if (runStart === -1) runStart = index;
88 continue;
89 }
90 if (!isBase64Whitespace(code)) return null;
91 if (runStart !== -1) {
92 runs.push(payload.slice(runStart, index));
93 runStart = -1;
94 }
95 }
96 if (runStart !== -1) {
97 runs.push(payload.slice(runStart));
98 }
99 const base64 = runs.length === 1 ? runs[0]! : runs.join("");
100 if (base64.length === 0 || base64.length % 4 !== 0) return null;
101 const firstPad = base64.indexOf("=");
102 if (firstPad !== -1) {
103 // '=' is only valid as one or two trailing padding characters; Node's
104 // decoder would otherwise silently truncate at the first '='.
105 if (base64.length - firstPad > 2) return null;
106 for (let index = firstPad; index < base64.length; index += 1) {
107 if (base64.charCodeAt(index) !== 0x3d) return null;
108 }
109 }
110
111 return { mimeType, base64 };
112}
113
114export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
115 const key = input.mimeType.toLowerCase();
116 const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
117 ? IMAGE_EXTENSION_BY_MIME_TYPE[key]
118 : undefined;
119 if (fromMime) {
120 return fromMime;
121 }
122
123 const fromMimeExtension = Option.map(Mime.getExtension(input.mimeType), (ext) => `.${ext}`);
124 if (Option.isSome(fromMimeExtension) && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension.value)) {
125 return fromMimeExtension.value;
126 }
127
128 const fileName = input.fileName?.trim() ?? "";
129 const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
130 const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
131 if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
132 return fileNameExtension;
133 }
134
135 return ".bin";
136}