/*
 * THIS IS A GENERATED/BUNDLED FILE.
 * The source is available at https://github.com/dylanpizzo/obsidian-plugins-galore.
 * Contributions are very welcome!
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
  __markAsModule(target);
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, desc) => {
  if (module2 && typeof module2 === "object" || typeof module2 === "function") {
    for (let key of __getOwnPropNames(module2))
      if (!__hasOwnProp.call(target, key) && key !== "default")
        __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
  }
  return target;
};
var __toModule = (module2) => {
  return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};

// src/main.ts
__export(exports, {
  default: () => Galore
});
var import_obsidian7 = __toModule(require("obsidian"));

// src/util/cacheRequest.ts
var import_obsidian = __toModule(require("obsidian"));
var cache = [];
var cacheRequest = (req) => __async(void 0, null, function* () {
  const filteredCache = cache.filter((item) => item.req === JSON.stringify(req));
  if (filteredCache.length) {
    return filteredCache[0].res;
  }
  const res = yield (0, import_obsidian.request)(req);
  cache.push({ req: JSON.stringify(req), res });
  return res;
});

// src/util/gitServerInterface.ts
var countRegexInString = (str, re) => ((str || "").match(re) || []).length;
var getKeyWithMax = (obj) => Object.keys(obj).reduce((a, b) => obj[a] >= obj[b] ? a : b, null);
var parseRepoURL = (url) => __async(void 0, null, function* () {
  let urlObj = null;
  try {
    urlObj = new URL(url);
  } catch (e) {
    urlObj = new URL("https://" + url);
  }
  const domain = urlObj.hostname;
  let path = urlObj.pathname;
  if (path[0] === "/") {
    path = path.slice(1);
  }
  const pathParts = path.split("/");
  const owner = pathParts[0];
  const name = pathParts[1];
  const originBody = yield cacheRequest({ url: urlObj.origin });
  const typeScores = {
    github: countRegexInString(originBody, /github/gi),
    gitea: countRegexInString(originBody, /gitea/gi),
    gitlab: countRegexInString(originBody, /gitlab/gi)
  };
  const type = getKeyWithMax(typeScores);
  return {
    domain,
    owner,
    name,
    url,
    type
  };
});
var getRelease = (repo, options) => __async(void 0, null, function* () {
  const { type, domain, owner, name } = repo;
  const { allowPrerelease = false } = options || {};
  let release = null;
  if (type === "github") {
    const rawReleases = JSON.parse(yield cacheRequest({
      url: `https://api.${domain}/repos/${owner}/${name}/releases`
    }));
    const rawRelease = rawReleases.filter((x) => !x.draft && (allowPrerelease || !x.prerelease)).sort((x) => x.published_at)[0];
    release = {
      version: rawRelease.tag_name,
      assets: rawRelease.assets.map((asset) => ({
        name: asset.name,
        url: asset.browser_download_url
      }))
    };
  } else if (type === "gitea") {
    const rawReleases = JSON.parse(yield cacheRequest({
      url: `https://${domain}/api/v1/repos/${owner}/${name}/releases`
    }));
    const rawRelease = rawReleases.filter((x) => !x.draft && (allowPrerelease || !x.prerelease)).sort((x) => x.published_at)[0];
    release = {
      version: rawRelease.tag_name,
      assets: rawRelease.assets.map((asset) => ({
        name: asset.name,
        url: asset.browser_download_url
      }))
    };
  } else if (type === "gitlab") {
    const rawReleases = JSON.parse(yield cacheRequest({
      url: `https://${domain}/api/v4/projects/${owner}%2F${name}/releases`
    }));
    const rawRelease = rawReleases.filter((x) => allowPrerelease || !x.upcoming_release).sort((x) => x.published_at)[0];
    release = {
      version: rawRelease.tag_name,
      assets: rawRelease.assets.links.map((asset) => ({
        name: asset.name,
        url: asset.direct_asset_url
      }))
    };
  }
  return release;
});
var getAsset = (release, name) => __async(void 0, null, function* () {
  const asset = release.assets.filter((asset2) => asset2.name === name)[0];
  if (!asset) {
    return null;
  }
  return cacheRequest({
    url: asset.url
  });
});
var getAssets = (release, names) => __async(void 0, null, function* () {
  const assets = names ? release.assets.filter((asset) => names.includes(asset.name)) : release.assets;
  return Promise.all(assets.map((asset) => __async(void 0, null, function* () {
    return { name: asset.name, content: yield cacheRequest({ url: asset.url }) };
  })));
});

// src/ui/settingsPage.ts
var import_obsidian6 = __toModule(require("obsidian"));

// src/util/pluginActions.ts
var import_obsidian3 = __toModule(require("obsidian"));

// src/ui/errorModal.ts
var import_obsidian2 = __toModule(require("obsidian"));
var GaloreErrorModal = class extends import_obsidian2.Modal {
  constructor(app2, error) {
    super(app2);
    this.error = null;
    this.error = error;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.setText("Oops. Something went wrong!");
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/util/pluginActions.ts
var getPluginsDir = (app2) => {
  return (0, import_obsidian3.normalizePath)(app2.vault.configDir + "/plugins") + "/";
};
var getPluginPath = (app2, pluginID) => {
  return getPluginsDir(app2) + pluginID + "/";
};
var getRemotePluginMeta = (repo) => __async(void 0, null, function* () {
  try {
    const release = yield getRelease(repo);
    return { repo, version: release.version };
  } catch (error) {
    console.error(error);
    new GaloreErrorModal(app, error).open();
  }
});
var getRemotePlugin = (repo) => __async(void 0, null, function* () {
  try {
    const release = yield getRelease(repo);
    const galore = { repo, version: release.version };
    const rawManifest = yield getAsset(release, "manifest.json");
    const manifest = JSON.parse(yield getAsset(release, "manifest.json"));
    const assets = yield getAssets(release);
    return {
      galore,
      manifest,
      assets
    };
  } catch (error) {
    console.error(error);
    new GaloreErrorModal(app, error).open();
  }
});
var getLocalPluginMeta = (pluginsGalore, pluginID) => {
  return pluginsGalore.galoreData.plugins[pluginID];
};
var writePlugin = (pluginsGalore, plugin) => __async(void 0, null, function* () {
  try {
    const path = getPluginPath(app, plugin.manifest.id);
    const adapter = app.vault.adapter;
    if (!(yield adapter.exists(path))) {
      yield adapter.mkdir(path);
    }
    pluginsGalore.galoreData.plugins[plugin.manifest.id] = plugin.galore;
    yield pluginsGalore.saveGaloreData();
    yield Promise.all(plugin.assets.map((asset) => __async(void 0, null, function* () {
      return adapter.write(path + asset.name, asset.content);
    })));
  } catch (error) {
    console.error(error);
    new GaloreErrorModal(app, error).open();
  }
});
var installPluginFromRepo = (pluginsGalore, repo) => __async(void 0, null, function* () {
  const plugin = yield getRemotePlugin(repo);
  yield writePlugin(pluginsGalore, plugin);
  return plugin;
});
var getGalorePlugins = (pluginsGalore) => __async(void 0, null, function* () {
  try {
    const app2 = pluginsGalore.app;
    const adapter = app2.vault.adapter;
    const pluginsDir = getPluginsDir(app2);
    const galorePluginPaths = Object.keys(pluginsGalore.galoreData.plugins).map((pluginID) => pluginsDir + "/" + pluginID + "/");
    const galorePlugins = yield Promise.all(galorePluginPaths.map((path) => __async(void 0, null, function* () {
      const localManifest = JSON.parse(yield adapter.read(path + "manifest.json"));
      const localGalore = getLocalPluginMeta(pluginsGalore, localManifest.id);
      const remoteGalore = yield getRemotePluginMeta(localGalore.repo);
      return {
        manifest: localManifest,
        repo: localGalore.repo,
        localVersion: localGalore.version,
        remoteVersion: remoteGalore.version,
        canUpdate: localGalore.version !== remoteGalore.version
      };
    })));
    return galorePlugins;
  } catch (error) {
    console.error(error);
    new GaloreErrorModal(app, error).open();
  }
});

// src/ui/updateModal.ts
var import_obsidian4 = __toModule(require("obsidian"));
var GaloreUpdateModal = class extends import_obsidian4.Modal {
  constructor(plugin, galorePlugins) {
    super(app);
    this.galorePlugins = null;
    this.plugin = plugin;
    this.app = plugin.app;
    this.galorePlugins = galorePlugins;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.createEl("h2", { text: "Plugins Galore: Update Plugins" });
    new import_obsidian4.Setting(contentEl).setName("Select the plugins below to update, and then click Update.").setDesc("").addButton((button) => button.setButtonText("Cancel").onClick((ev) => {
      this.close();
    })).addButton((button) => button.setButtonText("Update").setCta().onClick((ev) => __async(this, null, function* () {
      const pluginsToUpdate = this.galorePlugins.filter((plugin) => plugin.toggle.getValue());
      for (const plugin of pluginsToUpdate) {
        yield installPluginFromRepo(this.plugin, plugin.repo);
      }
      new import_obsidian4.Notice(`Updated ${pluginsToUpdate.length} plugins`);
      this.close();
    })));
    for (const plugin of this.galorePlugins) {
      new import_obsidian4.Setting(contentEl).setName(plugin.manifest.name).setDesc(`Version: ${plugin.localVersion} -> ${plugin.remoteVersion}`).addToggle((toggle) => {
        plugin.toggle = toggle;
        toggle.setValue(true);
      });
    }
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/ui/addModal.ts
var import_obsidian5 = __toModule(require("obsidian"));
var GaloreAddModal = class extends import_obsidian5.Modal {
  constructor(plugin) {
    super(app);
    this.plugin = plugin;
    this.app = plugin.app;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.empty();
    contentEl.createEl("h2", { text: "Plugins Galore: Add a Plugin" });
    let repoURL = "";
    let siteType = "github";
    new import_obsidian5.Setting(contentEl).setName("Repo URL").setDesc("").addText((text) => text.setPlaceholder("https://github.com/{owner}/{plugin-repo}").setValue(repoURL).onChange((value) => {
      repoURL = value;
    }));
    new import_obsidian5.Setting(contentEl).setName("Install the plugin").setDesc("").addButton((button) => button.setButtonText("Install").setCta().onClick((ev) => __async(this, null, function* () {
      const repo = yield parseRepoURL(repoURL);
      const plugin = yield installPluginFromRepo(this.plugin, repo);
      new import_obsidian5.Notice(`Installed ${plugin.manifest.name}.`);
      this.close();
    })));
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/ui/settingsPage.ts
var GaloreSettingTab = class extends import_obsidian6.PluginSettingTab {
  constructor(plugin) {
    super(app, plugin);
    this.plugin = plugin;
    this.app = plugin.app;
  }
  display() {
    const { containerEl } = this;
    containerEl.empty();
    containerEl.createEl("h2", { text: "Plugins Galore" });
    let repoURL = "";
    let repoInput = null;
    new import_obsidian6.Setting(containerEl).setName("Add a plugin").setDesc("").addButton((button) => button.setButtonText("Add a plugin").setCta().onClick((ev) => __async(this, null, function* () {
      new GaloreAddModal(this.plugin).open();
    })));
    new import_obsidian6.Setting(containerEl).setName("Installed Plugins").setDesc("This only checks for updates on plugins installed through Plugins Galore.").addButton((button) => button.setButtonText("Check for updates").setCta().onClick((ev) => __async(this, null, function* () {
      const galorePlugins = yield getGalorePlugins(this.plugin);
      const galorePluginsThatCanUpdate = galorePlugins.filter((x) => x.canUpdate);
      if (galorePluginsThatCanUpdate.length) {
        new GaloreUpdateModal(this.plugin, galorePluginsThatCanUpdate).open();
      } else {
        new import_obsidian6.Notice("No plugins updates found.");
      }
    })));
  }
};

// src/main.ts
var Galore = class extends import_obsidian7.Plugin {
  onload() {
    return __async(this, null, function* () {
      yield this.loadGaloreData();
      this.addSettingTab(new GaloreSettingTab(this));
    });
  }
  loadGaloreData() {
    return __async(this, null, function* () {
      this.galoreData = Object.assign({}, {
        plugins: {
          "plugins-galore": {
            repo: yield parseRepoURL("https://github.com/dylanpizzo/obsidian-plugins-galore"),
            version: this.manifest.version
          }
        }
      }, yield this.loadData());
    });
  }
  saveGaloreData() {
    return __async(this, null, function* () {
      yield this.saveData(this.galoreData);
    });
  }
};
