import { l as lodash, X as Promise$1, Y as FontFaceObserver, Z as lru } from "./index.js";
import readFile from "./read-file.js";
import "vue";
let FontFace = window.FontFace;
if (!document.fonts || !document.fonts.load) {
  FontFace = window.FontFace = function(name, url, descriptors) {
    this.name = name;
    this.url = url;
    lodash.exports.assign(this, {
      style: "normal",
      weight: "normal"
    }, descriptors);
    const _dfd = this._dfd = {};
    _dfd.promise = new Promise$1((resolve, reject) => {
      _dfd.resolve = resolve;
      _dfd.reject = reject;
    });
  };
  lodash.exports.assign(FontFace.prototype, {
    toCSS() {
      let css = "@font-face {\n";
      css += "font-family: " + this.name + ";\n";
      css += "src: " + this.url + ";";
      css += "font-weight: " + this.weight + ";";
      css += "font-style: " + this.style + ";";
      css += "}";
      return css;
    },
    load() {
      return this._dfd.promise;
    }
  });
  const fonts = document.fonts = {
    ready: Promise$1.resolve(),
    check: lodash.exports.noop,
    _fonts: [],
    size: 0,
    loadTimeout: 1e3,
    add(fontFace) {
      let style = fonts.style;
      if (!style) {
        style = fonts.style = document.createElement("style");
        document.head.appendChild(style);
      }
      if (!(fontFace instanceof FontFace)) {
        throw new TypeError("Only support FontFace");
      }
      fonts._fonts.push(fontFace);
      fonts.size = fonts._fonts.length;
      const dfd = fontFace._dfd;
      new FontFaceObserver(fontFace.name).load("BESbswy", fonts.loadTimeout).then(dfd.resolve, (font) => {
        dfd.resolve(font);
      });
      let cssText = style.innerHTML;
      cssText += "\n";
      cssText += fontFace.toCSS();
      style.innerHTML = cssText;
      return fonts;
    },
    load() {
      const promises = fonts._fonts.map((font) => {
        return font.load();
      });
      return Promise$1.all(promises);
    }
  };
}
var FontFace$1 = FontFace;
const caches = {
  image: new lru.LRUMap(30),
  audio: new lru.LRUMap(20),
  video: new lru.LRUMap(20),
  font: new lru.LRUMap(20),
  fontSubset: new lru.LRUMap(20),
  xml: new lru.LRUMap(20),
  xmlStr: new lru.LRUMap(20)
};
const crossOriginParam = "cross_origin=1";
const isCrossOriginUrl = (url) => {
  const origin = location.host;
  return url.indexOf("data:") !== 0 && url.indexOf(origin) < 0;
};
const getComputedUrl = (url = "", fitCrossOrigin = false) => {
  if (!url || !fitCrossOrigin) {
    return url;
  }
  if (isCrossOriginUrl(url) && url.indexOf(crossOriginParam) < 0) {
    url += url.indexOf("?") < 0 ? "?" : "&";
    url += crossOriginParam;
  }
  return url;
};
const _loadImage = (url) => {
  return new Promise$1((resolve, reject) => {
    const img = new Image();
    if (isCrossOriginUrl(url)) {
      img.crossOrigin = "Anonymous";
    }
    img.onload = () => {
      resolve(img);
    };
    img.onerror = function() {
      const msg = "Image load error: " + url;
      reject(new Error(msg));
    };
    img.src = url;
  });
};
const _loadMedia = (url, time = 0, tag = "video") => {
  return new Promise$1((resolve, reject) => {
    const media = document.createElement(tag);
    if (isCrossOriginUrl(url)) {
      media.crossOrigin = "Anonymous";
    }
    media.onloadeddata = () => {
      media.currentTime = time;
    };
    media.ontimeupdate = () => {
      resolve(media);
    };
    media.onerror = function(e) {
      const msg = "Video load error: " + url;
      reject(new Error(msg));
    };
    media.currentTime = time === 0 ? 1e-3 : 0;
    media.src = url;
  });
};
const _loadXML = (url) => {
  return new Promise$1((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.overrideMimeType("application/xml");
    xhr.onreadystatechange = function() {
      if (xhr.readyState !== 4)
        return;
      if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
        resolve(xhr.responseXML, xhr);
      } else {
        reject(new Error(xhr.responseText));
      }
    };
    xhr.send(null);
  });
};
const parseXML = (content) => {
  return Promise$1.try(() => {
    if (DOMParser && DOMParser.prototype.parseFromString) {
      const parser = new DOMParser();
      return parser.parseFromString(content, "application/xml");
    }
    const blob = new Blob([content], { type: "xml/svg" });
    const url = URL.createObjectURL(blob);
    return _loadXML(url).then((xml) => {
      URL.revokeObjectURL(url);
      return xml;
    });
  });
};
var loader = {
  isCrossOriginUrl,
  getComputedUrl,
  parseXML,
  _loadImage,
  _loadVideo: _loadMedia,
  _loadXML,
  loadImage(url, fitCrossOrigin = false, tryLoadVideo = false) {
    const imgCaches = caches.image;
    url = getComputedUrl(url, fitCrossOrigin);
    if (!imgCaches.get(url)) {
      !tryLoadVideo ? imgCaches.set(url, _loadImage(url)) : imgCaches.set(url, _loadImage(url).catch((e) => {
        return _loadMedia(url, 0).then((video) => {
          video.naturalWidth = video.width = video.videoWidth;
          video.naturalHeight = video.height = video.videoHeight;
          return video;
        }).catch(() => {
          throw e;
        });
      }));
    }
    return imgCaches.get(url);
  },
  loadVideo(url, currentTime = 0, fitCrossOrigin = false) {
    const videoCaches = caches.video;
    url = getComputedUrl(url, fitCrossOrigin);
    const key = url + currentTime;
    if (!videoCaches.get(key)) {
      videoCaches.set(key, _loadMedia(url, currentTime, "video").then((video) => {
        video.naturalWidth = video.width = video.videoWidth;
        video.naturalHeight = video.height = video.videoHeight;
        return video;
      }));
    }
    return videoCaches.get(key);
  },
  loadAudio(url, currentTime = 0, fitCrossOrigin = false) {
    const audioCaches = caches.audio;
    url = getComputedUrl(url, fitCrossOrigin);
    if (!audioCaches.get(url)) {
      audioCaches.set(url, _loadMedia(url, currentTime, "audio"));
    }
    return audioCaches.get(url);
  },
  loadXML(url) {
    const xmlCaches = caches.xml;
    if (!xmlCaches.get(url)) {
      xmlCaches.set(url, _loadXML(url).catch((err) => {
        err.message = "Svg load error: " + err.message;
        throw err;
      }));
    }
    return xmlCaches.get(url);
  },
  loadXMLStr(url) {
    const xmlCaches = caches.xmlStr;
    if (!xmlCaches.get(url)) {
      xmlCaches.set(url, Promise$1.try(() => {
        return fetch(url).then((res) => res.text());
      }).catch((err) => {
        err.message = "Svg str load error: " + err.message;
        throw err;
      }));
    }
    return xmlCaches.get(url);
  },
  loadFont(options, timeout = 1e4) {
    const fontCaches = caches.font;
    const subsetCaches = caches.fontSubset;
    const { name, family } = options;
    if (!fontCaches.get(name)) {
      const urls = [`local("${name}")`];
      if (family && family !== name) {
        urls.push(`local("${family}")`);
      }
      if (options.woff || options.url) {
        urls.push(`url("${options.woff || options.url}")`);
      } else if (options.ttf) {
        urls.push(`url("${options.ttf}")`);
      }
      const fontParams = {
        weight: options.weight || "normal",
        style: options.style || "normal",
        display: options.display || "auto"
      };
      const registerFont = (urls2, hasSubset) => {
        return Promise$1.try(() => {
          let font;
          let subsetName, subsetFamily;
          if (hasSubset) {
            subsetName = name + options.subset.suffix;
            subsetFamily = family + options.subset.suffix;
          }
          try {
            font = new FontFace$1(subsetName || name, urls2.join(","), fontParams);
          } catch (e) {
            font = new FontFace$1(subsetFamily || family, urls2.join(","), fontParams);
          }
          document.fonts.add(font);
          return font.load();
        }).timeout(timeout, `Font [${family}] load timeout(${timeout}ms)`).catch((err) => {
          delete fontCaches[name];
          throw err;
        });
      };
      if (options.subset && options.subset.promise) {
        const promiseFn = () => options.subset.promise.then((url) => {
          return registerFont([`local("${name}")`, 'url("' + url + '")'], true);
        }).catch((e) => {
          fontCaches.set(name, registerFont(urls));
          return fontCaches.get(name);
        });
        if (!options.subset.content)
          return promiseFn();
        const cacheKey = options.subset.content + "-" + name + "-" + options.subset.suffix;
        if (!subsetCaches.get(cacheKey)) {
          subsetCaches.set(cacheKey, promiseFn());
        }
        return subsetCaches.get(cacheKey);
      } else {
        fontCaches.set(name, registerFont(urls));
      }
    }
    return fontCaches.get(name);
  },
  readFile
};
export { loader as default };
