import lodash from "lodash";
import { DEFAULTS } from "../defaults.js";
const fetchLinkPreview = async (fetchData, url) => {
  const fixedUrl = url.split("↵").join("");
  const response = await fetchData?.(fixedUrl);
  if (!response?.description && !response?.title && !response?.thumbnail_url && !response?.html) {
    throw new Error();
  }
  return {
    thumbnailUrl: response?.thumbnail_url,
    title: response?.title,
    description: response?.description,
    html: response?.html,
    fixedUrl
  };
};
const createLinkPreviewData = async (linkData, { thumbnailUrl, title, description, html, fixedUrl }, linkPreviewConfig) => {
  const currentConfig = { ...DEFAULTS, ...linkPreviewConfig }.config;
  const data = {
    config: {
      ...currentConfig,
      link: { ...currentConfig.link, ...lodash.pickBy(linkData), url: fixedUrl },
      width: html && 350
    },
    thumbnail_url: thumbnailUrl,
    title,
    description,
    html
  };
  if (thumbnailUrl && await isValidImgSrc(thumbnailUrl)) {
    data.thumbnail_url = thumbnailUrl;
  }
  return data;
};
const isValidImgSrc = (url) => {
  return new Promise((resolve) => {
    const image = document.createElement("img");
    image.src = url;
    image.onload = () => {
      resolve(true);
    };
    image.onerror = () => {
      resolve(false);
    };
  });
};
const shouldAddLinkPreview = (title, enableLinkPreview) => enableLinkPreview && title;
const shouldAddEmbed = (html, enableEmbed, url) => {
  if (Array.isArray(enableEmbed)) {
    return enableEmbed.filter((whiteListType) => url.toLowerCase().includes(whiteListType.toLowerCase())).length > 0;
  }
  return html && enableEmbed;
};
export {
  createLinkPreviewData,
  fetchLinkPreview,
  shouldAddEmbed,
  shouldAddLinkPreview
};
//# sourceMappingURL=utils.js.map
