export const BINARY_MEDIA_TYPES_BY_EXTENSION: Readonly> = Object.freeze({ ".pdf": "application/pdf", ".doc": "application/msword", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".xls": "application/vnd.ms-excel", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".ppt": "application/vnd.ms-powerpoint", ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", }); export const BINARY_FILE_EXTENSIONS = Object.freeze( Object.keys(BINARY_MEDIA_TYPES_BY_EXTENSION), ); export const BINARY_FILE_ACCEPT = BINARY_FILE_EXTENSIONS.join(","); export function sourceFileExtension(path: string): string { const fileName = path.split("/").at(-1) ?? ""; const dot = fileName.lastIndexOf("."); return dot < 0 ? "" : fileName.slice(dot).toLowerCase(); } export function binaryMediaTypeForPath(path: string): string | undefined { return BINARY_MEDIA_TYPES_BY_EXTENSION[sourceFileExtension(path)]; } export function bytesToBase64(bytes: Uint8Array): string { let binary = ""; const chunkSize = 0x8000; for (let offset = 0; offset < bytes.length; offset += chunkSize) { binary += String.fromCharCode( ...bytes.subarray(offset, offset + chunkSize), ); } return btoa(binary); } /** Returns the decoded size after the caller has validated canonical base64. */ export function canonicalBase64DecodedByteLength(value: string): number { let padding = 0; if (value.endsWith("==")) { padding = 2; } else if (value.endsWith("=")) { padding = 1; } return (value.length / 4) * 3 - padding; } export function base64ContentBlob( contentBase64: string, mediaType?: string, ): Blob { const binary = atob(contentBase64); const bytes = new Uint8Array(binary.length); for (let index = 0; index < binary.length; index += 1) { bytes[index] = binary.charCodeAt(index); } return new Blob([bytes], { type: mediaType ?? "application/octet-stream", }); }