CoolFace
Apppublic

opusdev/vector-similarity-api

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes
fromDataURI.js54 linesDownload Raw Back to helpers
1'use strict';2 3import AxiosError from '../core/AxiosError.js';4import parseProtocol from './parseProtocol.js';5import platform from '../platform/index.js';6 7const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;8 9/**10 * Parse data uri to a Buffer or Blob11 *12 * @param {String} uri13 * @param {?Boolean} asBlob14 * @param {?Object} options15 * @param {?Function} options.Blob16 *17 * @returns {Buffer|Blob}18 */19export default function fromDataURI(uri, asBlob, options) {20  const _Blob = options && options.Blob || platform.classes.Blob;21  const protocol = parseProtocol(uri);22 23  if (asBlob === undefined && _Blob) {24    asBlob = true;25  }26 27  if (protocol === 'data') {28    uri = protocol.length ? uri.slice(protocol.length + 1) : uri;29 30    const match = DATA_URL_PATTERN.exec(uri);31 32    if (!match) {33      throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);34    }35 36    const mime = match[1];37    const isBase64 = match[2];38    const body = match[3];39    const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');40 41    if (asBlob) {42      if (!_Blob) {43        throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);44      }45 46      return new _Blob([buffer], {type: mime});47    }48 49    return buffer;50  }51 52  throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);53}54