All files index.ts

100% Statements 17/17
92.3% Branches 12/13
100% Functions 5/5
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43        1x 35x 35x 10x   25x     1x                             1x 13x 13x       17x 17x 17x 5x 5x     12x 12x  
import fs from 'fs';
import path from 'path';
import fetch from 'node-fetch';
 
export const validUrl = (url: string) => {
  try {
    const { protocol } = new URL(url);
    return protocol === 'http:' || protocol === 'https:';
  } catch {
    return false;
  }
};
export const extTypeMap = {
  '.png': 'image/png',
  '.apng': 'image/apng',
  '.gif': 'image/gif',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.bm': 'image/bmp',
  '.bmp': 'image/bmp',
  '.webp': 'image/webp',
  '.ico': 'image/x-icon',
  '.svg': 'image/svg+xml'
}
 
export type ExtType =  keyof typeof extTypeMap;
 
const fileExt = (file: string) => {
  const target = validUrl(file) ? new URL(file).pathname : file;
  return path.extname(target);
};
 
export default function image2uri(file: string, options: { ext?: string } = {}): string | Promise<string> {
  const ext = (options.ext || fileExt(file)).toLowerCase() as ExtType;
  const contentType = extTypeMap[ext]
  if (validUrl(file)) {
    return fetch(file).then((response) => response.buffer()).then((buffer) => {
      return contentType ? `data:${contentType};base64,${buffer.toString('base64')}` : buffer.toString('base64');
    });
  }
  const image = fs.readFileSync(file);
  return contentType ? `data:${contentType};base64,${image.toString('base64')}` : image.toString('base64');
}