/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __reflectGet = Reflect.get;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
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/services/linkSuggesterService/handlers/pixelFinder.js
var require_pixelFinder = __commonJS({
  "src/services/linkSuggesterService/handlers/pixelFinder.js"(exports, module2) {
    (function() {
      var properties = [
        "direction",
        "boxSizing",
        "width",
        "height",
        "overflowX",
        "overflowY",
        "borderTopWidth",
        "borderRightWidth",
        "borderBottomWidth",
        "borderLeftWidth",
        "borderStyle",
        "paddingTop",
        "paddingRight",
        "paddingBottom",
        "paddingLeft",
        "fontStyle",
        "fontVariant",
        "fontWeight",
        "fontStretch",
        "fontSize",
        "fontSizeAdjust",
        "lineHeight",
        "fontFamily",
        "textAlign",
        "textTransform",
        "textIndent",
        "textDecoration",
        "letterSpacing",
        "wordSpacing",
        "tabSize",
        "MozTabSize"
      ];
      var isBrowser = typeof window !== "undefined";
      var isFirefox = isBrowser && global.window.mozInnerScreenX != null;
      function getCaretCoordinates(element, position, options) {
        if (!isBrowser) {
          throw new Error("textarea-caret-position#getCaretCoordinates should only be called in a browser");
        }
        var debug = options && options.debug || false;
        if (debug) {
          var el = global.document.querySelector("#input-textarea-caret-position-mirror-div");
          if (el)
            el.parentNode.removeChild(el);
        }
        var div = global.document.createElement("div");
        div.id = "input-textarea-caret-position-mirror-div";
        global.document.body.appendChild(div);
        var style = div.style;
        var computed = global.window.getComputedStyle ? global.window.getComputedStyle(element) : element.currentStyle;
        var isInput = element.nodeName === "INPUT";
        style.whiteSpace = "pre-wrap";
        if (!isInput)
          style.wordWrap = "break-word";
        style.position = "absolute";
        if (!debug)
          style.visibility = "hidden";
        properties.forEach(function(prop) {
          if (isInput && prop === "lineHeight") {
            if (computed.boxSizing === "border-box") {
              var height = parseInt(computed.height);
              var outerHeight = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom) + parseInt(computed.borderTopWidth) + parseInt(computed.borderBottomWidth);
              var targetHeight = outerHeight + parseInt(computed.lineHeight);
              if (height > targetHeight) {
                style.lineHeight = height - outerHeight + "px";
              } else if (height === targetHeight) {
                style.lineHeight = computed.lineHeight;
              } else {
                style.lineHeight = 0;
              }
            } else {
              style.lineHeight = computed.height;
            }
          } else {
            style[prop] = computed[prop];
          }
        });
        if (isFirefox) {
          if (element.scrollHeight > parseInt(computed.height))
            style.overflowY = "scroll";
        } else {
          style.overflow = "hidden";
        }
        div.textContent = element.value.substring(0, position);
        if (isInput)
          div.textContent = div.textContent.replace(/\s/g, "\xA0");
        var span = global.document.createElement("span");
        span.textContent = element.value.substring(position) || ".";
        div.appendChild(span);
        var coordinates = {
          top: span.offsetTop + parseInt(computed["borderTopWidth"]),
          left: span.offsetLeft + parseInt(computed["borderLeftWidth"]),
          height: parseInt(computed["lineHeight"])
        };
        if (debug) {
          span.style.backgroundColor = "#aaa";
        } else {
          global.document.body.removeChild(div);
        }
        return coordinates;
      }
      if (typeof module2 != "undefined" && typeof module2.exports != "undefined") {
        module2.exports = getCaretCoordinates;
      } else if (isBrowser) {
        global.window.getCaretCoordinates = getCaretCoordinates;
      }
    })();
  }
});

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => RpgManager
});
module.exports = __toCommonJS(main_exports);
var import_obsidian46 = require("obsidian");

// src/core/enums/ComponentType.ts
var ComponentType = /* @__PURE__ */ ((ComponentType2) => {
  ComponentType2[ComponentType2["Campaign"] = 1] = "Campaign";
  ComponentType2[ComponentType2["Adventure"] = 2] = "Adventure";
  ComponentType2[ComponentType2["Act"] = 4] = "Act";
  ComponentType2[ComponentType2["Scene"] = 8] = "Scene";
  ComponentType2[ComponentType2["Session"] = 16] = "Session";
  ComponentType2[ComponentType2["Character"] = 32] = "Character";
  ComponentType2[ComponentType2["NonPlayerCharacter"] = 64] = "NonPlayerCharacter";
  ComponentType2[ComponentType2["Location"] = 128] = "Location";
  ComponentType2[ComponentType2["Event"] = 256] = "Event";
  ComponentType2[ComponentType2["Clue"] = 512] = "Clue";
  ComponentType2[ComponentType2["Faction"] = 1024] = "Faction";
  ComponentType2[ComponentType2["Music"] = 2048] = "Music";
  ComponentType2[ComponentType2["Subplot"] = 4096] = "Subplot";
  return ComponentType2;
})(ComponentType || {});

// src/core/modals/CreationModal.ts
var import_obsidian2 = require("obsidian");

// src/managers/servicesManager/abstracts/AbstractService.ts
var import_obsidian = require("obsidian");
var AbstractService = class extends import_obsidian.Component {
  constructor(api) {
    super();
    this.api = api;
  }
};

// src/services/tagService/TagService.ts
var _TagService = class extends AbstractService {
  constructor(api) {
    super(api);
    this.dataSettings = /* @__PURE__ */ new Map();
    this.dataSettings.set(1 /* Campaign */, _TagService.campaignTag);
    this.dataSettings.set(2 /* Adventure */, _TagService.adventureTag);
    this.dataSettings.set(4 /* Act */, _TagService.actTag);
    this.dataSettings.set(8 /* Scene */, _TagService.sceneTag);
    this.dataSettings.set(16 /* Session */, _TagService.sessionTag);
    this.dataSettings.set(32 /* Character */, _TagService.pcTag);
    this.dataSettings.set(512 /* Clue */, _TagService.clueTag);
    this.dataSettings.set(256 /* Event */, _TagService.eventTag);
    this.dataSettings.set(1024 /* Faction */, _TagService.factionTag);
    this.dataSettings.set(128 /* Location */, _TagService.locationTag);
    this.dataSettings.set(64 /* NonPlayerCharacter */, _TagService.npcTag);
    this.dataSettings.set(2048 /* Music */, _TagService.musicTag);
    this.dataSettings.set(4096 /* Subplot */, _TagService.subplotTag);
    this._requiredIds = /* @__PURE__ */ new Map();
    this._requiredIds.set(1 /* Campaign */, [1 /* Campaign */]);
    this._requiredIds.set(2 /* Adventure */, [1 /* Campaign */]);
    this._requiredIds.set(4 /* Act */, [1 /* Campaign */, 2 /* Adventure */]);
    this._requiredIds.set(8 /* Scene */, [1 /* Campaign */, 2 /* Adventure */, 4 /* Act */, 8 /* Scene */]);
    this._requiredIds.set(16 /* Session */, [1 /* Campaign */, 16 /* Session */]);
    this._requiredIds.set(32 /* Character */, [1 /* Campaign */]);
    this._requiredIds.set(512 /* Clue */, [1 /* Campaign */]);
    this._requiredIds.set(256 /* Event */, [1 /* Campaign */]);
    this._requiredIds.set(1024 /* Faction */, [1 /* Campaign */]);
    this._requiredIds.set(128 /* Location */, [1 /* Campaign */]);
    this._requiredIds.set(64 /* NonPlayerCharacter */, [1 /* Campaign */]);
    this._requiredIds.set(2048 /* Music */, [2048 /* Music */]);
    this._requiredIds.set(4096 /* Subplot */, [4096 /* Subplot */]);
  }
  sanitiseTags(tags) {
    if (tags == null)
      return [];
    let temporaryResponse = [];
    if (typeof tags === "string") {
      temporaryResponse = tags.split(",");
      temporaryResponse.forEach((tag) => {
        tag = tag.replaceAll(" ", "").replaceAll("#", "");
      });
    } else {
      temporaryResponse = tags;
    }
    const response = [];
    temporaryResponse.forEach((tag) => {
      if (tag != null)
        response.push(tag);
    });
    return response;
  }
  getDataType(tag) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
    if (tag.startsWith((_a = this.dataSettings.get(1 /* Campaign */)) != null ? _a : "?"))
      return 1 /* Campaign */;
    if (tag.startsWith((_b = this.dataSettings.get(2 /* Adventure */)) != null ? _b : "?"))
      return 2 /* Adventure */;
    if (tag.startsWith((_c = this.dataSettings.get(4 /* Act */)) != null ? _c : "?"))
      return 4 /* Act */;
    if (tag.startsWith((_d = this.dataSettings.get(8 /* Scene */)) != null ? _d : "?"))
      return 8 /* Scene */;
    if (tag.startsWith((_e = this.dataSettings.get(16 /* Session */)) != null ? _e : "?"))
      return 16 /* Session */;
    if (tag.startsWith((_f = this.dataSettings.get(64 /* NonPlayerCharacter */)) != null ? _f : "?"))
      return 64 /* NonPlayerCharacter */;
    if (tag.startsWith((_g = this.dataSettings.get(32 /* Character */)) != null ? _g : "?"))
      return 32 /* Character */;
    if (tag.startsWith((_h = this.dataSettings.get(512 /* Clue */)) != null ? _h : "?"))
      return 512 /* Clue */;
    if (tag.startsWith((_i = this.dataSettings.get(128 /* Location */)) != null ? _i : "?"))
      return 128 /* Location */;
    if (tag.startsWith((_j = this.dataSettings.get(1024 /* Faction */)) != null ? _j : "?"))
      return 1024 /* Faction */;
    if (tag.startsWith((_k = this.dataSettings.get(256 /* Event */)) != null ? _k : "?"))
      return 256 /* Event */;
    if (tag.startsWith((_l = this.dataSettings.get(2048 /* Music */)) != null ? _l : "?"))
      return 2048 /* Music */;
    if (tag.startsWith((_m = this.dataSettings.get(4096 /* Subplot */)) != null ? _m : "?"))
      return 4096 /* Subplot */;
    return void 0;
  }
  hasRpgManagerTags(tags) {
    for (let tagIndex = 0; tagIndex < tags.length; tagIndex++) {
      if (this.isRpgManagerTag(tags[tagIndex]))
        return true;
    }
    return false;
  }
  isRpgManagerTag(tag) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
    if (tag == null)
      throw new Error("");
    if (tag.startsWith((_a = this.dataSettings.get(1 /* Campaign */)) != null ? _a : "?"))
      return true;
    if (tag.startsWith((_b = this.dataSettings.get(2 /* Adventure */)) != null ? _b : "?"))
      return true;
    if (tag.startsWith((_c = this.dataSettings.get(4 /* Act */)) != null ? _c : "?"))
      return true;
    if (tag.startsWith((_d = this.dataSettings.get(8 /* Scene */)) != null ? _d : "?"))
      return true;
    if (tag.startsWith((_e = this.dataSettings.get(16 /* Session */)) != null ? _e : "?"))
      return true;
    if (tag.startsWith((_f = this.dataSettings.get(64 /* NonPlayerCharacter */)) != null ? _f : "?"))
      return true;
    if (tag.startsWith((_g = this.dataSettings.get(32 /* Character */)) != null ? _g : "?"))
      return true;
    if (tag.startsWith((_h = this.dataSettings.get(512 /* Clue */)) != null ? _h : "?"))
      return true;
    if (tag.startsWith((_i = this.dataSettings.get(128 /* Location */)) != null ? _i : "?"))
      return true;
    if (tag.startsWith((_j = this.dataSettings.get(1024 /* Faction */)) != null ? _j : "?"))
      return true;
    if (tag.startsWith((_k = this.dataSettings.get(256 /* Event */)) != null ? _k : "?"))
      return true;
    if (tag.startsWith((_l = this.dataSettings.get(2048 /* Music */)) != null ? _l : "?"))
      return true;
    return tag.startsWith((_m = this.dataSettings.get(4096 /* Subplot */)) != null ? _m : "?");
  }
  getId(type, tag) {
    let response = void 0;
    const tagType = this.getDataType(tag);
    if (tagType === void 0)
      return void 0;
    const settings = this.dataSettings.get(tagType);
    if (settings === void 0)
      return void 0;
    const ids = tag.substring(settings.length + 1);
    if (ids === "")
      return void 0;
    const tagIds = ids.split("/");
    switch (type) {
      case 1 /* Campaign */:
        response = tagIds[0] ? tagIds[0] : void 0;
        break;
      case 2 /* Adventure */:
        response = +tagIds[1] ? tagIds[1] : void 0;
        break;
      case 16 /* Session */:
        response = +tagIds[1] ? tagIds[1] : void 0;
        break;
      case 4 /* Act */:
        response = +tagIds[2] ? tagIds[2] : void 0;
        break;
      case 8 /* Scene */:
        response = +tagIds[3] ? tagIds[3] : void 0;
        break;
    }
    return response;
  }
  getTag(tags) {
    if (tags == null)
      return void 0;
    let response;
    tags.forEach((tag) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
      if (tag !== null && typeof tag === "string") {
        if (tag.startsWith((_a = this.dataSettings.get(1 /* Campaign */)) != null ? _a : "?"))
          response = tag;
        if (tag.startsWith((_b = this.dataSettings.get(2 /* Adventure */)) != null ? _b : "?"))
          response = tag;
        if (tag.startsWith((_c = this.dataSettings.get(4 /* Act */)) != null ? _c : "?"))
          response = tag;
        if (tag.startsWith((_d = this.dataSettings.get(8 /* Scene */)) != null ? _d : "?"))
          response = tag;
        if (tag.startsWith((_e = this.dataSettings.get(16 /* Session */)) != null ? _e : "?"))
          response = tag;
        if (tag.startsWith((_f = this.dataSettings.get(64 /* NonPlayerCharacter */)) != null ? _f : "?"))
          response = tag;
        if (tag.startsWith((_g = this.dataSettings.get(32 /* Character */)) != null ? _g : "?"))
          response = tag;
        if (tag.startsWith((_h = this.dataSettings.get(512 /* Clue */)) != null ? _h : "?"))
          response = tag;
        if (tag.startsWith((_i = this.dataSettings.get(128 /* Location */)) != null ? _i : "?"))
          response = tag;
        if (tag.startsWith((_j = this.dataSettings.get(1024 /* Faction */)) != null ? _j : "?"))
          response = tag;
        if (tag.startsWith((_k = this.dataSettings.get(256 /* Event */)) != null ? _k : "?"))
          response = tag;
        if (tag.startsWith((_l = this.dataSettings.get(2048 /* Music */)) != null ? _l : "?"))
          response = tag;
        if (tag.startsWith((_m = this.dataSettings.get(4096 /* Subplot */)) != null ? _m : "?"))
          response = tag;
      }
    });
    return response;
  }
  fuzzyTagGuesser(tag) {
    const response = void 0;
    const oldCampaignTag = this.api.settings.campaignTag;
    const oldAdventureTag = this.api.settings.adventureTag;
    const oldActTag = this.api.settings.actTag;
    const oldSceneTag = this.api.settings.sceneTag;
    const oldSessionTag = this.api.settings.sessionTag;
    const oldSubplotTag = this.api.settings.subplotTag;
    const oldPcTag = this.api.settings.pcTag;
    const oldNpcTag = this.api.settings.npcTag;
    const oldClueTag = this.api.settings.clueTag;
    const oldEventTag = this.api.settings.eventTag;
    const oldLocationTag = this.api.settings.locationTag;
    const oldFactionTag = this.api.settings.factionTag;
    const oldMusicTag = this.api.settings.musicTag;
    if (oldCampaignTag !== void 0 && tag.startsWith(oldCampaignTag))
      return { tag: oldCampaignTag, type: 1 /* Campaign */ };
    if (oldAdventureTag !== void 0 && tag.startsWith(oldAdventureTag))
      return { tag: oldAdventureTag, type: 2 /* Adventure */ };
    if (oldActTag !== void 0 && tag.startsWith(oldActTag))
      return { tag: oldActTag, type: 4 /* Act */ };
    if (oldSceneTag !== void 0 && tag.startsWith(oldSceneTag))
      return { tag: oldSceneTag, type: 8 /* Scene */ };
    if (oldSessionTag !== void 0 && tag.startsWith(oldSessionTag))
      return { tag: oldSessionTag, type: 16 /* Session */ };
    if (oldSubplotTag !== void 0 && tag.startsWith(oldSubplotTag))
      return { tag: oldSubplotTag, type: 4096 /* Subplot */ };
    if (oldPcTag !== void 0 && tag.startsWith(oldPcTag))
      return { tag: oldPcTag, type: 32 /* Character */ };
    if (oldNpcTag !== void 0 && tag.startsWith(oldNpcTag))
      return { tag: oldNpcTag, type: 64 /* NonPlayerCharacter */ };
    if (oldClueTag !== void 0 && tag.startsWith(oldClueTag))
      return { tag: oldClueTag, type: 512 /* Clue */ };
    if (oldEventTag !== void 0 && tag.startsWith(oldEventTag))
      return { tag: oldEventTag, type: 256 /* Event */ };
    if (oldLocationTag !== void 0 && tag.startsWith(oldLocationTag))
      return { tag: oldLocationTag, type: 128 /* Location */ };
    if (oldFactionTag !== void 0 && tag.startsWith(oldFactionTag))
      return { tag: oldFactionTag, type: 1024 /* Faction */ };
    if (oldMusicTag !== void 0 && tag.startsWith(oldMusicTag))
      return { tag: oldMusicTag, type: 2048 /* Music */ };
    if (tag.startsWith("rpgm/outline/campaign"))
      return { tag, type: 1 /* Campaign */ };
    if (tag.startsWith("rpgm/outline/adventure"))
      return { tag, type: 2 /* Adventure */ };
    if (tag.startsWith("rpgm/outline/act"))
      return { tag, type: 4 /* Act */ };
    if (tag.startsWith("rpgm/outline/scene"))
      return { tag, type: 8 /* Scene */ };
    if (tag.startsWith("rpgm/outline/session"))
      return { tag, type: 16 /* Session */ };
    if (tag.startsWith("rpgm/outline/subplot"))
      return { tag, type: 4096 /* Subplot */ };
    if (tag.startsWith("rpgm/element/character/pc"))
      return { tag, type: 32 /* Character */ };
    if (tag.startsWith("rpgm/element/character/npc"))
      return { tag, type: 64 /* NonPlayerCharacter */ };
    if (tag.startsWith("rpgm/element/clue"))
      return { tag, type: 512 /* Clue */ };
    if (tag.startsWith("rpgm/element/event"))
      return { tag, type: 256 /* Event */ };
    if (tag.startsWith("rpgm/element/location"))
      return { tag, type: 128 /* Location */ };
    if (tag.startsWith("rpgm/element/faction"))
      return { tag, type: 1024 /* Faction */ };
    if (tag.startsWith("rpgm/element/music"))
      return { tag, type: 2048 /* Music */ };
    if (tag.toLowerCase().indexOf("campaign") !== -1)
      return { tag, type: 1 /* Campaign */ };
    if (tag.toLowerCase().indexOf("adventure") !== -1)
      return { tag, type: 2 /* Adventure */ };
    if (tag.toLowerCase().indexOf("act") !== -1)
      return { tag, type: 4 /* Act */ };
    if (tag.toLowerCase().indexOf("scene") !== -1)
      return { tag, type: 8 /* Scene */ };
    if (tag.toLowerCase().indexOf("session") !== -1)
      return { tag, type: 16 /* Session */ };
    if (tag.toLowerCase().indexOf("subplot") !== -1)
      return { tag, type: 4096 /* Subplot */ };
    if (tag.toLowerCase().indexOf("pc") !== -1)
      return { tag, type: 32 /* Character */ };
    if (tag.toLowerCase().indexOf("npc") !== -1)
      return { tag, type: 64 /* NonPlayerCharacter */ };
    if (tag.toLowerCase().indexOf("clue") !== -1)
      return { tag, type: 512 /* Clue */ };
    if (tag.toLowerCase().indexOf("event") !== -1)
      return { tag, type: 256 /* Event */ };
    if (tag.toLowerCase().indexOf("location") !== -1)
      return { tag, type: 128 /* Location */ };
    if (tag.toLowerCase().indexOf("faction") !== -1)
      return { tag, type: 1024 /* Faction */ };
    if (tag.toLowerCase().indexOf("music") !== -1)
      return { tag, type: 2048 /* Music */ };
    return response;
  }
  fuzzyTagsGuesser(tags) {
    if (tags == null)
      return void 0;
    let response;
    for (let index = 0; index < tags.length; index++) {
      response = this.fuzzyTagGuesser(tags[index]);
      if (response !== void 0 && response.tag.indexOf("rpgm") === -1)
        response = void 0;
    }
    if (response !== void 0) {
      for (let index = 0; index < tags.length; index++) {
        if (tags[index].startsWith(response.tag))
          response.tag = tags[index];
      }
    }
    return response;
  }
  getTemplateDataType(tags) {
    if (tags == null)
      return void 0;
    let response = 0;
    tags.forEach((tag) => {
      if (tag.startsWith("rpgm/template/" + ComponentType[1 /* Campaign */].toLowerCase()))
        response += 1 /* Campaign */;
      if (tag.startsWith("rpgm/template/" + ComponentType[2 /* Adventure */].toLowerCase()))
        response += 2 /* Adventure */;
      if (tag.startsWith("rpgm/template/" + ComponentType[4 /* Act */].toLowerCase()))
        response += 4 /* Act */;
      if (tag.startsWith("rpgm/template/" + ComponentType[8 /* Scene */].toLowerCase()))
        response += 8 /* Scene */;
      if (tag.startsWith("rpgm/template/" + ComponentType[16 /* Session */].toLowerCase()))
        response += 16 /* Session */;
      if (tag.startsWith("rpgm/template/" + ComponentType[64 /* NonPlayerCharacter */].toLowerCase()))
        response += 64 /* NonPlayerCharacter */;
      if (tag.startsWith("rpgm/template/" + ComponentType[32 /* Character */].toLowerCase()))
        response += 32 /* Character */;
      if (tag.startsWith("rpgm/template/" + ComponentType[512 /* Clue */].toLowerCase()))
        response += 512 /* Clue */;
      if (tag.startsWith("rpgm/template/" + ComponentType[128 /* Location */].toLowerCase()))
        response += 128 /* Location */;
      if (tag.startsWith("rpgm/template/" + ComponentType[1024 /* Faction */].toLowerCase()))
        response += 1024 /* Faction */;
      if (tag.startsWith("rpgm/template/" + ComponentType[256 /* Event */].toLowerCase()))
        response += 256 /* Event */;
      if (tag.startsWith("rpgm/template/" + ComponentType[2048 /* Music */].toLowerCase()))
        response += 2048 /* Music */;
      if (tag.startsWith("rpgm/template/" + ComponentType[4096 /* Subplot */].toLowerCase()))
        response += 4096 /* Subplot */;
    });
    if (response === 0)
      return void 0;
    return response;
  }
};
var TagService = _TagService;
TagService.campaignTag = "rpgm/campaign";
TagService.adventureTag = "rpgm/adventure";
TagService.actTag = "rpgm/act";
TagService.sceneTag = "rpgm/scene";
TagService.sessionTag = "rpgm/session";
TagService.npcTag = "rpgm/npc";
TagService.pcTag = "rpgm/pc";
TagService.locationTag = "rpgm/location";
TagService.factionTag = "rpgm/faction";
TagService.eventTag = "rpgm/event";
TagService.clueTag = "rpgm/clue";
TagService.musicTag = "rpgm/music";
TagService.subplotTag = "rpgm/subplot";

// src/core/modals/CreationModal.ts
var CreationModal = class extends import_obsidian2.Modal {
  constructor(api, type, _create = true, _name = null, campaignId, parentId) {
    super(app);
    this.api = api;
    this.type = type;
    this._create = _create;
    this._name = _name;
    this.campaignSetting = 0 /* Agnostic */;
    this.availableSpecificTemplates = [];
    this.availableGenericTemplates = [];
    this.scope = new import_obsidian2.Scope();
    this.scope.register([], "Escape", (evt) => {
      evt.preventDefault();
    });
    if (campaignId !== void 0) {
      this.campaignId = campaignId;
      if (parentId !== void 0) {
        if (type === 4 /* Act */) {
          this.adventureId = parentId;
        }
        if (type === 8 /* Scene */) {
          this.actId = parentId;
          try {
            const act = this.api.database.readById(parentId);
            this.adventureId = act.index.parentId;
          } catch (e) {
          }
        }
      }
    }
    this.app.vault.getFiles().filter((file) => file.parent.path === this.app.plugins.getPlugin("rpg-manager").settings.templateFolder).forEach((file) => {
      var _a, _b;
      const metadata = this.app.metadataCache.getFileCache(file);
      if (metadata != null) {
        const tags = this.api.service(TagService).sanitiseTags((_a = metadata.frontmatter) == null ? void 0 : _a.tags);
        if (tags.length > 0) {
          const tags2 = this.api.service(TagService).sanitiseTags((_b = metadata.frontmatter) == null ? void 0 : _b.tags);
          const templateType = this.api.service(TagService).getTemplateDataType(tags2);
          if (templateType == void 0 || (templateType & this.type) === this.type)
            this.availableGenericTemplates.push(file);
        } else {
          this.availableGenericTemplates.push(file);
        }
      }
    });
  }
  onOpen() {
    super.onOpen();
    const { contentEl } = this;
    contentEl.empty();
    contentEl.addClass("rpg-manager-modal");
    if (!this._create && this.app.workspace.getActiveViewOfType(import_obsidian2.MarkdownView) == null) {
      contentEl.createEl("h2", { cls: "rpgm-modal-title", text: "Error" });
      contentEl.createSpan({ cls: "", text: "To fill a note with a RPG Manager element you must have a valid file opened." });
      return;
    }
    contentEl.createEl("h2", { cls: "rpgm-modal-title", text: "Create New " + ComponentType[this.type] });
    const gridEl = contentEl.createDiv({ cls: "rpg-manager-modal-grid" });
    const navigationEl = gridEl.createDiv({ cls: "rpg-manager-modal-grid-navigation" });
    this.additionalInformationEl = gridEl.createDiv({ cls: "rpg-manager-modal-grid-additional-elements" });
    const titleEl = navigationEl.createDiv({ cls: "rpgm-input-title" });
    titleEl.createEl("label", { text: "Title of your new " + ComponentType[this.type] });
    this.title = titleEl.createEl("input", { type: "text" });
    if (this._name !== null) {
      this.title.value = this._name;
    }
    this.titleError = navigationEl.createEl("p", { cls: "error", text: "Please specify a valid title" });
    const selectionTitleEl = navigationEl.createDiv({ cls: "rpgm-input-title" });
    selectionTitleEl.createEl("label", { text: "Template to use" });
    this.templateEl = selectionTitleEl.createEl("select");
    this.templateEl.createEl("option", {
      text: "",
      value: ""
    });
    this.templateEl.createEl("option", {
      text: "RpgManager default " + ComponentType[this.type] + " template",
      value: "internal" + ComponentType[this.type]
    }).selected = true;
    this.templateEl.createEl("option", {
      text: "",
      value: ""
    });
    if (this.availableSpecificTemplates.length > 0) {
      const templateOptionEl = this.templateEl.createEl("option", {
        text: ComponentType[this.type] + "-specific frontmatter"
      });
      templateOptionEl.disabled = true;
      this.availableSpecificTemplates.forEach((file) => {
        this.templateEl.createEl("option", {
          text: file.basename,
          value: file.path
        });
      });
      this.templateEl.createEl("option", {
        text: "",
        value: ""
      });
    }
    if (this.availableGenericTemplates.length > 0) {
      const templateOptionEl = this.templateEl.createEl("option", {
        text: "Generic frontmatter"
      });
      templateOptionEl.disabled = true;
      this.availableGenericTemplates.forEach((file) => {
        this.templateEl.createEl("option", {
          text: file.basename,
          value: file.path
        });
      });
    }
    this.campaignModal = this.api.modals.getPartial(this.campaignSetting, 1 /* Campaign */, this);
    const childElement = navigationEl.createDiv();
    this.button = contentEl.createEl("button", { cls: "mod-cta", text: "Create" });
    if (this.type !== 1 /* Campaign */) {
      this.button.disabled = true;
    }
    this.button.addEventListener("click", (e) => {
      this._save();
    });
    this.campaignModal.addElement(childElement);
    titleEl.addEventListener("keypress", function(event) {
      if (event.key === "Enter")
        this.button.click();
    }.bind(this));
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
    super.onClose();
  }
  _save() {
    return __async(this, null, function* () {
      if (this.title.value === "") {
        this.titleError.style.display = "block";
        return;
      }
      if (!this.campaignModal.validate())
        return;
      if (this.adventureModal != null && !this.adventureModal.validate())
        return;
      if (this.actModal != null && !this.actModal.validate())
        return;
      if (this.sceneModal != null && !this.sceneModal.validate())
        return;
      if (this.sessionModal != null && !this.sessionModal.validate())
        return;
      if (this.elementModal != null && !this.elementModal.validate())
        return;
      this.saver.save(this.campaignSetting, this.type, this._create, this.templateEl.value, this.title.value, this.campaignId, this.adventureId, this.actId, this.sceneId, this.sessionId, this.saver.prepareAdditionalInformation());
      this.close();
    });
  }
  enableButton() {
    this.button.disabled = false;
  }
  getContentEl() {
    const { contentEl } = this;
    return contentEl;
  }
};

// src/services/relationshipsService/enums/TableField.ts
var tableFieldName = /* @__PURE__ */ new Map([
  [0 /* Index */, "Index"],
  [1 /* Image */, "Image"],
  [2 /* Name */, "Name"],
  [3 /* Age */, "Age"],
  [4 /* Synopsis */, "Synopsis"],
  [5 /* Found */, "Found"],
  [6 /* Date */, "Date"],
  [7 /* Url */, "Url"],
  [8 /* StoryCircleIndicator */, "Story Circle Indicator"],
  [11 /* Duration */, "Duration"],
  [12 /* SceneType */, "Type"],
  [13 /* SceneExciting */, "Exciting?"]
]);

// src/settings/interfaces/RpgManagerSettingsInterface.ts
var rpgManagerDefaultSettings = {
  automaticMove: true,
  templateFolder: "",
  imagesFolder: "",
  YouTubeKey: "",
  previousVersion: "",
  usePlotStructures: false,
  useSceneAnalyser: false,
  advanced: {
    Agnostic: {
      ActList: {
        title: "Acts",
        defaultVisible: true,
        fields: [
          { field: 0 /* Index */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      AdventureList: {
        title: "Adventures",
        defaultVisible: true,
        fields: [
          { field: 0 /* Index */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      CharacterList: {
        title: "Player Characters",
        defaultVisible: true,
        fields: [
          { field: 1 /* Image */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 3 /* Age */, checked: true, required: false },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      ClueList: {
        title: "Clues",
        defaultVisible: true,
        fields: [
          { field: 1 /* Image */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 5 /* Found */, checked: true, required: false },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      EventList: {
        title: "Events",
        defaultVisible: true,
        fields: [
          { field: 1 /* Image */, checked: false, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 6 /* Date */, checked: true, required: false },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      FactionList: {
        title: "Factions",
        defaultVisible: true,
        fields: [
          { field: 1 /* Image */, checked: false, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      LocationList: {
        title: "Locations",
        defaultVisible: true,
        fields: [
          { field: 1 /* Image */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      MusicList: {
        title: "Musics",
        defaultVisible: true,
        fields: [
          { field: 1 /* Image */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 7 /* Url */, checked: true, required: true },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      NonPlayerCharacterList: {
        title: "Non Player Characters",
        defaultVisible: true,
        fields: [
          { field: 1 /* Image */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 3 /* Age */, checked: true, required: false },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      SceneList: {
        title: "Scenes",
        defaultVisible: true,
        fields: [
          { field: 0 /* Index */, checked: true, required: false },
          { field: 8 /* StoryCircleIndicator */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 4 /* Synopsis */, checked: true, required: false },
          { field: 6 /* Date */, checked: true, required: false },
          { field: 11 /* Duration */, checked: false, required: false },
          { field: 12 /* SceneType */, checked: false, required: false },
          { field: 13 /* SceneExciting */, checked: false, required: false }
        ]
      },
      SessionList: {
        title: "Sessions",
        defaultVisible: true,
        fields: [
          { field: 0 /* Index */, checked: true, required: false },
          { field: 2 /* Name */, checked: true, required: true },
          { field: 6 /* Date */, checked: true, required: false },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      },
      SubplotList: {
        title: "Subplots",
        defaultVisible: false,
        fields: [
          { field: 2 /* Name */, checked: true, required: true },
          { field: 4 /* Synopsis */, checked: true, required: false }
        ]
      }
    }
  }
};

// src/settings/RpgManagerSettings.ts
var import_obsidian7 = require("obsidian");

// src/managers/databaseManager/modals/DatabaseErrorModal.ts
var import_obsidian4 = require("obsidian");

// src/managers/modalsManager/abstracts/AbstractModal.ts
var import_obsidian3 = require("obsidian");
var AbstractModal = class extends import_obsidian3.Modal {
  constructor(api) {
    super(api.app);
    this.api = api;
    this.maxWidth = false;
    this.scope = new import_obsidian3.Scope();
    this.scope.register([], "Escape", (evt) => {
      evt.preventDefault();
    });
  }
  onOpen() {
    var _a;
    super.onOpen();
    const { contentEl } = this;
    contentEl.empty();
    contentEl.addClass("rpg-manager-modal");
    if (this.maxWidth)
      this.modalEl.style.width = "var(--modal-max-width)";
    const mainContainer = contentEl.createDiv({ cls: "rpg-manager-modal-container" });
    mainContainer.createEl("h2", { text: (_a = this.title) != null ? _a : "RPG Manager" });
    this.rpgmContainerEl = mainContainer.createDiv({ cls: "rpg-manager-modal-main-container" });
  }
};

// src/managers/databaseManager/modals/DatabaseErrorModal.ts
var DatabaseErrorModal = class extends AbstractModal {
  constructor(api, _misconfiguredTags, _singleError = void 0, _singleErrorFile = void 0) {
    super(api);
    this._misconfiguredTags = _misconfiguredTags;
    this._singleError = _singleError;
    this._singleErrorFile = _singleErrorFile;
  }
  onOpen() {
    super.onOpen();
    const { contentEl } = this;
    contentEl.empty();
    contentEl.createEl("h1", { cls: "error", text: "RPG Manager Error" });
    if (this._singleError !== void 0 && this._singleErrorFile !== void 0 && this._misconfiguredTags === void 0) {
      this._misconfiguredTags = /* @__PURE__ */ new Map();
      this._misconfiguredTags.set(this._singleErrorFile, this._singleError);
    }
    if (this._misconfiguredTags === void 0)
      this._misconfiguredTags = /* @__PURE__ */ new Map();
    contentEl.createEl("p", { text: "One or more of the tags that define an outline or an element are not correctly configured and can't be read!" });
    contentEl.createEl("p", { text: "Please double check the errors and correct them." });
    this._misconfiguredTags.forEach((error, file) => {
      var _a;
      const errorEl = contentEl.createEl("div");
      const title = (_a = error.getErrorTitle()) != null ? _a : file.basename;
      import_obsidian4.MarkdownRenderer.renderMarkdown("**" + title + "**\n" + error.showErrorMessage(), errorEl, file.path, null);
    });
    const viewErrorsButtonEl = contentEl.createEl("button", { text: "Fix errors" });
    viewErrorsButtonEl.addEventListener("click", () => {
      this.api.staticViews.create("rpgm-error-view" /* Errors */, [this._misconfiguredTags]);
      this.close();
    });
  }
  onClose() {
    super.onClose();
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/core/errors/abstracts/AbstractRpgManagerError.ts
var AbstractRpgManagerError = class extends Error {
  constructor(api, index) {
    super();
    this.api = api;
    this.index = index;
  }
  getErrorTitle() {
    return void 0;
  }
  getErrorLinks() {
    return void 0;
  }
};

// src/core/errors/ComponentDuplicatedError.ts
var ComponentDuplicatedError = class extends AbstractRpgManagerError {
  constructor(api, idMap, _duplication, _duplicated = void 0) {
    super(api, idMap);
    this._duplication = _duplication;
    this._duplicated = _duplicated;
  }
  getErrorTitle() {
    return "Duplicated outline indexService";
  }
  showErrorMessage() {
    var _a;
    let response = "";
    if (this._duplication.length > 1) {
      this._duplication.forEach((component) => {
        response += " - " + component.file.basename + "\n";
      });
    } else if (this._duplicated !== void 0) {
      response += " - " + this._duplication[0].file.basename + "\n - " + ((_a = this._duplicated) == null ? void 0 : _a.file.basename) + "\n";
    }
    return response;
  }
  showErrorActions() {
    const response = "Two or more outlines have the same tag. The identifier of the outline must be unique\nPlease change one of the following:\n";
    return response;
  }
  getErrorLinks() {
    var _a;
    const response = [];
    if (this._duplication.length > 1) {
      this._duplication.forEach((component) => {
        response.push(component.file.path);
      });
    } else if (this._duplicated !== void 0) {
      response.push(this._duplication[0].file.path);
      response.push((_a = this._duplicated) == null ? void 0 : _a.file.path);
    }
    return response;
  }
};

// node_modules/ts-md5/dist/esm/md5.js
var Md5 = class {
  constructor() {
    this._dataLength = 0;
    this._bufferLength = 0;
    this._state = new Int32Array(4);
    this._buffer = new ArrayBuffer(68);
    this._buffer8 = new Uint8Array(this._buffer, 0, 68);
    this._buffer32 = new Uint32Array(this._buffer, 0, 17);
    this.start();
  }
  static hashStr(str, raw = false) {
    return this.onePassHasher.start().appendStr(str).end(raw);
  }
  static hashAsciiStr(str, raw = false) {
    return this.onePassHasher.start().appendAsciiStr(str).end(raw);
  }
  static _hex(x) {
    const hc = Md5.hexChars;
    const ho = Md5.hexOut;
    let n2;
    let offset2;
    let j;
    let i;
    for (i = 0; i < 4; i += 1) {
      offset2 = i * 8;
      n2 = x[i];
      for (j = 0; j < 8; j += 2) {
        ho[offset2 + 1 + j] = hc.charAt(n2 & 15);
        n2 >>>= 4;
        ho[offset2 + 0 + j] = hc.charAt(n2 & 15);
        n2 >>>= 4;
      }
    }
    return ho.join("");
  }
  static _md5cycle(x, k) {
    let a = x[0];
    let b = x[1];
    let c = x[2];
    let d = x[3];
    a += (b & c | ~b & d) + k[0] - 680876936 | 0;
    a = (a << 7 | a >>> 25) + b | 0;
    d += (a & b | ~a & c) + k[1] - 389564586 | 0;
    d = (d << 12 | d >>> 20) + a | 0;
    c += (d & a | ~d & b) + k[2] + 606105819 | 0;
    c = (c << 17 | c >>> 15) + d | 0;
    b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
    b = (b << 22 | b >>> 10) + c | 0;
    a += (b & c | ~b & d) + k[4] - 176418897 | 0;
    a = (a << 7 | a >>> 25) + b | 0;
    d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
    d = (d << 12 | d >>> 20) + a | 0;
    c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
    c = (c << 17 | c >>> 15) + d | 0;
    b += (c & d | ~c & a) + k[7] - 45705983 | 0;
    b = (b << 22 | b >>> 10) + c | 0;
    a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
    a = (a << 7 | a >>> 25) + b | 0;
    d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
    d = (d << 12 | d >>> 20) + a | 0;
    c += (d & a | ~d & b) + k[10] - 42063 | 0;
    c = (c << 17 | c >>> 15) + d | 0;
    b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
    b = (b << 22 | b >>> 10) + c | 0;
    a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
    a = (a << 7 | a >>> 25) + b | 0;
    d += (a & b | ~a & c) + k[13] - 40341101 | 0;
    d = (d << 12 | d >>> 20) + a | 0;
    c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
    c = (c << 17 | c >>> 15) + d | 0;
    b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
    b = (b << 22 | b >>> 10) + c | 0;
    a += (b & d | c & ~d) + k[1] - 165796510 | 0;
    a = (a << 5 | a >>> 27) + b | 0;
    d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
    d = (d << 9 | d >>> 23) + a | 0;
    c += (d & b | a & ~b) + k[11] + 643717713 | 0;
    c = (c << 14 | c >>> 18) + d | 0;
    b += (c & a | d & ~a) + k[0] - 373897302 | 0;
    b = (b << 20 | b >>> 12) + c | 0;
    a += (b & d | c & ~d) + k[5] - 701558691 | 0;
    a = (a << 5 | a >>> 27) + b | 0;
    d += (a & c | b & ~c) + k[10] + 38016083 | 0;
    d = (d << 9 | d >>> 23) + a | 0;
    c += (d & b | a & ~b) + k[15] - 660478335 | 0;
    c = (c << 14 | c >>> 18) + d | 0;
    b += (c & a | d & ~a) + k[4] - 405537848 | 0;
    b = (b << 20 | b >>> 12) + c | 0;
    a += (b & d | c & ~d) + k[9] + 568446438 | 0;
    a = (a << 5 | a >>> 27) + b | 0;
    d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
    d = (d << 9 | d >>> 23) + a | 0;
    c += (d & b | a & ~b) + k[3] - 187363961 | 0;
    c = (c << 14 | c >>> 18) + d | 0;
    b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
    b = (b << 20 | b >>> 12) + c | 0;
    a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
    a = (a << 5 | a >>> 27) + b | 0;
    d += (a & c | b & ~c) + k[2] - 51403784 | 0;
    d = (d << 9 | d >>> 23) + a | 0;
    c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
    c = (c << 14 | c >>> 18) + d | 0;
    b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
    b = (b << 20 | b >>> 12) + c | 0;
    a += (b ^ c ^ d) + k[5] - 378558 | 0;
    a = (a << 4 | a >>> 28) + b | 0;
    d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
    d = (d << 11 | d >>> 21) + a | 0;
    c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
    c = (c << 16 | c >>> 16) + d | 0;
    b += (c ^ d ^ a) + k[14] - 35309556 | 0;
    b = (b << 23 | b >>> 9) + c | 0;
    a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
    a = (a << 4 | a >>> 28) + b | 0;
    d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
    d = (d << 11 | d >>> 21) + a | 0;
    c += (d ^ a ^ b) + k[7] - 155497632 | 0;
    c = (c << 16 | c >>> 16) + d | 0;
    b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
    b = (b << 23 | b >>> 9) + c | 0;
    a += (b ^ c ^ d) + k[13] + 681279174 | 0;
    a = (a << 4 | a >>> 28) + b | 0;
    d += (a ^ b ^ c) + k[0] - 358537222 | 0;
    d = (d << 11 | d >>> 21) + a | 0;
    c += (d ^ a ^ b) + k[3] - 722521979 | 0;
    c = (c << 16 | c >>> 16) + d | 0;
    b += (c ^ d ^ a) + k[6] + 76029189 | 0;
    b = (b << 23 | b >>> 9) + c | 0;
    a += (b ^ c ^ d) + k[9] - 640364487 | 0;
    a = (a << 4 | a >>> 28) + b | 0;
    d += (a ^ b ^ c) + k[12] - 421815835 | 0;
    d = (d << 11 | d >>> 21) + a | 0;
    c += (d ^ a ^ b) + k[15] + 530742520 | 0;
    c = (c << 16 | c >>> 16) + d | 0;
    b += (c ^ d ^ a) + k[2] - 995338651 | 0;
    b = (b << 23 | b >>> 9) + c | 0;
    a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
    a = (a << 6 | a >>> 26) + b | 0;
    d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
    d = (d << 10 | d >>> 22) + a | 0;
    c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
    c = (c << 15 | c >>> 17) + d | 0;
    b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
    b = (b << 21 | b >>> 11) + c | 0;
    a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
    a = (a << 6 | a >>> 26) + b | 0;
    d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
    d = (d << 10 | d >>> 22) + a | 0;
    c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
    c = (c << 15 | c >>> 17) + d | 0;
    b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
    b = (b << 21 | b >>> 11) + c | 0;
    a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
    a = (a << 6 | a >>> 26) + b | 0;
    d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
    d = (d << 10 | d >>> 22) + a | 0;
    c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
    c = (c << 15 | c >>> 17) + d | 0;
    b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
    b = (b << 21 | b >>> 11) + c | 0;
    a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
    a = (a << 6 | a >>> 26) + b | 0;
    d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
    d = (d << 10 | d >>> 22) + a | 0;
    c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
    c = (c << 15 | c >>> 17) + d | 0;
    b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
    b = (b << 21 | b >>> 11) + c | 0;
    x[0] = a + x[0] | 0;
    x[1] = b + x[1] | 0;
    x[2] = c + x[2] | 0;
    x[3] = d + x[3] | 0;
  }
  start() {
    this._dataLength = 0;
    this._bufferLength = 0;
    this._state.set(Md5.stateIdentity);
    return this;
  }
  appendStr(str) {
    const buf8 = this._buffer8;
    const buf32 = this._buffer32;
    let bufLen = this._bufferLength;
    let code;
    let i;
    for (i = 0; i < str.length; i += 1) {
      code = str.charCodeAt(i);
      if (code < 128) {
        buf8[bufLen++] = code;
      } else if (code < 2048) {
        buf8[bufLen++] = (code >>> 6) + 192;
        buf8[bufLen++] = code & 63 | 128;
      } else if (code < 55296 || code > 56319) {
        buf8[bufLen++] = (code >>> 12) + 224;
        buf8[bufLen++] = code >>> 6 & 63 | 128;
        buf8[bufLen++] = code & 63 | 128;
      } else {
        code = (code - 55296) * 1024 + (str.charCodeAt(++i) - 56320) + 65536;
        if (code > 1114111) {
          throw new Error("Unicode standard supports code points up to U+10FFFF");
        }
        buf8[bufLen++] = (code >>> 18) + 240;
        buf8[bufLen++] = code >>> 12 & 63 | 128;
        buf8[bufLen++] = code >>> 6 & 63 | 128;
        buf8[bufLen++] = code & 63 | 128;
      }
      if (bufLen >= 64) {
        this._dataLength += 64;
        Md5._md5cycle(this._state, buf32);
        bufLen -= 64;
        buf32[0] = buf32[16];
      }
    }
    this._bufferLength = bufLen;
    return this;
  }
  appendAsciiStr(str) {
    const buf8 = this._buffer8;
    const buf32 = this._buffer32;
    let bufLen = this._bufferLength;
    let i;
    let j = 0;
    for (; ; ) {
      i = Math.min(str.length - j, 64 - bufLen);
      while (i--) {
        buf8[bufLen++] = str.charCodeAt(j++);
      }
      if (bufLen < 64) {
        break;
      }
      this._dataLength += 64;
      Md5._md5cycle(this._state, buf32);
      bufLen = 0;
    }
    this._bufferLength = bufLen;
    return this;
  }
  appendByteArray(input) {
    const buf8 = this._buffer8;
    const buf32 = this._buffer32;
    let bufLen = this._bufferLength;
    let i;
    let j = 0;
    for (; ; ) {
      i = Math.min(input.length - j, 64 - bufLen);
      while (i--) {
        buf8[bufLen++] = input[j++];
      }
      if (bufLen < 64) {
        break;
      }
      this._dataLength += 64;
      Md5._md5cycle(this._state, buf32);
      bufLen = 0;
    }
    this._bufferLength = bufLen;
    return this;
  }
  getState() {
    const s2 = this._state;
    return {
      buffer: String.fromCharCode.apply(null, Array.from(this._buffer8)),
      buflen: this._bufferLength,
      length: this._dataLength,
      state: [s2[0], s2[1], s2[2], s2[3]]
    };
  }
  setState(state) {
    const buf = state.buffer;
    const x = state.state;
    const s2 = this._state;
    let i;
    this._dataLength = state.length;
    this._bufferLength = state.buflen;
    s2[0] = x[0];
    s2[1] = x[1];
    s2[2] = x[2];
    s2[3] = x[3];
    for (i = 0; i < buf.length; i += 1) {
      this._buffer8[i] = buf.charCodeAt(i);
    }
  }
  end(raw = false) {
    const bufLen = this._bufferLength;
    const buf8 = this._buffer8;
    const buf32 = this._buffer32;
    const i = (bufLen >> 2) + 1;
    this._dataLength += bufLen;
    const dataBitsLen = this._dataLength * 8;
    buf8[bufLen] = 128;
    buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0;
    buf32.set(Md5.buffer32Identity.subarray(i), i);
    if (bufLen > 55) {
      Md5._md5cycle(this._state, buf32);
      buf32.set(Md5.buffer32Identity);
    }
    if (dataBitsLen <= 4294967295) {
      buf32[14] = dataBitsLen;
    } else {
      const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/);
      if (matches === null) {
        return;
      }
      const lo = parseInt(matches[2], 16);
      const hi = parseInt(matches[1], 16) || 0;
      buf32[14] = lo;
      buf32[15] = hi;
    }
    Md5._md5cycle(this._state, buf32);
    return raw ? this._state : Md5._hex(this._state);
  }
};
Md5.stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]);
Md5.buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
Md5.hexChars = "0123456789abcdef";
Md5.hexOut = [];
Md5.onePassHasher = new Md5();
if (Md5.hashStr("hello") !== "5d41402abc4b2a76b9719d911017c592") {
  throw new Error("Md5 self test failed.");
}

// src/services/indexService/Index.ts
var Index = class {
  constructor(_api, type, _id, _campaignId, _parentId) {
    this._api = _api;
    this.type = type;
    this._id = _id;
    this._campaignId = _campaignId;
    this._parentId = _parentId;
    this.campaignSettings = 0 /* Agnostic */;
    this._parentPosition = void 0;
    this.tagMap = /* @__PURE__ */ new Map();
    this.positionInParent = 1;
    if (type === 1 /* Campaign */) {
      this._campaignId = this._id;
      this._parentId = this._id;
    }
  }
  get id() {
    return this._id;
  }
  get campaignId() {
    return this._campaignId;
  }
  get parentId() {
    return this._parentId;
  }
  get parentPosition() {
    if (this._parentPosition === void 0) {
      try {
        const parent = this._api.database.readById(this._parentId);
        this._parentPosition = parent.index.positionInParent;
      } catch (e) {
        this._parentPosition = 1;
      }
    }
    return this._parentPosition;
  }
  get checksum() {
    const md5 = new Md5();
    md5.appendStr(this._id);
    md5.appendStr(this._campaignId);
    md5.appendStr(this._parentId);
    md5.appendStr(this.positionInParent.toString());
    md5.appendStr(this.campaignSettings.toString());
    md5.appendStr(this.type.toString());
    const response = md5.end();
    return response;
  }
};

// node_modules/uuid/dist/esm-browser/rng.js
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
  if (!getRandomValues) {
    getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
    if (!getRandomValues) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues(rnds8);
}

// node_modules/uuid/dist/esm-browser/stringify.js
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
  byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset2 = 0) {
  return (byteToHex[arr[offset2 + 0]] + byteToHex[arr[offset2 + 1]] + byteToHex[arr[offset2 + 2]] + byteToHex[arr[offset2 + 3]] + "-" + byteToHex[arr[offset2 + 4]] + byteToHex[arr[offset2 + 5]] + "-" + byteToHex[arr[offset2 + 6]] + byteToHex[arr[offset2 + 7]] + "-" + byteToHex[arr[offset2 + 8]] + byteToHex[arr[offset2 + 9]] + "-" + byteToHex[arr[offset2 + 10]] + byteToHex[arr[offset2 + 11]] + byteToHex[arr[offset2 + 12]] + byteToHex[arr[offset2 + 13]] + byteToHex[arr[offset2 + 14]] + byteToHex[arr[offset2 + 15]]).toLowerCase();
}

// node_modules/uuid/dist/esm-browser/native.js
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var native_default = {
  randomUUID
};

// node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset2) {
  if (native_default.randomUUID && !buf && !options) {
    return native_default.randomUUID();
  }
  options = options || {};
  const rnds = options.random || (options.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset2 = offset2 || 0;
    for (let i = 0; i < 16; ++i) {
      buf[offset2 + i] = rnds[i];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
var v4_default = v4;

// src/services/indexService/IndexService.ts
var IndexService = class extends AbstractService {
  create(type, id, campaignId, parentId, positionInParent, campaignSettings) {
    const response = new Index(this.api, type, id, campaignId, parentId);
    if (positionInParent !== void 0)
      response.positionInParent = positionInParent;
    if (campaignSettings !== void 0)
      response.campaignSettings = campaignSettings;
    return response;
  }
  createFromIndex(index) {
    const response = this.create(index.type, index.id, index.campaignId, index.parentId, index.positionInParent, index.campaignSettings);
    return response;
  }
  createUUID() {
    return v4_default();
  }
};

// src/services/loggerService/enums/LogMessageType.ts
var LogMessageType = /* @__PURE__ */ ((LogMessageType2) => {
  LogMessageType2[LogMessageType2["System"] = 1] = "System";
  LogMessageType2[LogMessageType2["Database"] = 2] = "Database";
  LogMessageType2[LogMessageType2["DatabaseInitialisation"] = 4] = "DatabaseInitialisation";
  LogMessageType2[LogMessageType2["ComponentInitialisation"] = 8] = "ComponentInitialisation";
  LogMessageType2[LogMessageType2["Updater"] = 16] = "Updater";
  LogMessageType2[LogMessageType2["TagUpdates"] = 32] = "TagUpdates";
  LogMessageType2[LogMessageType2["SessionSceneLink"] = 64] = "SessionSceneLink";
  LogMessageType2[LogMessageType2["Model"] = 128] = "Model";
  LogMessageType2[LogMessageType2["TagManagement"] = 256] = "TagManagement";
  LogMessageType2[LogMessageType2["Performance"] = 512] = "Performance";
  return LogMessageType2;
})(LogMessageType || {});

// src/services/loggerService/loggers/ConsoleLogger.ts
var ConsoleLogger = class {
  constructor(_api) {
    this._api = _api;
    this._debuggableTypes = 2 /* Warning */ | 4 /* Error */;
    this._isDebug = this._api.version.indexOf("-") !== -1;
  }
  maybeWriteLog(log, duration2 = void 0) {
    return __async(this, null, function* () {
      if (this._isDebug || (log.type & this._debuggableTypes) === log.type) {
        let messageContent = log.message;
        let messageHeader;
        if (messageContent.startsWith("\x1B")) {
          messageHeader = messageContent.substring(0, messageContent.indexOf("\x1B[0m") + 6) + "\n";
          messageContent = messageContent.substring(messageContent.indexOf("\x1B[0m") + 6);
        }
        const data = [
          messageContent + "\n"
        ];
        if (log.object !== void 0)
          data.push(log.object);
        switch (log.type) {
          case 1 /* Info */:
            if (messageHeader !== void 0) {
              console.info("\x1B[38;2;102;178;155mRPG Manager: " + LogMessageType[log.messageType] + "\x1B[0m\n" + messageHeader, ...data);
            } else {
              console.info("\x1B[38;2;102;178;155mRPG Manager: " + LogMessageType[log.messageType] + "\x1B[0m\n", ...data);
            }
            break;
          case 4 /* Error */:
            console.error(...data);
            break;
          default:
            console.warn(...data);
            break;
        }
      }
    });
  }
  maybeWriteLogList(group) {
    return __async(this, null, function* () {
      let maxLogType = 1 /* Info */;
      if (group.logs.length > 0) {
        const messageContent = [];
        const messageType = group.logs[0].messageType;
        const totalDuration = Date.now() - group.start;
        for (let index = 0; index < group.logs.length; index++) {
          if (index === 0) {
            group.logs[0].duration = group.logs[index].start - group.start;
          } else {
            group.logs[index].duration = group.logs[index].start - group.logs[index - 1].start;
          }
          messageContent.push(group.logs[index].message + " in " + group.logs[index].duration + "ms\n");
          if (group.logs[index].object !== void 0)
            messageContent.push(group.logs[index].object);
          if (group.logs[index].type > maxLogType)
            maxLogType = group.logs[index].type;
        }
        switch (maxLogType) {
          case 1 /* Info */:
            console.info("\x1B[38;2;102;178;155mRPG Manager: " + LogMessageType[messageType] + " (" + totalDuration / 1e3 + "s)\x1B[0m\n", ...messageContent);
            break;
          case 4 /* Error */:
            console.error(...messageContent);
            break;
          default:
            console.warn(...messageContent);
            break;
        }
      }
    });
  }
};

// src/services/loggerService/abstracts/AbstractLogMessage.ts
var AbstractLogMessage = class {
  constructor(type, messageType, message, object) {
    this.type = type;
    this.messageType = messageType;
    this.message = message;
    this.object = object;
    this.duration = void 0;
    this.start = Date.now();
  }
};

// src/services/loggerService/messages/InfoMessage.ts
var InfoMessage = class extends AbstractLogMessage {
  constructor(messageType, message, object) {
    super(1 /* Info */, messageType, message, object);
  }
};

// src/services/loggerService/messages/WarningMessage.ts
var WarningMessage = class extends AbstractLogMessage {
  constructor(messageType, message, object) {
    super(2 /* Warning */, messageType, message, object);
  }
};

// src/services/loggerService/messages/ErrorMessage.ts
var ErrorMessage = class extends AbstractLogMessage {
  constructor(messageType, message, object) {
    super(4 /* Error */, messageType, message, object);
  }
};

// src/services/loggerService/groups/LogGroup.ts
var LogGroup = class {
  constructor() {
    this.logs = [];
    this.start = Date.now();
  }
  add(log) {
    return __async(this, null, function* () {
      this.logs.push(log);
    });
  }
};

// src/services/loggerService/LoggerService.ts
var LoggerService = class extends AbstractService {
  constructor(api) {
    super(api);
    this._logWriter = new ConsoleLogger(this.api);
  }
  createInfo(messageType, message, object) {
    return new InfoMessage(messageType, message, object);
  }
  info(messageType, message, object) {
    return __async(this, null, function* () {
      this._logWriter.maybeWriteLog(this.createInfo(messageType, message, object));
    });
  }
  createWarning(messageType, message, object) {
    return new WarningMessage(messageType, message, object);
  }
  warning(messageType, message, object) {
    return __async(this, null, function* () {
      this._logWriter.maybeWriteLog(this.createWarning(messageType, message, object));
    });
  }
  createError(messageType, message, object) {
    return new ErrorMessage(messageType, message, object);
  }
  error(messageType, message, object) {
    return __async(this, null, function* () {
      this._logWriter.maybeWriteLog(this.createError(messageType, message, object));
    });
  }
  createGroup() {
    return new LogGroup();
  }
  group(group) {
    return __async(this, null, function* () {
      this._logWriter.maybeWriteLogList(group);
    });
  }
};

// src/services/codeblockService/workers/CodeblockWorker.ts
var import_obsidian5 = require("obsidian");

// src/services/yamlService/YamlService.ts
var YamlService = class extends AbstractService {
  stringify(yaml) {
    let response = "";
    response = this._stringify(yaml, 0).join("\n") + "\n";
    return response;
  }
  _stringify(yaml, indent, isArray = false) {
    const response = [];
    if (isArray) {
      for (let index = 0; index < yaml.length; index++) {
        const value = yaml[index];
        if (value == null) {
          response.push("");
        } else {
          switch (typeof value) {
            case "object":
              response.push(...this._stringify(value, indent + 1));
              break;
            case "number":
            case "boolean":
              response.push(value.toString());
              break;
            case "undefined":
              break;
            default:
              response.push('"' + value.replaceAll("\n", "\\n").replaceAll('"', '\\"') + '"');
              break;
          }
        }
      }
    } else {
      Object.entries(yaml).forEach(([key, value], index) => {
        const yamlKey = "  ".repeat(indent) + key + ": ";
        if (value == null) {
          response.push(yamlKey);
        } else if (Array.isArray(value)) {
          const yamlDataType = this._dataType(value);
          switch (yamlDataType) {
            case 0 /* Basic */:
              response.push(yamlKey + "[" + this._stringify(value, 0, true).join(",") + "]");
              break;
            case 2 /* Object */:
              response.push(yamlKey);
              for (let index2 = 0; index2 < value.length; index2++) {
                const arrayReponse = this._stringify(value[index2], 0, false);
                for (let responseIndex = 0; responseIndex < arrayReponse.length; responseIndex++) {
                  if (responseIndex === 0) {
                    arrayReponse[responseIndex] = "  ".repeat(indent + 1) + "- " + arrayReponse[responseIndex];
                  } else {
                    arrayReponse[responseIndex] = "  ".repeat(indent + 2) + arrayReponse[responseIndex];
                  }
                }
                response.push(...arrayReponse);
              }
              break;
          }
        } else {
          switch (typeof value) {
            case "object":
              response.push(yamlKey);
              response.push(...this._stringify(value, indent + 1));
              break;
            case "number":
            case "boolean":
              response.push(yamlKey + value);
              break;
            default:
              response.push(yamlKey + '"' + value.replaceAll("\n", "\\n").replaceAll('"', '\\"') + '"');
              break;
          }
        }
      });
    }
    return response;
  }
  _dataType(values) {
    for (let index = 0; index < values.length; index++) {
      if (typeof values[index] === "object") {
        if (Array.isArray(values[index]))
          return 1 /* Array */;
        return 2 /* Object */;
      }
    }
    return 0 /* Basic */;
  }
};

// src/services/fileManipulatorService/FileManipulator.ts
var FileManipulator = class {
  constructor(_api, _file, fileContent) {
    this._api = _api;
    this._file = _file;
    if (fileContent !== void 0)
      this._fileContent = fileContent;
  }
  get content() {
    return this._fileContent;
  }
  get contentArray() {
    return this._fileContent.split("\n");
  }
  maybeWrite(content) {
    return __async(this, null, function* () {
      if (content !== this._fileContent)
        yield this._api.app.vault.modify(this._file, content);
      return true;
    });
  }
  read() {
    return __async(this, null, function* () {
      const cache = yield this._api.app.metadataCache.getFileCache(this._file);
      if (cache === null)
        return false;
      this.cachedFile = cache;
      if (this._fileContent === void 0)
        this._fileContent = yield this._api.app.vault.read(this._file);
      return true;
    });
  }
};

// src/services/fileManipulatorService/FileManipulatorService.ts
var FileManipulatorService = class extends AbstractService {
  read(file) {
    return __async(this, null, function* () {
      const response = new FileManipulator(this.api, file);
      return response.read().then((loaded) => {
        if (!loaded)
          return void 0;
        return response;
      });
    });
  }
  maybeWrite(file, content) {
    return __async(this, null, function* () {
      return this.read(file).then((fileManipulator) => {
        if (fileManipulator !== void 0)
          fileManipulator.maybeWrite(content).then((response) => {
            return;
          });
      });
    });
  }
  patternPosition(fileManipulator, pattern) {
    const arrayContent = fileManipulator.contentArray;
    let startLine = void 0;
    let endLine = void 0;
    let isPartialStart = void 0;
    let isPartialEnd = void 0;
    let analysedLine = 0;
    for (let index = 0; index < arrayContent.length; index++) {
      const line = arrayContent[index];
      let isMatching = false;
      if (analysedLine === 0 && pattern.length === 1) {
        isMatching = line === pattern[0];
        if (isMatching) {
          startLine = index;
          isPartialStart = false;
        }
      } else if (analysedLine === 0) {
        isMatching = line.endsWith(pattern[0]);
        if (isMatching) {
          startLine = index;
          isPartialStart = line !== pattern[0];
        }
      } else if (analysedLine === pattern.length - 1) {
        isMatching = line.startsWith(pattern[pattern.length - 1]);
        if (isMatching) {
          endLine = index;
          isPartialEnd = line !== pattern[pattern.length - 1];
        }
      } else {
        isMatching = line === pattern[analysedLine];
      }
      if (isMatching) {
        analysedLine++;
        if (startLine !== void 0 && endLine !== void 0 && isPartialStart !== void 0 && isPartialEnd !== void 0) {
          return {
            partialEnd: isPartialEnd,
            partialStart: isPartialStart,
            start: startLine,
            end: endLine + 1,
            content: pattern
          };
        }
      } else if (analysedLine !== 0) {
        analysedLine = 0;
        startLine = void 0;
        endLine = void 0;
        isPartialStart = void 0;
        isPartialEnd = void 0;
      }
    }
    return void 0;
  }
  replacePattern(fileManipulator, patternPosition, content) {
    return __async(this, null, function* () {
      const arrayContent = fileManipulator.contentArray;
      if (patternPosition.partialStart) {
        arrayContent[patternPosition.start].replace(patternPosition.content[0], content[0]);
        patternPosition.start++;
      }
      if (patternPosition.partialEnd) {
        arrayContent[patternPosition.end].replace(arrayContent[patternPosition.end], content[content.length - 1]);
        content.splice(content.length - 1, 1);
        patternPosition.end--;
      }
      arrayContent.splice(patternPosition.start, patternPosition.end - patternPosition.start, ...content);
      fileManipulator.maybeWrite(arrayContent.join("\n"));
    });
  }
};

// src/services/codeblockService/workers/CodeblockWorker.ts
var CodeblockWorker = class {
  constructor(_api) {
    this._api = _api;
  }
  readContent(isFrontmatter, file, codeblockName = "RpgManagerData") {
    return __async(this, null, function* () {
      var _a, _b, _c, _d, _e, _f;
      let editor = void 0;
      let cache = null;
      let codeblock;
      let codeblockContent = void 0;
      let codeblockStart = void 0;
      let codeblockEnd = void 0;
      let fileContent = void 0;
      if (file === void 0) {
        const activeView = yield this._api.app.workspace.getActiveViewOfType(import_obsidian5.MarkdownView);
        if (activeView == void 0)
          return void 0;
        editor = yield activeView.editor;
        file = yield activeView.file;
        fileContent = yield this._api.app.vault.read(file);
        cache = yield this._api.app.metadataCache.getFileCache(file);
        if (cache == void 0)
          return void 0;
        let codeblockData = void 0;
        for (let index = 0; index < ((_b = (_a = cache == null ? void 0 : cache.sections) == null ? void 0 : _a.length) != null ? _b : 0); index++) {
          codeblockData = yield (cache == null ? void 0 : cache.sections) !== void 0 ? cache.sections[index] : void 0;
          if (codeblockData !== void 0 && (!isFrontmatter && editor.getLine(codeblockData.position.start.line) === "```" + codeblockName || isFrontmatter && codeblockData.type === "yaml")) {
            codeblockStart = { line: codeblockData.position.start.line + 1, ch: 0 };
            codeblockEnd = { line: codeblockData.position.end.line, ch: 0 };
            codeblockContent = yield editor.getRange(codeblockStart, codeblockEnd);
            codeblock = (_c = yield (0, import_obsidian5.parseYaml)(codeblockContent)) != null ? _c : {};
            break;
          }
        }
      } else {
        fileContent = yield this._api.app.vault.read(file);
        const fileContentLines = fileContent.split("\n");
        cache = yield this._api.app.metadataCache.getFileCache(file);
        if (cache == void 0)
          return void 0;
        let codeblockData = void 0;
        for (let index = 0; index < ((_e = (_d = cache == null ? void 0 : cache.sections) == null ? void 0 : _d.length) != null ? _e : 0); index++) {
          codeblockData = yield (cache == null ? void 0 : cache.sections) !== void 0 ? cache.sections[index] : void 0;
          if (codeblockData !== void 0 && (!isFrontmatter && fileContentLines[codeblockData.position.start.line] === "```" + codeblockName || isFrontmatter && codeblockData.type === "yaml")) {
            codeblockStart = { line: codeblockData.position.start.line + 1, ch: 0 };
            codeblockEnd = { line: codeblockData.position.end.line, ch: 0 };
            codeblockContent = "";
            for (let lineIndex = codeblockData.position.start.line + 1; lineIndex < codeblockData.position.end.line; lineIndex++) {
              codeblockContent += fileContentLines[lineIndex] + "\n";
            }
            if (codeblockContent === void 0)
              return void 0;
            codeblock = (_f = yield (0, import_obsidian5.parseYaml)(codeblockContent)) != null ? _f : {};
            break;
          }
        }
      }
      if (cache == void 0 || file === void 0 || fileContent === void 0 || codeblockContent === void 0 || codeblockStart === void 0 || codeblockEnd === void 0)
        return void 0;
      const response = {
        editor,
        file,
        originalFileContent: fileContent,
        cache,
        codeblock,
        codeblockStart,
        codeblockEnd,
        codeblockContent,
        originalCodeblockContent: codeblockContent,
        isFrontmatter
      };
      return response;
    });
  }
  tryReadOpenContent(file, codeblockName = "RpgManagerData") {
    return __async(this, null, function* () {
      var _a, _b, _c;
      let editor = void 0;
      let cache = null;
      let codeblock;
      let codeblockContent = void 0;
      let codeblockStart = void 0;
      let codeblockEnd = void 0;
      const activeViews = [];
      yield this._api.app.workspace.iterateRootLeaves((leaf) => {
        try {
          if (leaf.view.file === file)
            activeViews.push(leaf.view);
        } catch (e) {
        }
      });
      if (activeViews.length === 0)
        return void 0;
      const activeView = activeViews[0];
      const newfile = yield activeView.file;
      if (newfile.path !== file.path)
        return void 0;
      editor = yield activeView.editor;
      const fileContent = yield this._api.app.vault.read(file);
      cache = yield this._api.app.metadataCache.getFileCache(file);
      if (cache == void 0)
        return void 0;
      let codeblockData = void 0;
      for (let index = 0; index < ((_b = (_a = cache == null ? void 0 : cache.sections) == null ? void 0 : _a.length) != null ? _b : 0); index++) {
        codeblockData = yield (cache == null ? void 0 : cache.sections) !== void 0 ? cache.sections[index] : void 0;
        if (codeblockData !== void 0 && editor.getLine(codeblockData.position.start.line) === "```" + codeblockName) {
          codeblockStart = { line: codeblockData.position.start.line + 1, ch: 0 };
          codeblockEnd = { line: codeblockData.position.end.line, ch: 0 };
          codeblockContent = yield editor.getRange(codeblockStart, codeblockEnd);
          codeblock = (_c = yield (0, import_obsidian5.parseYaml)(codeblockContent)) != null ? _c : {};
          break;
        }
      }
      if (cache == void 0 || file === void 0 || fileContent === void 0 || codeblockContent === void 0 || codeblockStart === void 0 || codeblockEnd === void 0)
        return void 0;
      const response = {
        editor,
        file,
        originalFileContent: fileContent,
        cache,
        codeblock,
        codeblockStart,
        codeblockEnd,
        codeblockContent,
        originalCodeblockContent: codeblockContent,
        isFrontmatter: false
      };
      return response;
    });
  }
  updateContent(domain) {
    return __async(this, null, function* () {
      if (domain.editor !== void 0) {
        yield domain.editor.replaceRange(this._api.service(YamlService).stringify(domain.codeblock), domain.codeblockStart, domain.codeblockEnd);
        yield this._api.app.vault.modify(domain.file, domain.editor.getValue()).then(() => {
          var _a;
          (_a = this._api.database.readByPath(domain.file.path)) == null ? void 0 : _a.touch();
          this._api.app.workspace.trigger("rpgmanager:refresh-views");
        });
        return true;
      } else {
        const newContent = yield domain.originalFileContent.replace(domain.originalCodeblockContent, domain.codeblockContent);
        yield this._api.service(FileManipulatorService).maybeWrite(domain.file, newContent);
        return true;
      }
    });
  }
};

// src/services/codeblockService/workers/CodeblockImageWorker.ts
var CodeblockImageWorker = class {
  constructor(_api) {
    this._api = _api;
  }
  addOrUpdate(domain, data) {
    return __async(this, null, function* () {
      if (domain.codeblock.data === void 0)
        domain.codeblock.data = {};
      if (domain.codeblock.data.images == void 0)
        domain.codeblock.data.images = [];
      let found;
      for (let index = 0; index < domain.codeblock.data.images.length; index++) {
        if (data.path === domain.codeblock.data.images[index].path) {
          found = index;
          break;
        }
      }
      if (found !== void 0) {
        domain.codeblock.data.images.splice(found, 1, data);
      } else {
        domain.codeblock.data.images.push(data);
      }
      domain.codeblockContent = this._api.service(YamlService).stringify(domain.codeblock);
    });
  }
  remove(domain, path2) {
    return __async(this, null, function* () {
      if (domain.codeblock.data.images === void 0)
        return;
      let found;
      for (let index = 0; index < domain.codeblock.data.images.length; index++) {
        if (path2 === domain.codeblock.data.images[index].path) {
          found = index;
          break;
        }
      }
      if (found !== void 0) {
        domain.codeblock.data.images.splice(found, 1);
      }
      domain.codeblockContent = this._api.service(YamlService).stringify(domain.codeblock);
    });
  }
};

// src/services/relationshipsService/enums/RelationshipType.ts
var RelationshipType = /* @__PURE__ */ ((RelationshipType2) => {
  RelationshipType2[RelationshipType2["Reversed"] = 1] = "Reversed";
  RelationshipType2[RelationshipType2["Bidirectional"] = 2] = "Bidirectional";
  RelationshipType2[RelationshipType2["Unidirectional"] = 4] = "Unidirectional";
  RelationshipType2[RelationshipType2["Parent"] = 8] = "Parent";
  RelationshipType2[RelationshipType2["Child"] = 16] = "Child";
  RelationshipType2[RelationshipType2["Hierarchy"] = 32] = "Hierarchy";
  RelationshipType2[RelationshipType2["Undefined"] = 64] = "Undefined";
  return RelationshipType2;
})(RelationshipType || {});

// src/services/relationshipsService/Relationship.ts
var Relationship = class {
  constructor(type, path2, description = void 0, component = void 0, isInContent = false) {
    this.type = type;
    this.path = path2;
    this.description = description;
    this.component = component;
    this.isInContent = isInContent;
  }
};

// src/services/relationshipsService/RelationshipService.ts
var RelationshipService = class extends AbstractService {
  addRelationshipsFromContent(fileContent, metadata, stage) {
    return __async(this, null, function* () {
      var _a, _b;
      if (metadata.relationships == void 0)
        metadata.relationships = [];
      let content = fileContent;
      let indexOfRelationship = content.indexOf("[[");
      while (indexOfRelationship !== -1) {
        content = content.substring(content.indexOf("[[") + 2);
        const endLinkIndex = content.indexOf("]]");
        if (endLinkIndex === -1)
          break;
        const nameAndAlias = content.substring(0, endLinkIndex);
        const aliasIndex = nameAndAlias.indexOf("|");
        let basename = void 0;
        let skipHiddenLink = false;
        if (aliasIndex === -1) {
          basename = nameAndAlias;
        } else {
          if (nameAndAlias.substring(aliasIndex) === "|") {
            skipHiddenLink = true;
          } else {
            basename = nameAndAlias.substring(0, aliasIndex);
          }
        }
        if (!skipHiddenLink && basename !== void 0) {
          let path2 = void 0;
          const allFiles = this.api.app.vault.getMarkdownFiles();
          for (let filesIndex = 0; filesIndex < allFiles.length; filesIndex++) {
            if (allFiles[filesIndex].basename === basename) {
              path2 = allFiles[filesIndex].path;
              break;
            }
          }
          if (path2 !== void 0) {
            let relationshipAlreadyExists = false;
            for (let relationshipsIndex = 0; relationshipsIndex < metadata.relationships.length; relationshipsIndex++) {
              if (metadata.relationships[relationshipsIndex].path === path2) {
                relationshipAlreadyExists = true;
                break;
              }
            }
            if (!relationshipAlreadyExists) {
              let relationship = void 0;
              if (stage === 2 /* Run */ || stage === 0 /* Plot */) {
                relationship = 4 /* Unidirectional */;
              } else {
                relationship = 2 /* Bidirectional */;
              }
              (_a = metadata.relationships) == null ? void 0 : _a.push({
                type: this.getReadableRelationshipType(relationship),
                path: path2,
                isInContent: true
              });
            }
          } else {
            (_b = metadata.relationships) == null ? void 0 : _b.push({
              type: void 0,
              path: basename,
              isInContent: true
            });
          }
        }
        indexOfRelationship = content.indexOf("[[");
      }
    });
  }
  createRelationship(type, path2, description = void 0, component = void 0, isInContent = false, existingRelationships = void 0) {
    const response = new Relationship(type, path2, description, component, isInContent);
    if (existingRelationships !== void 0)
      existingRelationships.add(response);
    return response;
  }
  createRelationshipFromMetadata(relationship) {
    var _a;
    const response = new Relationship(relationship.type !== void 0 ? this.getTypeFromString(relationship.type) : 64 /* Undefined */, relationship.path, relationship.description, void 0, (_a = relationship.isInContent) != null ? _a : false);
    return response;
  }
  createRelationshipFromReverse(component, relationship) {
    var _a;
    if (component.stage === 0 /* Plot */ || component.stage === 2 /* Run */)
      return void 0;
    if (relationship.component !== null && component.file.path === ((_a = relationship.component) == null ? void 0 : _a.file.path))
      return void 0;
    let reverseRelationshipType = void 0;
    switch (relationship.type) {
      case 2 /* Bidirectional */:
        reverseRelationshipType = 1 /* Reversed */;
        break;
      case 16 /* Child */:
        reverseRelationshipType = 8 /* Parent */;
        break;
    }
    if (reverseRelationshipType === void 0)
      return void 0;
    const response = new Relationship(reverseRelationshipType, component.file.path, void 0, component, false);
    return response;
  }
  getComponentTypeFromListName(listName) {
    let response = void 0;
    switch (listName.toLowerCase()) {
      case "adventures":
        response = 2 /* Adventure */;
        break;
      case "acts":
        response = 4 /* Act */;
        break;
      case "scenes":
        response = 8 /* Scene */;
        break;
      case "sessions":
        response = 16 /* Session */;
        break;
      case "pcs":
        response = 32 /* Character */;
        break;
      case "npcs":
        response = 64 /* NonPlayerCharacter */;
        break;
      case "clues":
        response = 512 /* Clue */;
        break;
      case "events":
        response = 256 /* Event */;
        break;
      case "factions":
        response = 1024 /* Faction */;
        break;
      case "locations":
        response = 128 /* Location */;
        break;
      case "musics":
        response = 2048 /* Music */;
        break;
      case "subplots":
        response = 4096 /* Subplot */;
        break;
    }
    if (response === void 0) {
      this.api.service(LoggerService).createError(1 /* System */, "The requested list (" + listName + ") does not exist");
      throw new Error("The requested list (" + listName + ") does not exist");
    }
    return response;
  }
  getReadableRelationshipType(type) {
    return RelationshipType[type].toString().toLowerCase();
  }
  getTypeFromString(readableRelationshipType) {
    readableRelationshipType = readableRelationshipType[0].toUpperCase() + readableRelationshipType.substring(1).toLowerCase();
    return RelationshipType[readableRelationshipType];
  }
  getTableFields(relationshipComponentType) {
    let fieldList = void 0;
    switch (relationshipComponentType) {
      case 2 /* Adventure */:
        fieldList = this.api.settings.advanced.Agnostic.AdventureList;
        break;
      case 4 /* Act */:
        fieldList = this.api.settings.advanced.Agnostic.ActList;
        break;
      case 8 /* Scene */:
        fieldList = this.api.settings.advanced.Agnostic.SceneList;
        break;
      case 16 /* Session */:
        fieldList = this.api.settings.advanced.Agnostic.SessionList;
        break;
      case 4096 /* Subplot */:
        fieldList = this.api.settings.advanced.Agnostic.SubplotList;
        break;
      case 32 /* Character */:
        fieldList = this.api.settings.advanced.Agnostic.CharacterList;
        break;
      case 512 /* Clue */:
        fieldList = this.api.settings.advanced.Agnostic.ClueList;
        break;
      case 256 /* Event */:
        fieldList = this.api.settings.advanced.Agnostic.EventList;
        break;
      case 1024 /* Faction */:
        fieldList = this.api.settings.advanced.Agnostic.FactionList;
        break;
      case 128 /* Location */:
        fieldList = this.api.settings.advanced.Agnostic.LocationList;
        break;
      case 2048 /* Music */:
        fieldList = this.api.settings.advanced.Agnostic.MusicList;
        break;
      case 64 /* NonPlayerCharacter */:
        fieldList = this.api.settings.advanced.Agnostic.NonPlayerCharacterList;
        break;
    }
    const response = [];
    fieldList == null ? void 0 : fieldList.fields.forEach((element) => {
      if (element.checked)
        response.push(element.field);
    });
    return response;
  }
  getTableFieldInline(relationshipComponentType, field) {
    switch (field) {
      case 2 /* Name */:
      case 4 /* Synopsis */:
      case 7 /* Url */:
        return false;
        break;
      default:
        return true;
        break;
    }
  }
};

// src/services/codeblockService/workers/CodeblockRelationshipWorker.ts
var CodeblockRelationshipWorker = class {
  constructor(_api) {
    this._api = _api;
  }
  addOrUpdate(domain, data) {
    return __async(this, null, function* () {
      if (domain.codeblock.relationships === void 0)
        domain.codeblock.relationships = [];
      let found;
      for (let relationshipsIndex = 0; relationshipsIndex < domain.codeblock.relationships.length; relationshipsIndex++) {
        if (data.path === domain.codeblock.relationships[relationshipsIndex].path) {
          found = relationshipsIndex;
          break;
        }
      }
      if (found !== void 0)
        domain.codeblock.relationships.splice(found, 1);
      const metadataRelationship = {
        type: this._api.service(RelationshipService).getReadableRelationshipType(data.type),
        path: data.path,
        description: data.description
      };
      domain.codeblock.relationships.push(metadataRelationship);
      domain.codeblockContent = this._api.service(YamlService).stringify(domain.codeblock);
    });
  }
  remove(domain, path2) {
    return __async(this, null, function* () {
      if (domain.codeblock.relationships === void 0)
        return;
      let found;
      for (let relationshipsIndex = 0; relationshipsIndex < domain.codeblock.relationships.length; relationshipsIndex++) {
        if (path2 === domain.codeblock.relationships[relationshipsIndex].path) {
          found = relationshipsIndex;
          break;
        }
      }
      if (found !== void 0) {
        domain.codeblock.relationships.splice(found, 1);
      }
      domain.codeblockContent = this._api.service(YamlService).stringify(domain.codeblock);
    });
  }
};

// src/services/codeblockService/workers/CodeblockKeyWorker.ts
var CodeblockKeyWorker = class {
  constructor(_api) {
    this._api = _api;
  }
  addOrUpdate(domain, data) {
    return __async(this, null, function* () {
      const parts = data.key.split(".");
      let key = domain.codeblock;
      for (let index = 0; index < parts.length; index++) {
        if (key[parts[index]] === void 0)
          key[parts[index]] = {};
        if (index === parts.length - 1)
          key[parts[index]] = data.value;
        else
          key = key[parts[index]];
      }
      domain.codeblockContent = this._api.service(YamlService).stringify(domain.codeblock);
    });
  }
  remove(domain, path2) {
    return __async(this, null, function* () {
      const parts = path2.split(".");
      let key = domain.codeblock;
      for (let index = 0; index < parts.length; index++) {
        if (key[parts[index]] === void 0)
          key[parts[index]] = {};
        if (index === parts.length - 1)
          delete key[parts[index]];
        else
          key = key[parts[index]];
      }
      domain.codeblockContent = this._api.service(YamlService).stringify(domain.codeblock);
    });
  }
};

// src/services/galleryService/data/Image.ts
var Image2 = class {
  constructor(path2, src) {
    this._path = path2;
    this._src = src;
    this._caption = "";
  }
  get path() {
    return this._path;
  }
  get caption() {
    return this._caption;
  }
  set caption(caption) {
    this._caption = caption;
  }
  get src() {
    return this._src;
  }
};

// src/services/imageService/ImageService.ts
var ImageService = class extends AbstractService {
  createImage(path2, caption) {
    const imageLocation = this._getImageLocation(path2);
    if (imageLocation === void 0)
      return void 0;
    const response = new Image2(path2, imageLocation);
    if (caption !== void 0)
      response.caption = caption;
    return response;
  }
  _getImageLocation(path2) {
    if (path2.trim().toLowerCase().startsWith("http"))
      return path2;
    if (this.api.app.vault.getAbstractFileByPath(path2) === void 0)
      return void 0;
    return this.api.root + path2;
  }
};

// src/services/codeblockService/workers/CodeblockRunningWorker.ts
var CodeblockRunningWorker = class {
  constructor(_api) {
    this._api = _api;
  }
  addOrUpdate(domain, data) {
    return __async(this, null, function* () {
      if (domain.codeblock.data.durations === void 0)
        domain.codeblock.data.durations = [];
      const durations = domain.codeblock.data.durations;
      for (let index = 0; index < durations.length; index++) {
        if (durations[index].indexOf("-") === -1) {
          return;
        }
      }
      durations.push(Math.floor(Date.now() / 1e3).toString());
      domain.codeblockContent = this._api.service(YamlService).stringify(domain.codeblock);
    });
  }
  remove(domain, path2) {
    return __async(this, null, function* () {
      const durations = domain.codeblock.data.durations;
      let totalDuration = 0;
      for (let index = 0; index < durations.length; index++) {
        if (durations[index].indexOf("-") === -1) {
          const end = Math.floor(Date.now() / 1e3);
          const start = +durations[index];
          durations[index] = durations[index] + "-" + end.toString();
          totalDuration += end - start;
        } else {
          const [start, end] = durations[index].split("-");
          totalDuration += +end - +start;
        }
      }
      domain.codeblock.data.duration = totalDuration;
      domain.codeblockContent = this._api.service(YamlService).stringify(domain.codeblock);
    });
  }
};

// src/services/codeblockService/CodeblockService.ts
var CodeblockService = class extends AbstractService {
  constructor(api) {
    super(api);
    this._worker = new CodeblockWorker(this.api);
  }
  addOrUpdate(key, value, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file);
      if (domain === void 0)
        return void 0;
      const dataWorker = yield new CodeblockKeyWorker(this.api);
      yield dataWorker.addOrUpdate(domain, { key, value });
      yield this._worker.updateContent(domain);
    });
  }
  addOrUpdateInIndex(key, value, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file, "RpgManagerID");
      if (domain === void 0)
        return void 0;
      const dataWorker = yield new CodeblockKeyWorker(this.api);
      yield dataWorker.addOrUpdate(domain, { key, value });
      yield this._worker.updateContent(domain);
    });
  }
  addOrUpdateMultiple(keyValues, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file);
      if (domain === void 0)
        return void 0;
      const dataWorker = yield new CodeblockKeyWorker(this.api);
      yield keyValues.forEach((value, key) => {
        dataWorker.addOrUpdate(domain, { key, value });
      });
      yield this._worker.updateContent(domain);
    });
  }
  addOrUpdateMultipleInIndex(keyValues, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file, "RpgManagerID");
      if (domain === void 0)
        return void 0;
      const dataWorker = yield new CodeblockKeyWorker(this.api);
      yield keyValues.forEach((value, key) => {
        dataWorker.addOrUpdate(domain, { key, value });
      });
      yield this._worker.updateContent(domain);
    });
  }
  addOrUpdateFrontmatter(key, value, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(true, file);
      if (domain === void 0)
        return void 0;
      const dataWorker = yield new CodeblockKeyWorker(this.api);
      yield dataWorker.addOrUpdate(domain, { key, value });
      yield this._worker.updateContent(domain);
    });
  }
  addOrUpdateImage(path2, caption, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file);
      if (domain === void 0)
        return void 0;
      const dataWorker = yield new CodeblockImageWorker(this.api);
      yield dataWorker.addOrUpdate(domain, { path: path2, caption });
      return this._worker.updateContent(domain).then(() => {
        return this.api.service(ImageService).createImage(path2, caption);
      });
    });
  }
  addOrUpdateRelationship(relationship, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file);
      if (domain === void 0)
        return;
      const dataWorker = yield new CodeblockRelationshipWorker(this.api);
      yield dataWorker.addOrUpdate(domain, relationship);
      this._worker.updateContent(domain);
    });
  }
  addOrUpdateRelationshipInCodeblock(relationship, domain) {
    return __async(this, null, function* () {
      const dataWorker = yield new CodeblockRelationshipWorker(this.api);
      dataWorker.addOrUpdate(domain, relationship);
    });
  }
  replaceID(file, id) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file, "RpgManagerID");
      if (domain === void 0)
        return;
      const checksum = yield Md5.hashStr(id);
      const dataWorker = yield new CodeblockKeyWorker(this.api);
      yield dataWorker.addOrUpdate(domain, { key: "id", value: id });
      yield dataWorker.addOrUpdate(domain, { key: "checksum", value: checksum });
      const oldModel = yield this.api.database.readByPath(file.path);
      if (oldModel !== void 0)
        yield this.api.database.delete(oldModel);
      yield this._worker.updateContent(domain);
    });
  }
  remove(key, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file);
      if (domain === void 0)
        return void 0;
      const dataWorker = yield new CodeblockKeyWorker(this.api);
      yield dataWorker.remove(domain, key);
      this._worker.updateContent(domain);
    });
  }
  removeFrontmatter(key, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(true, file);
      if (domain === void 0)
        return void 0;
      const dataWorker = yield new CodeblockKeyWorker(this.api);
      yield dataWorker.remove(domain, key);
      this._worker.updateContent(domain);
    });
  }
  read(file, codeblockName = "RpgManagerData") {
    return __async(this, null, function* () {
      return this._worker.readContent(false, file, codeblockName);
    });
  }
  removeImage(path2, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file);
      if (domain === void 0)
        return;
      const dataWorker = new CodeblockImageWorker(this.api);
      yield dataWorker.remove(domain, path2);
      this._worker.updateContent(domain);
    });
  }
  removeRelationship(path2, file) {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false, file);
      if (domain === void 0)
        return;
      const dataWorker = yield new CodeblockRelationshipWorker(this.api);
      yield dataWorker.remove(domain, path2);
      this._worker.updateContent(domain);
    });
  }
  selectRpgManagerData() {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false);
      if (domain === void 0 || domain.editor === void 0)
        return;
      domain.editor.setSelection(domain.codeblockStart, domain.codeblockEnd);
      domain.editor.focus();
    });
  }
  startRunningTime() {
    return __async(this, null, function* () {
      const domain = yield this._worker.readContent(false);
      if (domain === void 0 || domain.editor === void 0)
        return;
      const dataWorker = yield new CodeblockRunningWorker(this.api);
      dataWorker.addOrUpdate(domain, {});
      this._worker.updateContent(domain);
    });
  }
  stopRunningTime(file) {
    return __async(this, null, function* () {
      let domain = void 0;
      if (file !== void 0)
        domain = yield this._worker.tryReadOpenContent(file);
      if (domain === void 0)
        domain = yield this._worker.readContent(false, file);
      if (domain === void 0)
        return;
      const dataWorker = yield new CodeblockRunningWorker(this.api);
      dataWorker.remove(domain, "");
      this._worker.updateContent(domain);
    });
  }
  updateDomain(domain) {
    return __async(this, null, function* () {
      domain.codeblockContent = yield this.api.service(YamlService).stringify(domain.codeblock);
      yield this._worker.updateContent(domain);
    });
  }
};

// src/managers/databaseManager/DatabaseInitialiser.ts
var DatabaseInitialiser = class {
  static initialise(api) {
    return __async(this, null, function* () {
      this._api = api;
      this._misconfiguredTags = yield /* @__PURE__ */ new Map();
      const group = this._api.service(LoggerService).createGroup();
      const response = yield this._api.createDatabase();
      group.add(this._api.service(LoggerService).createInfo(4 /* DatabaseInitialisation */, "Database Initialised"));
      const components = [];
      const markdownFiles = app.vault.getMarkdownFiles();
      let componentCounter = 0;
      for (let index = 0; index < markdownFiles.length; index++) {
        try {
          yield this.createComponent(api, markdownFiles[index]).then((component) => {
            if (component === void 0)
              return void 0;
            if (component.stage == 0 /* Plot */ || component.stage === 2 /* Run */) {
              let error = void 0;
              try {
                const duplicate = response.readById(component.index.id);
                error = new ComponentDuplicatedError(this._api, component.index, [duplicate], component);
              } catch (e) {
              }
              if (error !== void 0)
                throw error;
            }
            response.create(component);
            components.push(component);
            componentCounter++;
          });
        } catch (e) {
          this._misconfiguredTags.set(markdownFiles[index], e);
        }
      }
      group.add(this._api.service(LoggerService).createInfo(4 /* DatabaseInitialisation */, componentCounter + " Components created"));
      yield Promise.all(components);
      const metadata = [];
      yield components.forEach((component) => {
        try {
          metadata.push(component.readMetadata());
        } catch (e) {
          this._misconfiguredTags.set(component.file, e);
        }
      });
      Promise.all(metadata).then(() => {
        group.add(this._api.service(LoggerService).createInfo(4 /* DatabaseInitialisation */, "Data read for " + metadata.length + " Components"));
        this._initialiseRelationships(response).then(() => {
          group.add(this._api.service(LoggerService).createInfo(4 /* DatabaseInitialisation */, "Relationships created"));
          this._validateComponents(response).then(() => {
            group.add(this._api.service(LoggerService).createInfo(4 /* DatabaseInitialisation */, "Components Validated"));
            response.ready();
            if (this._misconfiguredTags.size > 0) {
              new DatabaseErrorModal(this._api, this._misconfiguredTags).open();
            }
            this._api.service(LoggerService).group(group);
          });
        });
      });
      return response;
    });
  }
  static _validateComponents(database) {
    return __async(this, null, function* () {
      database.recordset.forEach((component) => {
        try {
          component.validateHierarchy();
        } catch (e) {
          database.delete(component);
          this._misconfiguredTags.set(component.file, e);
        }
      });
    });
  }
  static readID(file) {
    return __async(this, null, function* () {
      var _a;
      const codeblockDomain = yield this._api.service(CodeblockService).read(file, "RpgManagerID");
      if (codeblockDomain === void 0 || ((_a = codeblockDomain == null ? void 0 : codeblockDomain.codeblock) == null ? void 0 : _a.id) === void 0)
        return void 0;
      const response = this._api.service(IndexService).createFromIndex(codeblockDomain.codeblock);
      return response;
    });
  }
  static createComponent(api, file) {
    return __async(this, null, function* () {
      const id = yield this.readID(file);
      if (id === void 0)
        return void 0;
      const response = yield api.models.get(id, id.campaignSettings, file);
      return response;
    });
  }
  static _initialiseRelationships(database) {
    return __async(this, null, function* () {
      for (let index = 0; index < database.recordset.length; index++) {
        const model = database.recordset[index];
        const relationships = model.getRelationships(database).relationships;
        for (let relationshipIndex = 0; relationshipIndex < relationships.length; relationshipIndex++) {
          const relationship = relationships[relationshipIndex];
          if (relationship.component !== void 0) {
            const newRelationship = this._api.service(RelationshipService).createRelationshipFromReverse(model, relationship);
            if (newRelationship !== void 0)
              relationship.component.getRelationships(database).add(newRelationship, model);
          }
        }
      }
      for (let index = 0; index < database.recordset.length; index++) {
        database.recordset[index].touch();
      }
    });
  }
};
DatabaseInitialiser._misconfiguredTags = /* @__PURE__ */ new Map();

// src/settings/SettingsUpdater.ts
var SettingsUpdater = class {
  constructor(_api) {
    this._api = _api;
  }
  updateTags(updatedTags) {
    return __async(this, null, function* () {
      this._api.service(LoggerService).info(32 /* TagUpdates */, "Collecting files");
      const files = yield this._api.app.vault.getMarkdownFiles();
      for (let index = 0; index < files.length; index++) {
        const content = yield this._api.app.vault.read(files[index]);
        this._api.service(LoggerService).info(32 /* TagUpdates */, "Reading file contents", files[index]);
        let newFileContent = content;
        yield updatedTags.forEach((newTag, oldTag) => {
          newFileContent = newFileContent.replaceAll(oldTag, newTag);
        });
        this._api.service(LoggerService).info(32 /* TagUpdates */, "Tags Updated", files[index]);
        if (newFileContent !== content) {
          yield this._api.app.vault.modify(files[index], newFileContent);
          this._api.service(LoggerService).info(32 /* TagUpdates */, "File updated", files[index]);
        }
      }
      this._api.service(LoggerService).info(32 /* TagUpdates */, "Re-initialising databaseManager");
      return yield DatabaseInitialiser.initialise(this._api).then((database) => {
        this._api.database = database;
        this._api.service(LoggerService).info(32 /* TagUpdates */, "Database re-initialised");
        this._api.app.workspace.trigger("rpgmanager:refresh-views");
        return;
      });
    });
  }
};

// src/settings/factories/SettingsFactory.ts
var import_obsidian6 = require("obsidian");
var SettingsFactory = class {
  constructor(_app, _plugin, _map, _containerEl) {
    this._app = _app;
    this._plugin = _plugin;
    this._map = _map;
    this._containerEl = _containerEl;
  }
  _generateFragment(text) {
    const lines = text.split("\n");
    return createFragment((fragment) => {
      lines.forEach((content) => {
        fragment.appendText(content);
        fragment.createEl("br");
      });
      fragment.appendText(" ");
    });
  }
  createHeader(text, level = 2, additionalText = void 0) {
    const elementType = "h" + level.toString();
    this._containerEl.createEl(elementType, { text });
    if (additionalText !== void 0) {
      this._containerEl.createEl("span", { text: this._generateFragment(additionalText) });
    }
  }
  createWarning(text) {
    this._containerEl.createEl("p", { text }).style.color = "var(--text-error)";
  }
  createTextSetting(type, description = "") {
    const settings = this._map.get(type);
    if (settings === void 0)
      throw new Error("Setting type not found");
    return new import_obsidian6.Setting(this._containerEl).setName(settings.title).setDesc(this._generateFragment(description)).addText((text) => {
      var _a;
      return text.setPlaceholder((_a = settings.placeholder) != null ? _a : "").setValue(settings.value).onChange((value) => {
        settings.value = value;
      });
    });
  }
  createDropdownSetting(type, description, options) {
    const settings = this._map.get(type);
    if (settings === void 0)
      throw new Error("Setting type not found");
    return new import_obsidian6.Setting(this._containerEl).setName(settings.title).setDesc(this._generateFragment(description)).addDropdown((dropdown) => {
      dropdown.addOption("", "");
      options.forEach((value, display) => {
        dropdown.addOption(value, display);
      });
      dropdown.setValue(settings.value);
      dropdown.onChange((value) => __async(this, null, function* () {
        switch (type) {
          case 13 /* templateFolder */:
            yield this._plugin.updateSettings({ templateFolder: value });
            settings.value = value;
            break;
          case 18 /* imagesFolder */:
            yield this._plugin.updateSettings({ imagesFolder: value });
            settings.value = value;
            break;
        }
      }));
    });
  }
  createToggleSetting(type, description) {
    const settings = this._map.get(type);
    if (settings === void 0)
      throw new Error("Setting type not found");
    return new import_obsidian6.Setting(this._containerEl).setName(settings.title).setDesc(this._generateFragment(description)).addToggle((toggle) => toggle.setValue(settings.value).onChange((value) => __async(this, null, function* () {
      switch (type) {
        case 11 /* automaticMove */:
          yield this._plugin.updateSettings({ automaticMove: value });
          settings.value = value;
          break;
        case 16 /* usePlotStructures */:
          yield this._plugin.updateSettings({ usePlotStructures: value });
          settings.value = value;
          break;
        case 17 /* useSceneAnalyser */:
          yield this._plugin.updateSettings({ useSceneAnalyser: value });
          settings.value = value;
          break;
      }
      this._app.workspace.trigger("rpgmanager:force-refresh-views");
    })));
  }
};

// src/settings/RpgManagerSettings.ts
var RpgManagerSettings = class extends import_obsidian7.PluginSettingTab {
  constructor(_api) {
    super(_api.app, app.plugins.getPlugin("rpg-manager"));
    this._api = _api;
    this._advancedSettingsDescription = /* @__PURE__ */ new Map();
    this._plugin = app.plugins.getPlugin("rpg-manager");
    const { containerEl } = this;
    this.containerEl = containerEl;
    this._map = /* @__PURE__ */ new Map();
    this._map.set(12 /* YouTubeApiKey */, { title: "YouTube API Key", value: this._plugin.settings.YouTubeKey, placeholder: "Your YouTube API Key" });
    this._map.set(11 /* automaticMove */, { title: "Automatically organise elements in folders", value: this._plugin.settings.automaticMove, placeholder: "Organise new elements" });
    this._map.set(13 /* templateFolder */, { title: "Template folder", value: this._plugin.settings.templateFolder, placeholder: "Template Folder" });
    this._map.set(18 /* imagesFolder */, { title: "Images folder", value: this._plugin.settings.imagesFolder, placeholder: "Images Folder" });
    this._map.set(16 /* usePlotStructures */, { title: "Abt/Story Circle plot structure", value: this._plugin.settings.usePlotStructures, placeholder: "" });
    this._map.set(17 /* useSceneAnalyser */, { title: "SceneModel Analyser", value: this._plugin.settings.useSceneAnalyser, placeholder: "" });
    this._advancedSettingsDescription.set("ActList", { title: "Act List", description: "Select which fields you would like to see when displaying a list of Acts" });
    this._advancedSettingsDescription.set("AdventureList", { title: "Adventure List", description: "Select which fields you would like to see when displaying a list of Adventures" });
    this._advancedSettingsDescription.set("CharacterList", { title: "Player Character List", description: "Select which fields you would like to see when displaying a list of Player characters" });
    this._advancedSettingsDescription.set("ClueList", { title: "Clue List", description: "Select which fields you would like to see when displaying a list of Clues" });
    this._advancedSettingsDescription.set("EventList", { title: "Event List", description: "Select which fields you would like to see when displaying a list of Events" });
    this._advancedSettingsDescription.set("FactionList", { title: "Faction List", description: "Select which fields you would like to see when displaying a list of Factions" });
    this._advancedSettingsDescription.set("LocationList", { title: "Location List", description: "Select which fields you would like to see when displaying a list of Locations" });
    this._advancedSettingsDescription.set("MusicList", { title: "Music List", description: "Select which fields you would like to see when displaying a list of Musics" });
    this._advancedSettingsDescription.set("NonPlayerCharacterList", { title: "Non Player Character List", description: "Select which fields you would like to see when displaying a list of Non Player Characters" });
    this._advancedSettingsDescription.set("SceneList", { title: "Scene List", description: "Select which fields you would like to see when displaying a list of Scenes" });
    this._advancedSettingsDescription.set("SessionList", { title: "Session List", description: "Select which fields you would like to see when displaying a list of Sessions" });
    this._advancedSettingsDescription.set("SubplotList", { title: "Subplot List", description: "Select which fields you would like to see when displaying a list of Subplots" });
    this._settingsUpdater = new SettingsUpdater(this._api);
    this._settingsFactory = new SettingsFactory(this.app, this._plugin, this._map, this.containerEl);
  }
  display() {
    this.containerEl.empty();
    this._createFolderMap();
    this._settingsFactory.createHeader("CampaignSetting for Role Playing Game Manager");
    this._loadTemplatesSettings();
    this._loadImagesSettings();
    this._loadExternalServicesSettings();
    this._loadAdvancedSettings();
  }
  _loadExternalServicesSettings() {
    this._settingsFactory.createHeader("External Services", 3);
    this._settingsFactory.createWarning(`Configurations are saved in a file in your vault. If you share your vault, you share your key!`);
    this._settingsFactory.createTextSetting(12 /* YouTubeApiKey */, `Used to access YouTube-specific information`);
  }
  _loadTemplatesSettings() {
    this._settingsFactory.createHeader("Component creations", 3, "Manage how new subModels are created");
    this._settingsFactory.createDropdownSetting(13 /* templateFolder */, `Select the folder in which you keep the templates for RPG Manager.`, this._folderMap);
    this._settingsFactory.createToggleSetting(11 /* automaticMove */, `Keeps your structure organised by creating subfolders for your Outlines and Elements`);
    this._settingsFactory.createToggleSetting(16 /* usePlotStructures */, `Use ABT/Story Circle plot structures`);
    this._settingsFactory.createToggleSetting(17 /* useSceneAnalyser */, `Analyses the scenes inside acts or sessions to provide running time estimations and act or session balance`);
  }
  _loadImagesSettings() {
    this._settingsFactory.createHeader("Images Management", 3, "Manage where you store the galleryService for all your campaigns");
    this._settingsFactory.createDropdownSetting(18 /* imagesFolder */, `Select the folder in which you keep the images for RPG Manager. Leave it empty if you want to use the default Obsidian Attachment folder. RPG Manager scans every subfolder in the one you selected`, this._folderMap);
  }
  _createFolderMap(parent = void 0, indent = 0) {
    let folderList = [];
    if (parent != void 0) {
      folderList = parent.children.filter((file) => file instanceof import_obsidian7.TFolder);
    } else {
      this._folderMap = /* @__PURE__ */ new Map();
      folderList = this.app.vault.getRoot().children.filter((file) => file instanceof import_obsidian7.TFolder);
    }
    folderList.forEach((folder) => {
      this._folderMap.set(folder.path, folder.path);
      this._createFolderMap(folder, indent + 1);
    });
  }
  _loadAdvancedSettings() {
    this._settingsFactory.createHeader("Lists", 3);
    Object.keys(this._plugin.settings.advanced.Agnostic).forEach((name, index) => {
      const advancedSetting = this._plugin.settings.advanced.Agnostic[name];
      this._addSettingsItem(name, advancedSetting);
    });
  }
  _addSettingsItem(type, settings) {
    var _a, _b, _c, _d, _e;
    const settingItemEl = this.containerEl.createDiv({ cls: "setting-item" });
    const settingItemInfoEl = settingItemEl.createDiv({ cls: "setting-item-info" });
    settingItemInfoEl.createDiv({ cls: "setting-item-name", text: (_b = (_a = this._advancedSettingsDescription.get(type)) == null ? void 0 : _a.title) != null ? _b : "" });
    settingItemInfoEl.createDiv({ cls: "setting-item-description", text: (_d = (_c = this._advancedSettingsDescription.get(type)) == null ? void 0 : _c.description) != null ? _d : "" }).createEl("br");
    const settingItemControlEl = settingItemEl.createDiv({ cls: "setting-item-control" });
    const listSettingTableEl = settingItemControlEl.createEl("table", { cls: "rpgm-advanced-settings-table" });
    const defaultSettings = rpgManagerDefaultSettings.advanced.Agnostic[type];
    for (let index = 0; index < defaultSettings.fields.length; index++) {
      const listSettingTableRowEl = listSettingTableEl.createEl("tr");
      listSettingTableRowEl.createEl("td", { text: (_e = tableFieldName.get(defaultSettings.fields[index].field)) != null ? _e : "" });
      const listSettingTableCheckboxEl = listSettingTableRowEl.createEl("td");
      const listSettingFieldCheckboxEl = listSettingTableCheckboxEl.createEl("input");
      listSettingFieldCheckboxEl.type = "checkbox";
      listSettingFieldCheckboxEl.dataset.id = index.toString();
      let isChecked = defaultSettings.fields[index].checked;
      for (let actualSettingsIndex = 0; actualSettingsIndex < settings.fields.length; actualSettingsIndex++) {
        if (settings.fields[actualSettingsIndex].field === defaultSettings.fields[index].field) {
          isChecked = settings.fields[actualSettingsIndex].checked;
          break;
        }
      }
      if (isChecked)
        listSettingFieldCheckboxEl.checked = true;
      if (defaultSettings.fields[index].required)
        listSettingFieldCheckboxEl.disabled = true;
      listSettingFieldCheckboxEl.addEventListener("change", () => {
        this._updateAdvancedListSettings(index, type, listSettingFieldCheckboxEl.checked);
      });
    }
  }
  _updateAdvancedListSettings(index, type, checked) {
    return __async(this, null, function* () {
      const name = type;
      const partialSettings = {
        advanced: {
          Agnostic: this._plugin.settings.advanced.Agnostic
        }
      };
      if (partialSettings.advanced !== void 0) {
        for (let defaultIndex = 0; defaultIndex < rpgManagerDefaultSettings.advanced.Agnostic[name].fields.length; defaultIndex++) {
          if (partialSettings.advanced.Agnostic[name].fields[defaultIndex] === void 0) {
            partialSettings.advanced.Agnostic[name].fields.push(rpgManagerDefaultSettings.advanced.Agnostic[name].fields[defaultIndex]);
          }
        }
        partialSettings.advanced.Agnostic[name].fields[index].checked = checked;
        yield this._plugin.updateSettings(partialSettings);
      }
      this.app.workspace.trigger("rpgmanager:refresh-views");
    });
  }
};

// src/managers/servicesManager/ServicesManager.ts
var ServicesManager = class {
  constructor(_api) {
    this._api = _api;
    this._services = /* @__PURE__ */ new Map();
  }
  deregister(serviceClass) {
    this._services.delete(serviceClass);
  }
  get(service) {
    return this._services.get(service);
  }
  register(serviceClass) {
    this._services.set(serviceClass, new serviceClass(this._api));
  }
};

// src/managers/viewsManager/ViewsManager.ts
var ViewsManager = class {
  constructor(_api) {
    this._api = _api;
    this._factories = /* @__PURE__ */ new Map();
    this._elements = /* @__PURE__ */ new Map();
  }
  create(viewType, componentType, campaignSettings) {
    let response = this._factories.get(this._getIdentifier(viewType, componentType, campaignSettings));
    if (response !== void 0)
      return response;
    if (campaignSettings === 0 /* Agnostic */)
      return void 0;
    response = this._factories.get(this._getIdentifier(viewType, componentType, 0 /* Agnostic */));
    if (response === void 0)
      return void 0;
    return response;
  }
  getElement(elementClass) {
    return new elementClass(this._api);
  }
  register(view, viewType, componentType, campaignSettings) {
    return __async(this, null, function* () {
      this._factories.set(this._getIdentifier(viewType, componentType, campaignSettings), view);
    });
  }
  registerElement(elementClass) {
    return __async(this, null, function* () {
      this._elements.set(elementClass, new elementClass(this._api));
    });
  }
  _getIdentifier(viewType, componentType, campaignSettings) {
    return viewType.toString() + "-" + componentType.toString() + "-" + campaignSettings.toString();
  }
};

// src/managers/componentsManager/ComponentsManager.ts
var ComponentsManager = class {
  constructor(_api) {
    this._api = _api;
    this._components = /* @__PURE__ */ new Map();
  }
  get(component) {
    const response = this._components.get(component);
    if (response === void 0) {
      this._api.service(LoggerService).createError(1 /* System */, "The requested component (" + component.name + ") does not exist");
      throw new Error("The requested component (" + component.name + ") does not exist");
    }
    return response;
  }
  register(componentClass) {
    const component = new componentClass(this._api);
    this._components.set(componentClass, component);
    this._api.models.register(component.model, component.type, component.campaignSettings);
    component.modalParts.forEach((modalPart) => {
      this._api.modals.registerPartial(modalPart, component.campaignSettings, component.type);
    });
    this._api.templates.register(component.template, component.campaignSettings, component.type);
    component.views.forEach((viewType, view) => {
      this._api.views.register(view, viewType, component.type, component.campaignSettings);
    });
  }
};

// src/managers/modelsManager/ModelsManager.ts
var ModelsManager = class {
  constructor(_api) {
    this._api = _api;
    this._models = /* @__PURE__ */ new Map();
  }
  get(id, campaignSettings, file) {
    let modelClass = this._models.get(this._getIdentifier(id.type, campaignSettings));
    if (modelClass !== void 0)
      return this._initialiseComponentModel(modelClass, id, campaignSettings, file);
    if (campaignSettings === 0 /* Agnostic */)
      return void 0;
    modelClass = this._models.get(this._getIdentifier(id.type, 0 /* Agnostic */));
    if (modelClass === void 0)
      return void 0;
    return this._initialiseComponentModel(modelClass, id, campaignSettings, file);
  }
  register(model, type, campaignSettings) {
    this._models.set(this._getIdentifier(type, campaignSettings), model);
  }
  _getIdentifier(type, campaignSettings) {
    return type.toString() + "-" + campaignSettings.toString();
  }
  _initialiseComponentModel(modelClass, id, campaignSettings, file) {
    const response = new modelClass(this._api);
    response.initialise(campaignSettings, id, file);
    return response;
  }
};

// src/managers/controllerManager/Controller.ts
var import_obsidian8 = require("obsidian");
var Controller = class extends import_obsidian8.MarkdownRenderChild {
  constructor(_api, container, _source, _component, _sourcePath) {
    super(container);
    this._api = _api;
    this._source = _source;
    this._component = _component;
    this._sourcePath = _sourcePath;
    this._componentVersion = void 0;
    this._isActive = false;
    this._views = /* @__PURE__ */ new Map();
    this.registerEvent(this._api.app.vault.on("rename", (file, oldPath) => this._onRename(file, oldPath)));
    this.registerEvent(this._api.app.workspace.on("rpgmanager:refresh-views", this._render.bind(this)));
    this.registerEvent(this._api.app.workspace.on("rpgmanager:force-refresh-views", (() => {
      this._render(true);
    }).bind(this)));
  }
  onload() {
    super.onload();
    this._render();
  }
  _onRename(file, oldPath) {
    return __async(this, null, function* () {
      if (this._sourcePath === oldPath)
        this._sourcePath = file.path;
      this._render();
    });
  }
  _initialise() {
    return __async(this, null, function* () {
      var _a;
      if (this._componentVersion !== void 0 && this._currentComponent.version === this._componentVersion)
        return false;
      this._componentVersion = (_a = this._currentComponent.version) != null ? _a : 0 + 0;
      return true;
    });
  }
  _waitForComponentToBeReady() {
    return __async(this, null, function* () {
      const poll = (resolve) => {
        if (this._api.database.isReady) {
          if (this._currentComponent === void 0)
            this._loadCurrentModel();
          if (this._currentComponent !== void 0 && this._currentComponent.version !== void 0)
            resolve();
          else
            setTimeout((callback) => poll(resolve), 100);
        } else {
          setTimeout((callback) => poll(resolve), 100);
        }
      };
      return new Promise(poll);
    });
  }
  _loadCurrentModel() {
    if (this._api.database === void 0)
      return;
    const rpgmComponent = this._api.database.readByPath(this._sourcePath);
    if (rpgmComponent === void 0)
      return;
    this._currentComponent = rpgmComponent;
    const yamlSource = (0, import_obsidian8.parseYaml)(this._source);
    if (yamlSource.models.header !== void 0) {
      const viewClass = this._api.views.create(0 /* Header */, this._currentComponent.index.type, this._currentComponent.campaignSettings);
      if (viewClass !== void 0)
        this._views.set(this._createModelIdentifier(0 /* Header */, this._currentComponent.index.type), { viewClassInterface: viewClass, type: 0 /* Header */ });
    }
    if (yamlSource.models.lists !== void 0) {
      Object.entries(yamlSource.models.lists).forEach(([relationshipType, value]) => {
        const componentType = this._api.service(RelationshipService).getComponentTypeFromListName(relationshipType);
        if (Array.isArray(value)) {
          for (let index = 0; index < value.length; index++) {
            this._loadRelationshipModel(componentType, relationshipType, value[index]);
          }
        } else {
          this._loadRelationshipModel(componentType, relationshipType, value);
        }
      });
    }
  }
  _createModelIdentifier(viewType, componentType, relatedType, relationshipType) {
    let response = viewType.toString() + "-";
    response += componentType.toString() + "-";
    if (relatedType !== void 0)
      response += relatedType.toString() + "-";
    if (relationshipType !== void 0)
      response += relationshipType.toString() + "-";
    return response;
  }
  _loadRelationshipModel(componentType, relationshipType, value) {
    let requiredRelationship = void 0;
    let relationshipTitle = void 0;
    if (value != void 0) {
      requiredRelationship = value.relationship ? this._api.service(RelationshipService).getTypeFromString(value.relationship) : void 0;
      relationshipTitle = value.title;
    }
    if (componentType !== void 0) {
      const viewClass = this._api.views.create(1 /* Relationships */, componentType, this._currentComponent.campaignSettings);
      if (viewClass !== void 0)
        this._views.set(this._createModelIdentifier(0 /* Header */, this._currentComponent.index.type, componentType, requiredRelationship), {
          viewClassInterface: viewClass,
          type: 1 /* Relationships */,
          relatedType: componentType,
          relationshipType: requiredRelationship,
          title: relationshipTitle
        });
    }
  }
  _render(forceRefresh = false) {
    return __async(this, null, function* () {
      this._render = (0, import_obsidian8.debounce)(this._render, 250, true);
      yield this._waitForComponentToBeReady();
      if (this._currentComponent === void 0)
        return;
      if (yield !this._isComponentVisible())
        return;
      if (forceRefresh)
        this._componentVersion = void 0;
      if (yield this._initialise()) {
        this.containerEl.empty();
        this._views.forEach((viewClassDetails, identifier) => {
          let view = void 0;
          if (viewClassDetails.type === 0 /* Header */) {
            view = new viewClassDetails.viewClassInterface(this._api, this._currentComponent, this.containerEl, this._sourcePath);
          } else {
            if (viewClassDetails.relatedType !== void 0) {
              view = new viewClassDetails.viewClassInterface(this._api, this._currentComponent, this.containerEl, this._sourcePath);
              view.relatedComponentType = viewClassDetails.relatedType;
              view.relationshipType = viewClassDetails.relationshipType;
              view.relationshipTitle = viewClassDetails.title;
            }
          }
          if (view !== void 0)
            view.render();
        });
        this.containerEl.show();
      }
    });
  }
  _isComponentVisible() {
    return __async(this, null, function* () {
      if (this._currentComponent === void 0) {
        return false;
      }
      if (this._currentComponent.file === void 0) {
        return false;
      }
      yield this._api.app.workspace.iterateAllLeaves((leaf) => {
        var _a;
        if (leaf.view instanceof import_obsidian8.MarkdownView) {
          const file = (_a = leaf.view) == null ? void 0 : _a.file;
          if (file !== void 0) {
            if (file.path === this._currentComponent.file.path)
              return true;
          }
        }
      });
      return false;
    });
  }
};

// src/managers/controllerManager/ControllerManager.ts
var ControllerManager = class {
  constructor(_api) {
    this._api = _api;
  }
  create(container, source, component, sourcePath) {
    return new Controller(this._api, container, source, component, sourcePath);
  }
};

// src/managers/modalsManager/ModalsManager.ts
var ModalsManager = class {
  constructor(_api) {
    this._api = _api;
    this._modals = /* @__PURE__ */ new Map();
    this._modalParts = /* @__PURE__ */ new Map();
  }
  getPartial(campaignSettings, type, modal) {
    let modalPartClass = this._modalParts.get(this._getIdentifier(campaignSettings, type));
    if (modalPartClass !== void 0)
      return this._initialiseComponentModalPart(modalPartClass, modal);
    if (campaignSettings === 0 /* Agnostic */) {
      this._api.service(LoggerService).createError(1 /* System */, "The requested element (" + ComponentType[type] + ") does not have a creation modal");
      throw new Error("The requested element (" + ComponentType[type] + ") does not have a creation modal");
    }
    modalPartClass = this._modalParts.get(this._getIdentifier(0 /* Agnostic */, type));
    if (modalPartClass === void 0) {
      this._api.service(LoggerService).createError(1 /* System */, "The requested element (" + ComponentType[type] + ") does not have a creation modal");
      throw new Error("The requested element (" + ComponentType[type] + ") does not have a creation modal");
    }
    return this._initialiseComponentModalPart(modalPartClass, modal);
  }
  registerPartial(modalPart, campaignSettings, type) {
    this._modalParts.set(this._getIdentifier(campaignSettings, type), modalPart);
  }
  _getIdentifier(campaignSettings, type) {
    return campaignSettings.toString() + "-" + type.toString();
  }
  _initialiseComponentModal(modalClass) {
    const response = new modalClass(this._api);
    return response;
  }
  _initialiseComponentModalPart(modalClass, modal) {
    const response = new modalClass(this._api, modal);
    return response;
  }
};

// src/managers/templatesManager/TemplatesManager.ts
var TemplatesManager = class {
  constructor(_api) {
    this._api = _api;
    this._templates = /* @__PURE__ */ new Map();
  }
  get(campaignSettings, type, templateName, name, campaignId, parentId, positionInParent, additionalInformation) {
    let templateClass = this._templates.get(this._getIdentifier(type, campaignSettings));
    if (templateClass !== void 0)
      return this._initialiseTemplate(templateClass, campaignSettings, type, templateName, name, campaignId, parentId, positionInParent, additionalInformation);
    if (campaignSettings === 0 /* Agnostic */) {
      this._api.service(LoggerService).createError(1 /* System */, "The requested element (" + ComponentType[type] + ") does not have a creation template");
      throw new Error("The requested element (" + ComponentType[type] + ") does not have a creation template");
    }
    templateClass = this._templates.get(this._getIdentifier(type, 0 /* Agnostic */));
    if (templateClass === void 0) {
      this._api.service(LoggerService).createError(1 /* System */, "The requested element (" + ComponentType[type] + ") does not have a creation template");
      throw new Error("The requested element (" + ComponentType[type] + ") does not have a creation template");
    }
    return this._initialiseTemplate(templateClass, campaignSettings, type, templateName, name, campaignId, parentId, positionInParent, additionalInformation);
  }
  register(templateClass, campaignSettings, type) {
    this._templates.set(this._getIdentifier(type, campaignSettings), templateClass);
  }
  _getIdentifier(type, campaignSettings) {
    return type.toString() + "-" + campaignSettings.toString();
  }
  _initialiseTemplate(templateClass, campaignSettings, type, templateName, name, campaignId, parentId, positionInParent, additionalInformation) {
    const response = new templateClass(this._api, templateName, name, this._api.service(IndexService).createUUID(), campaignId, parentId, positionInParent, additionalInformation);
    return response;
  }
};

// src/services/plotsService/plots/AbtPlot.ts
var AbtPlot = class {
  constructor(_metadata) {
    this._metadata = _metadata;
  }
  get and() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.abt) == null ? void 0 : _b.and) != null ? _c : "";
  }
  get but() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.abt) == null ? void 0 : _b.but) != null ? _c : "";
  }
  get isEmpty() {
    return this.need === "" && this.and === "" && this.but === "" && this.therefore === "";
  }
  get need() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.abt) == null ? void 0 : _b.need) != null ? _c : "";
  }
  get therefore() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.abt) == null ? void 0 : _b.therefore) != null ? _c : "";
  }
};

// src/services/plotsService/plots/StoryCirclePlot.ts
var StoryCirclePlot = class {
  constructor(_metadata) {
    this._metadata = _metadata;
  }
  get change() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.storycircle) == null ? void 0 : _b.change) != null ? _c : "";
  }
  get find() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.storycircle) == null ? void 0 : _b.find) != null ? _c : "";
  }
  get go() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.storycircle) == null ? void 0 : _b.go) != null ? _c : "";
  }
  get isEmpty() {
    return this.you === "" && this.need === "" && this.go === "" && this.search === "" && this.find === "" && this.take === "" && this.return === "" && this.change === "";
  }
  get need() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.storycircle) == null ? void 0 : _b.need) != null ? _c : "";
  }
  get return() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.storycircle) == null ? void 0 : _b.return) != null ? _c : "";
  }
  get search() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.storycircle) == null ? void 0 : _b.search) != null ? _c : "";
  }
  get take() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.storycircle) == null ? void 0 : _b.take) != null ? _c : "";
  }
  get you() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this._metadata.plot) == null ? void 0 : _a.storycircle) == null ? void 0 : _b.you) != null ? _c : "";
  }
};

// src/services/relationshipsService/RelationshipList.ts
var RelationshipList = class {
  constructor() {
    this.relationships = [];
  }
  _getIndexOfExistingRelationship(path2) {
    for (let index = 0; index < this.relationships.length; index++) {
      if (this.relationships[index].path === path2) {
        return index;
      }
    }
    return -1;
  }
  existsAlready(component) {
    return this.getByPath(component.file.path) !== void 0;
  }
  add(relationship, model) {
    const indexOfExistingRelationship = this._getIndexOfExistingRelationship(relationship.path);
    let existingRelationship = void 0;
    if (indexOfExistingRelationship !== -1)
      existingRelationship = this.getByPath(relationship.path);
    if (indexOfExistingRelationship !== -1 && existingRelationship !== void 0) {
      if (relationship.type === 8 /* Parent */ || relationship.type !== 1 /* Reversed */ && existingRelationship.type === 1 /* Reversed */ || !relationship.isInContent && existingRelationship.isInContent || relationship.type === existingRelationship.type) {
        if (relationship.isInContent && !this.relationships[indexOfExistingRelationship].isInContent) {
          this.relationships[indexOfExistingRelationship].isAlsoInContent = true;
          return;
        }
        this.relationships.splice(indexOfExistingRelationship, 1);
        this.relationships.push(relationship);
      }
    } else {
      this.relationships.push(relationship);
    }
  }
  remove(relationship) {
    const indexOfExistingRelationship = this._getIndexOfExistingRelationship(relationship.path);
    if (indexOfExistingRelationship === -1)
      return;
    const existingRelationship = this.getByPath(relationship.path);
    if (existingRelationship === void 0 || existingRelationship.isAlsoInContent)
      return;
    this.relationships.splice(indexOfExistingRelationship, 1);
  }
  getByPath(path2) {
    const matchingRelationships = this.relationships.filter((searchedRelationship) => searchedRelationship.path === path2);
    if (matchingRelationships.length !== 1)
      return void 0;
    return matchingRelationships[0];
  }
  filter(predicate, thisArg) {
    return this.relationships.filter(predicate);
  }
  forEach(callbackfn) {
    return this.relationships.forEach(callbackfn);
  }
  get stringified() {
    const response = [];
    for (let index = 0; index < this.relationships.length; index++) {
      const relationship = this.relationships[index];
      response.push({
        path: relationship.path,
        description: relationship.description,
        type: relationship.type.toString(),
        isInContent: relationship.isInContent.valueOf(),
        componentVersion: relationship.component !== void 0 ? relationship.component.version : 0
      });
    }
    return response;
  }
  md5() {
    const md5 = new Md5();
    md5.appendStr(JSON.stringify(this.stringified));
    return md5.end();
  }
};

// src/core/errors/ComponentNotFoundError.ts
var ComponentNotFoundError = class extends AbstractRpgManagerError {
  showErrorMessage() {
    return "COMPONENT NOT FOUND";
  }
  showErrorActions() {
    return "";
  }
};

// src/managers/modelsManager/abstracts/AbstractModel.ts
var AbstractModel = class {
  constructor(api) {
    this.api = api;
    this.stage = 3 /* Element */;
    this.version = void 0;
    this.metadata = {};
    this.frontmatter = {};
    this._relationships = new RelationshipList();
  }
  get abt() {
    return new AbtPlot({});
  }
  get alias() {
    var _a;
    const response = [];
    const metadata = this.api.app.metadataCache.getFileCache(this.file);
    if (metadata == null)
      return response;
    if (((_a = metadata == null ? void 0 : metadata.frontmatter) == null ? void 0 : _a.alias) != void 0 && metadata.frontmatter.alias.length > 0) {
      metadata.frontmatter.alias.forEach((alias) => {
        response.push(alias);
      });
    }
    return response;
  }
  get campaign() {
    if (this.index.type === 1 /* Campaign */)
      return this;
    return this.api.database.readById(this.index.campaignId);
  }
  get campaignSettings() {
    return this._campaignSettings;
  }
  get hasAbtPlot() {
    var _a, _b;
    return ((_b = (_a = this.metadata) == null ? void 0 : _a.plot) == null ? void 0 : _b.abt) !== void 0;
  }
  get hasStoryCirclePlot() {
    var _a, _b;
    return ((_b = (_a = this.metadata) == null ? void 0 : _a.plot) == null ? void 0 : _b.storycircle) !== void 0;
  }
  get images() {
    var _a, _b, _c, _d;
    const response = [];
    if (((_b = (_a = this.metadata) == null ? void 0 : _a.data) == null ? void 0 : _b.images) != void 0 && Array.isArray((_d = (_c = this.metadata) == null ? void 0 : _c.data) == null ? void 0 : _d.images)) {
      this.metadata.data.images.forEach((imageMetadata) => {
        const image = this.api.service(ImageService).createImage(imageMetadata.path, imageMetadata.caption);
        if (image !== void 0)
          response.push(image);
      });
    }
    return response;
  }
  get isComplete() {
    var _a, _b;
    return ((_b = (_a = this.metadata) == null ? void 0 : _a.data) == null ? void 0 : _b.complete) !== false;
  }
  get link() {
    return "[[" + this.file.basename + "]]";
  }
  get storyCircle() {
    return new StoryCirclePlot({});
  }
  get synopsis() {
    var _a;
    const response = (_a = this.metadata.data) == null ? void 0 : _a.synopsis;
    if (response === void 0 || response === "")
      return void 0;
    return response;
  }
  getRelationships(database = void 0) {
    this._relationships.filter((relationship) => relationship.component === void 0).forEach((relationship) => {
      if (relationship.component === void 0) {
        const path2 = relationship.path;
        if (relationship.type !== 64 /* Undefined */) {
          relationship.component = (database != null ? database : this.api.database).readByPath(path2);
        } else {
          const maybeRelatedComponents = (database != null ? database : this.api.database).read((component) => component.file.basename === path2);
          if (maybeRelatedComponents.length === 1) {
            relationship.type = 4 /* Unidirectional */;
            relationship.component = maybeRelatedComponents[0];
            relationship.path = maybeRelatedComponents[0].file.path;
          }
        }
      }
    });
    return this._relationships;
  }
  initialise(campaignSettings, id, file) {
    this._campaignSettings = campaignSettings;
    this.index = id;
    this.file = file;
    const metadataCache = this.api.app.metadataCache.getFileCache(this.file);
    if (metadataCache !== null)
      this.frontmatter = metadataCache.frontmatter;
  }
  initialiseData() {
    return __async(this, null, function* () {
      return;
    });
  }
  initialiseRelationships() {
    return __async(this, null, function* () {
      var _a;
      this._relationships = new RelationshipList();
      if (((_a = this.metadata) == null ? void 0 : _a.relationships) !== void 0) {
        yield this.metadata.relationships.forEach((relationshipMetadata) => {
          if (relationshipMetadata.path !== this.file.path) {
            const relationship = this.api.service(RelationshipService).createRelationshipFromMetadata(relationshipMetadata);
            if (relationship !== void 0)
              this._relationships.add(relationship);
          }
        });
      }
    });
  }
  readMetadata() {
    return __async(this, null, function* () {
      return this.api.service(CodeblockService).read(this.file).then((domain) => {
        this.api.service(RelationshipService).addRelationshipsFromContent(domain.originalFileContent, domain.codeblock, this.stage);
        this.metadata = domain.codeblock;
        return this.initialiseRelationships().then(() => {
          return;
        });
      }).catch((e) => {
        if (e.message === "INVALID YAML")
          return;
      });
    });
  }
  addRelationshipToRelatedElements() {
    return __async(this, null, function* () {
      var _a, _b;
      const relationships = this._relationships.relationships;
      for (let index = 0; index < relationships.length; index++) {
        if (relationships[index].component !== void 0) {
          const relationship = this.api.service(RelationshipService).createRelationshipFromReverse(this, relationships[index]);
          if (relationship !== void 0)
            (_a = relationships[index].component) == null ? void 0 : _a.getRelationships().add(relationship);
          (_b = relationships[index].component) == null ? void 0 : _b.touch();
        }
      }
    });
  }
  addReverseRelationships() {
    return __async(this, null, function* () {
      const recordset = this.api.database.recordset;
      for (let index = 0; index < recordset.length; index++) {
        const relationships = recordset[index].getRelationships().relationships.filter((relationship) => relationship.component !== void 0 && relationship.component.file.path === this.file.path);
        if (relationships.length === 1) {
          const newRelationship = this.api.service(RelationshipService).createRelationshipFromReverse(recordset[index], relationships[0]);
          if (newRelationship !== void 0)
            this._relationships.add(newRelationship);
        }
      }
    });
  }
  touch(force) {
    if (force) {
      this.version = Date.now();
      return true;
    }
    const md5 = new Md5();
    md5.appendStr(JSON.stringify(this.metadata));
    const metadataMd5 = md5.end();
    const relationshipsMd5 = this._relationships.md5();
    if (this._previousMetadata !== metadataMd5 || this._previousRelationships !== relationshipsMd5 || this._previousIndex !== this.index.checksum) {
      this._previousMetadata = metadataMd5;
      this._previousRelationships = relationshipsMd5;
      this._previousRelationshipsStringified = structuredClone(this._relationships.stringified);
      this._previousIndex = this.index.checksum;
      this.version = Date.now();
      return true;
    }
    return false;
  }
  validateHierarchy() {
    try {
      this.campaign;
    } catch (e) {
      throw new ComponentNotFoundError(this.api, this.index);
    }
  }
};

// src/services/plotsService/models/Plots.ts
var Plots = class extends AbstractModel {
  get abt() {
    return new AbtPlot(this.metadata);
  }
  get storyCircle() {
    return new StoryCirclePlot(this.metadata);
  }
};

// src/services/plotsService/enums/AbtStage.ts
var AbtStage = /* @__PURE__ */ ((AbtStage2) => {
  AbtStage2[AbtStage2["Need"] = 0] = "Need";
  AbtStage2[AbtStage2["And"] = 1] = "And";
  AbtStage2[AbtStage2["But"] = 2] = "But";
  AbtStage2[AbtStage2["Therefore"] = 3] = "Therefore";
  return AbtStage2;
})(AbtStage || {});

// src/services/plotsService/enums/StoryCircleStage.ts
var StoryCircleStage = /* @__PURE__ */ ((StoryCircleStage2) => {
  StoryCircleStage2[StoryCircleStage2["You"] = 0] = "You";
  StoryCircleStage2[StoryCircleStage2["Need"] = 1] = "Need";
  StoryCircleStage2[StoryCircleStage2["Go"] = 2] = "Go";
  StoryCircleStage2[StoryCircleStage2["Search"] = 3] = "Search";
  StoryCircleStage2[StoryCircleStage2["Find"] = 4] = "Find";
  StoryCircleStage2[StoryCircleStage2["Take"] = 5] = "Take";
  StoryCircleStage2[StoryCircleStage2["Return"] = 6] = "Return";
  StoryCircleStage2[StoryCircleStage2["Change"] = 7] = "Change";
  return StoryCircleStage2;
})(StoryCircleStage || {});

// src/managers/viewsManager/abstracts/AbstractView.ts
var AbstractView = class {
  constructor(api) {
    this.api = api;
  }
  addSeparator(containerEl) {
    containerEl.createSpan({ cls: "separator", text: " | " });
  }
  addLinkWithFunction(containerEl, text, fn, isLast = false) {
    const containerSpanEl = containerEl.createSpan({ cls: "link" });
    if (isLast)
      containerSpanEl.addClass("clearfix");
    const anchorEl = containerSpanEl.createEl("a", { href: "#", text });
    anchorEl.addEventListener("click", fn.bind(this));
  }
};

// src/services/plotsService/views/PlotView.ts
var import_obsidian14 = require("obsidian");

// src/services/contentEditorService/enums/EditableContentType.ts
var EditableContentType = /* @__PURE__ */ ((EditableContentType2) => {
  EditableContentType2[EditableContentType2["Synopsis"] = 0] = "Synopsis";
  EditableContentType2[EditableContentType2["Goals"] = 1] = "Goals";
  EditableContentType2[EditableContentType2["Address"] = 2] = "Address";
  EditableContentType2[EditableContentType2["Action"] = 3] = "Action";
  EditableContentType2[EditableContentType2["Trigger"] = 4] = "Trigger";
  EditableContentType2[EditableContentType2["Url"] = 5] = "Url";
  EditableContentType2[EditableContentType2["AbtNeed"] = 6] = "AbtNeed";
  EditableContentType2[EditableContentType2["AbtAnd"] = 7] = "AbtAnd";
  EditableContentType2[EditableContentType2["AbtBut"] = 8] = "AbtBut";
  EditableContentType2[EditableContentType2["AbtTherefore"] = 9] = "AbtTherefore";
  EditableContentType2[EditableContentType2["StoryCircleYou"] = 10] = "StoryCircleYou";
  EditableContentType2[EditableContentType2["StoryCircleNeed"] = 11] = "StoryCircleNeed";
  EditableContentType2[EditableContentType2["StoryCircleGo"] = 12] = "StoryCircleGo";
  EditableContentType2[EditableContentType2["StoryCircleSearch"] = 13] = "StoryCircleSearch";
  EditableContentType2[EditableContentType2["StoryCircleFind"] = 14] = "StoryCircleFind";
  EditableContentType2[EditableContentType2["StoryCircleTake"] = 15] = "StoryCircleTake";
  EditableContentType2[EditableContentType2["StoryCircleReturn"] = 16] = "StoryCircleReturn";
  EditableContentType2[EditableContentType2["StoryCircleChange"] = 17] = "StoryCircleChange";
  return EditableContentType2;
})(EditableContentType || {});

// src/services/contentEditorService/abstracts/AbstractEditorModal.ts
var AbstractEditorModal = class extends AbstractModal {
  constructor(api, contentEditor, component, editableContentType, editableField, isLongText) {
    super(api);
    this.contentEditor = contentEditor;
    this.component = component;
    this.editableContentType = editableContentType;
    this.editableField = editableField;
    this.isLongText = isLongText;
    if (this.editableContentType !== void 0) {
      const contentValue = this.contentEditor.read(this.component, this.editableContentType);
      if (contentValue != null)
        this.contentValue = contentValue.toString().replaceAll('\\"', '"').replaceAll("\\n", "\n");
      else
        this.contentValue = "";
    }
  }
  onClose() {
    if (this.autocompletionHelper !== void 0)
      this.autocompletionHelper.close();
    this.rpgmContainerEl.empty();
    super.onClose();
  }
  onOpen() {
    super.onOpen();
    this.contentEditorContainerEl = this.rpgmContainerEl.createDiv({ cls: "rpg-manager-content-editor" });
    this.contentEditorButtonContainerEl = this.rpgmContainerEl.createDiv({ cls: "rpg-manager-content-editor-button" });
    const contentEditorButtonEl = this.contentEditorButtonContainerEl.createEl("button", { text: "Save" });
    contentEditorButtonEl.addEventListener("click", this.saveContent.bind(this));
  }
  addElements(contentEl) {
    if (this.isLongText) {
      this.contentEditorEl = contentEl.createEl("textarea", { cls: "rpg-manager-content-editor-input" });
    } else {
      this.contentEditorEl = contentEl.createEl("input", { cls: "rpg-manager-content-editor-input" });
      this.contentEditorEl.type = "text";
    }
    if (this.isLongText)
      this.contentEditorEl.textContent = this.contentValue;
    else
      this.contentEditorEl.value = this.contentValue;
    this.contentEditorEl.selectionStart = this.contentValue.length;
  }
  saveContent() {
    return __async(this, null, function* () {
      const value = this.contentEditorEl.value.replaceAll('"', '\\"').replaceAll("\n", "\\n");
      this.api.service(CodeblockService).addOrUpdate(this.editableField, value);
      this.close();
    });
  }
};

// src/services/linkSuggesterService/textAnalysers/LinkSuggesterTextAnalyser.ts
var LinkSuggesterTextAnalyser = class {
  constructor() {
    this._cursorPosition = 0;
    this.fullText = "";
    this.searchTerm = "";
    this.aliasSearch = void 0;
    this.isAlreadyClosed = false;
    this.lengthBeforeStart = 0;
  }
  replace(searchResult) {
    if (!this.isAlreadyClosed)
      searchResult += "]]";
    this.fullText = this.fullText.substring(0, this.searchStartPosition) + searchResult + this.fullText.substring(this._cursorPosition);
    this.searchStartPosition = void 0;
    this.isAlreadyClosed = false;
    this.aliasSearch = void 0;
    this.searchTerm = "";
  }
  isInSearch(fullText, cursorPosition) {
    this.fullText = fullText;
    this._cursorPosition = cursorPosition == null ? 0 : cursorPosition;
    if (this._cursorPosition == null)
      return false;
    if (this.searchStartPosition === void 0 && this.fullText.length < 2)
      return false;
    if (this.searchStartPosition === void 0) {
      if (this._isSearchJustStarted) {
        this.searchStartPosition = this._cursorPosition;
      } else if (!this._isInExistingLink) {
        return false;
      }
    } else {
      if (this._isNotInSearchAnyLonger) {
        this.searchStartPosition = void 0;
        return false;
      }
    }
    if (this.searchStartPosition === void 0)
      return false;
    else
      this.lengthBeforeStart = this.searchStartPosition;
    this.searchTerm = this.fullText.substring(this.searchStartPosition, this._cursorPosition);
    const indexOfSeparator = this.searchTerm.indexOf("|");
    if (indexOfSeparator !== -1) {
      this.aliasSearch = this.searchTerm.substring(indexOfSeparator + 1);
      this.searchTerm = this.searchTerm.substring(0, indexOfSeparator);
    } else {
      this.aliasSearch = void 0;
    }
    return true;
  }
  get _isSearchJustStarted() {
    return this.fullText.substring(this._cursorPosition - 2, this._cursorPosition) === "[[";
  }
  get _isNotInSearchAnyLonger() {
    return this.fullText[this._cursorPosition - 1] === "[" && this.fullText[this._cursorPosition - 2] !== "[";
  }
  get _isInExistingLink() {
    const beforeCursor = this.fullText.substring(0, this._cursorPosition - 1);
    const afterCursor = this.fullText.substring(this._cursorPosition);
    const lastOpeningIndexBeforeCursor = beforeCursor.lastIndexOf("[[");
    const lastClosingIndexBeforeCursor = beforeCursor.lastIndexOf("]]");
    if (lastOpeningIndexBeforeCursor === -1 || lastClosingIndexBeforeCursor > lastOpeningIndexBeforeCursor)
      return false;
    const firstOpeningIndexAfterCursor = afterCursor.indexOf("[[");
    const firstClosingIndexAfterCursor = afterCursor.indexOf("]]");
    if (firstClosingIndexAfterCursor === -1 || firstOpeningIndexAfterCursor !== -1 && firstOpeningIndexAfterCursor < firstClosingIndexAfterCursor)
      return false;
    this.searchStartPosition = lastOpeningIndexBeforeCursor + 2;
    this.isAlreadyClosed = true;
    return true;
  }
};

// src/services/linkSuggesterService/popUps/LinkSuggesterPopUp.ts
var import_obsidian9 = require("obsidian");

// src/services/linkSuggesterService/eventListeners/LinkSuggesterKeyboardEventListener.ts
var LinkSuggesterKeyboardEventListener = class {
  constructor(_api, _handler) {
    this._api = _api;
    this._handler = _handler;
    this.listener = (evt) => this._handleKeyPress(evt);
  }
  _handleKeyPress(evt) {
    if (evt.key === "ArrowUp" || evt.key === "ArrowDown" || evt.key === "Enter" || evt.key === "Escape" || evt.key === "Tab") {
      evt.preventDefault();
      switch (evt.key) {
        case "ArrowDown":
          this._handler.moveDown();
          break;
        case "ArrowUp":
          this._handler.moveUp();
          break;
        case "Enter":
          this._handler.select(false);
          break;
        case "Tab":
          this._handler.select(true);
          break;
        case "Escape":
          this._handler.hide();
          break;
      }
    }
  }
};

// src/services/linkSuggesterService/popUps/LinkSuggesterPopUp.ts
var LinkSuggesterPopUp = class {
  constructor(_api, _handler) {
    this._api = _api;
    this._handler = _handler;
    this._mouseOverIndex = void 0;
    this._keyboardListener = new LinkSuggesterKeyboardEventListener(this._api, this);
    this._isListeningToKeyboard = false;
  }
  fill(results, top, left) {
    this._results = results;
    if (this._results.length === 0) {
      this.hide();
      return;
    }
    if (!this._isListeningToKeyboard) {
      document.addEventListener("keydown", this._keyboardListener.listener);
      this._isListeningToKeyboard = true;
    }
    let suggestionContainerEl = this._getSuggestionContainer();
    if (suggestionContainerEl === void 0) {
      suggestionContainerEl = document.createElement("div");
      suggestionContainerEl.addClass("suggestion-container");
      this._suggestionEl = suggestionContainerEl.createDiv({ cls: "suggestion" });
    } else {
      this._suggestionEl = suggestionContainerEl.childNodes[0];
      this._suggestionEl.empty();
    }
    this._results.forEach((searchResult, index) => {
      const suggestionItemEl = this._suggestionEl.createDiv({ cls: "suggestion-item mod-complex" });
      suggestionItemEl.addEventListener("mouseenter", () => {
        if (this._mouseOverIndex !== index) {
          suggestionItemEl.addClass("is-selected");
          if (this._currentIndex !== void 0 && this._suggestionEl.childNodes[this._currentIndex] != void 0)
            this._suggestionEl.childNodes[this._currentIndex].removeClass("is-selected");
          this._mouseOverIndex = index;
          this._currentIndex = index;
        }
      });
      suggestionItemEl.addEventListener("mouseout", () => {
        suggestionItemEl.removeClass("is-selected");
        if (this._currentIndex !== void 0 && this._suggestionEl.childNodes[this._currentIndex] != void 0)
          this._suggestionEl.childNodes[this._currentIndex].addClass("is-selected");
      });
      suggestionItemEl.addEventListener("click", () => {
        this._currentIndex = index;
        this.select(false);
      });
      const suggestionContentEl = suggestionItemEl.createDiv({ cls: "suggestion-content" });
      if (searchResult.fancyTitle !== void 0) {
        suggestionContentEl.appendChild(searchResult.fancyTitle);
      } else {
        suggestionContentEl.createDiv({
          cls: "suggestion-title",
          text: searchResult.title
        });
      }
      if (searchResult.fancySubtitle !== void 0) {
        suggestionContentEl.appendChild(searchResult.fancySubtitle);
      } else {
        const suggestionNoteEl = suggestionContentEl.createDiv({ cls: "suggestion-note" });
        if (searchResult.alias !== void 0) {
          suggestionNoteEl.textContent = searchResult.file.path.slice(0, -3);
        } else {
          const indexOfSubfolder = searchResult.file.path.lastIndexOf("/");
          if (indexOfSubfolder !== -1)
            suggestionNoteEl.textContent = searchResult.file.path.substring(0, indexOfSubfolder + 1);
        }
      }
      const suggestionAux = suggestionItemEl.createDiv({ cls: "suggestion-aux" });
      if (searchResult.alias !== void 0) {
        const suggestionFlairEl = suggestionAux.createSpan({ cls: "suggestion-flair" });
        suggestionFlairEl.ariaLabel = "Alias";
        (0, import_obsidian9.setIcon)(suggestionFlairEl, "corner-up-right");
      }
    });
    document.body.append(suggestionContainerEl);
    suggestionContainerEl.style.left = left + "px";
    suggestionContainerEl.style.top = top - suggestionContainerEl.clientHeight + "px";
    if (this._currentIndex !== void 0 && this._suggestionEl.childNodes[this._currentIndex] != void 0)
      this._suggestionEl.childNodes[this._currentIndex].addClass("is-selected");
  }
  clear() {
    this._currentIndex = 0;
    this._results = [];
    this.hide();
  }
  hide() {
    if (this._isListeningToKeyboard) {
      document.removeEventListener("keydown", this._keyboardListener.listener);
      this._isListeningToKeyboard = false;
    }
    const suggestionContainer = this._getSuggestionContainer();
    if (suggestionContainer !== void 0)
      suggestionContainer.remove();
  }
  moveUp() {
    return __async(this, null, function* () {
      if (this._currentIndex === 0 || this._currentIndex === void 0)
        return;
      this._suggestionEl.childNodes[this._currentIndex].removeClass("is-selected");
      this._currentIndex--;
      this._suggestionEl.childNodes[this._currentIndex].addClass("is-selected");
      this._ensureSelectedItemVisibility();
    });
  }
  moveDown() {
    return __async(this, null, function* () {
      if (this._results.length === 0)
        return;
      if (this._currentIndex === this._results.length - 1)
        return;
      if (this._currentIndex === void 0)
        return;
      this._suggestionEl.childNodes[this._currentIndex].removeClass("is-selected");
      this._currentIndex++;
      this._suggestionEl.childNodes[this._currentIndex].addClass("is-selected");
      this._ensureSelectedItemVisibility();
    });
  }
  _ensureSelectedItemVisibility() {
    this._getVisibleHeight(this._suggestionEl.childNodes[this._currentIndex]);
  }
  _getVisibleHeight(element) {
    const scrollTop = this._suggestionEl.scrollTop;
    const scrollBot = scrollTop + this._suggestionEl.clientHeight;
    const containerRect = this._suggestionEl.getBoundingClientRect();
    const eleRect = element.getBoundingClientRect();
    const rect = {};
    rect.top = eleRect.top - containerRect.top, rect.right = eleRect.right - containerRect.right, rect.bottom = eleRect.bottom - containerRect.bottom, rect.left = eleRect.left - containerRect.left;
    const eleTop = rect.top + scrollTop;
    const eleBot = eleTop + element.offsetHeight;
    if (scrollBot < eleBot) {
      this._suggestionEl.scrollTop = eleTop - (scrollBot - scrollTop) + element.clientHeight;
    } else if (eleTop < scrollTop) {
      this._suggestionEl.scrollTop = eleTop;
    }
  }
  select(stayInside) {
    if (this._currentIndex >= this._results.length)
      return;
    const selectedResult = this._results[this._currentIndex];
    if (selectedResult === void 0)
      return;
    if (this._isListeningToKeyboard) {
      document.removeEventListener("keydown", this._keyboardListener.listener);
      this._isListeningToKeyboard = false;
    }
    let position = selectedResult.file.basename.length;
    if (selectedResult.alias === selectedResult.title)
      position += selectedResult.alias.length + 1;
    if (!stayInside)
      position += 2;
    this._handler.confirmSelection(selectedResult, position);
    this.hide();
  }
  _getSuggestionContainer() {
    const suggestionContainerElememts = document.getElementsByClassName("suggestion-container");
    if (suggestionContainerElememts.length === 0)
      return void 0;
    return suggestionContainerElememts[0];
  }
};

// src/services/searchService/workers/FuzzyFileSearchWorker.ts
var import_obsidian10 = require("obsidian");

// src/services/searchService/abstracts/AbstractSearchWorker.ts
var AbstractSearchWorker = class {
  setFancyName(text, fuzzySearchResult, isTitle = true) {
    const response = document.createElement("div");
    response.addClass(isTitle ? "suggestion-title" : "suggestion-note");
    if (fuzzySearchResult == null || fuzzySearchResult.matches == null) {
      response.textContent = text;
      return response;
    }
    let currentTextIndex = 0;
    for (let index = 0; index < fuzzySearchResult.matches.length; index++) {
      const matchingPart = fuzzySearchResult.matches[index];
      const start = matchingPart[0];
      const end = matchingPart[1];
      if (start > currentTextIndex)
        response.appendChild(document.createTextNode(text.substring(currentTextIndex, start)));
      const responseSpanEl = document.createElement("span");
      responseSpanEl.addClass("suggestion-highlight");
      responseSpanEl.textContent = text.substring(start, end);
      response.appendChild(responseSpanEl);
      currentTextIndex = end;
    }
    if (text.length > currentTextIndex)
      response.appendChild(document.createTextNode(text.substring(currentTextIndex)));
    return response;
  }
};

// src/services/searchService/workers/FuzzyFileSearchWorker.ts
var FuzzyFileSearchWorker = class extends AbstractSearchWorker {
  constructor(_api) {
    super();
    this._api = _api;
  }
  search(term, searchOnlyAliases) {
    var _a;
    const response = [];
    let query = (0, import_obsidian10.prepareQuery)(term);
    const matches = /* @__PURE__ */ new Map();
    if (searchOnlyAliases === void 0) {
      const files = this._api.app.vault.getMarkdownFiles();
      files.forEach((file) => {
        var _a2;
        const metadata = this._api.app.metadataCache.getFileCache(file);
        if (metadata !== void 0 && ((_a2 = metadata == null ? void 0 : metadata.frontmatter) == null ? void 0 : _a2.alias) !== void 0 && metadata.frontmatter.alias.length > 0) {
          metadata.frontmatter.alias.forEach((alias) => {
            const fuzzySearchResult2 = (0, import_obsidian10.fuzzySearch)(query, alias);
            if (fuzzySearchResult2 != null && fuzzySearchResult2.matches != null && fuzzySearchResult2.score < 0) {
              matches.set(file.path + alias, {
                title: alias,
                file,
                alias,
                fancyTitle: this.setFancyName(alias, fuzzySearchResult2, true),
                fancySubtitle: this.setFancyName(file.path, (0, import_obsidian10.fuzzySearch)(query, file.path), false),
                resultScoring: fuzzySearchResult2
              });
            }
          });
        }
        const fuzzySearchResult = (0, import_obsidian10.fuzzySearch)(query, file.basename);
        if (fuzzySearchResult != null && fuzzySearchResult.matches !== null && fuzzySearchResult.score < 0) {
          matches.set(file.path, {
            title: file.basename,
            file,
            fancyTitle: this.setFancyName(file.basename, fuzzySearchResult, true),
            fancySubtitle: this.setFancyName(file.path, (0, import_obsidian10.fuzzySearch)(query, file.path), false),
            resultScoring: fuzzySearchResult
          });
        }
      });
    } else {
      query = (0, import_obsidian10.prepareQuery)(searchOnlyAliases);
      const files = this._api.app.vault.getMarkdownFiles().filter((file) => file.basename === term);
      if (files.length === 0)
        return [];
      const metadata = this._api.app.metadataCache.getFileCache(files[0]);
      if (metadata !== void 0 && ((_a = metadata == null ? void 0 : metadata.frontmatter) == null ? void 0 : _a.alias) !== void 0 && metadata.frontmatter.alias.length > 0) {
        metadata.frontmatter.alias.forEach((alias) => {
          const fuzzySearchResult = (0, import_obsidian10.fuzzySearch)(query, alias);
          matches.set(files[0].path + alias, {
            title: alias,
            file: files[0],
            alias,
            fancyTitle: this.setFancyName(alias, fuzzySearchResult, true),
            fancySubtitle: this.setFancyName(files[0].basename, null, false),
            resultScoring: fuzzySearchResult
          });
        });
      }
    }
    if (matches.size === 0)
      return [];
    matches.forEach((value) => {
      response.push(value);
    });
    response.sort((a, b) => b.resultScoring.score - a.resultScoring.score);
    return response;
  }
};

// src/services/searchService/workers/FuzzyElementSearchWorker.ts
var import_obsidian11 = require("obsidian");
var FuzzyElementSearchWorker = class extends AbstractSearchWorker {
  constructor(_api, _element, _type) {
    super();
    this._api = _api;
    this._element = _element;
    this._type = _type;
  }
  search(term, searchOnlyAliases) {
    const response = [];
    let query = (0, import_obsidian11.prepareQuery)(term);
    const matches = /* @__PURE__ */ new Map();
    if (searchOnlyAliases === void 0) {
      this._api.database.read((element) => element.index.campaignId === this._element.index.campaignId && (this._type !== void 0 ? element.index.type === this._type : true)).forEach((element) => {
        if (element.alias.length > 0) {
          element.alias.forEach((alias) => {
            const fuzzySearchResult2 = (0, import_obsidian11.fuzzySearch)(query, alias);
            if (fuzzySearchResult2 != null && fuzzySearchResult2.matches != null && fuzzySearchResult2.score < 0) {
              matches.set(element.file.path + alias, {
                title: alias,
                file: element.file,
                alias,
                fancyTitle: this.setFancyName(alias, fuzzySearchResult2, true),
                fancySubtitle: this.setFancyName(element.file.path, (0, import_obsidian11.fuzzySearch)(query, element.file.path), false),
                resultScoring: fuzzySearchResult2
              });
            }
          });
        }
        const fuzzySearchResult = (0, import_obsidian11.fuzzySearch)(query, element.file.basename);
        if (fuzzySearchResult != null && fuzzySearchResult.matches !== null && fuzzySearchResult.score < 0) {
          matches.set(element.file.path, {
            title: element.file.basename,
            file: element.file,
            fancyTitle: this.setFancyName(element.file.basename, fuzzySearchResult, true),
            fancySubtitle: this.setFancyName(element.file.path, (0, import_obsidian11.fuzzySearch)(query, element.file.path), false),
            resultScoring: fuzzySearchResult
          });
        }
      });
    } else {
      query = (0, import_obsidian11.prepareQuery)(searchOnlyAliases);
      const element = this._api.database.readByBaseName(term);
      if (element === void 0)
        return [];
      if (element.alias !== void 0 && element.alias.length > 0) {
        element.alias.forEach((alias) => {
          const fuzzySearchResult = (0, import_obsidian11.fuzzySearch)(query, alias);
          matches.set(element.file.path + alias, {
            title: alias,
            file: element.file,
            alias,
            fancyTitle: this.setFancyName(alias, fuzzySearchResult, true),
            fancySubtitle: this.setFancyName(element.file.basename, null, false),
            resultScoring: fuzzySearchResult
          });
        });
      }
    }
    if (matches.size === 0)
      return [];
    matches.forEach((value) => {
      response.push(value);
    });
    response.sort((a, b) => b.resultScoring.score - a.resultScoring.score);
    return response;
  }
};

// src/services/searchService/SearchService.ts
var SearchService = class extends AbstractService {
  search(term, type = 0 /* FuzzyFileSearch */, element, searchOnlyAliases, componentType) {
    let worker;
    switch (type) {
      case 0 /* FuzzyFileSearch */:
        worker = new FuzzyFileSearchWorker(this.api);
        break;
      case 1 /* FuzzyElementSearch */:
        if (element !== void 0)
          worker = new FuzzyElementSearchWorker(this.api, element, componentType);
        else
          worker = new FuzzyFileSearchWorker(this.api);
        break;
    }
    return worker.search(term, searchOnlyAliases);
  }
};

// src/services/linkSuggesterService/handlers/LinkSuggesterHandler.ts
var LinkSuggesterHandler = class {
  constructor(_api, _containerEl, _component, _type) {
    this._api = _api;
    this._containerEl = _containerEl;
    this._component = _component;
    this._type = _type;
    this._containerEl.addEventListener("keyup", this._inputEvent.bind(this));
    this._containerEl.addEventListener("keydown", this._textStyleEvent.bind(this));
    this._analyser = new LinkSuggesterTextAnalyser();
    this._displayer = new LinkSuggesterPopUp(this._api, this);
  }
  _textStyleEvent(evt) {
    if (this._containerEl.selectionStart == void 0 || this._containerEl.selectionEnd == void 0)
      return;
    if (this._containerEl.selectionStart === this._containerEl.selectionEnd)
      return;
    if ((evt.metaKey || evt.ctrlKey) && evt.key === "b")
      this._containerEl.value = this._containerEl.value.substring(0, this._containerEl.selectionStart) + "**" + this._containerEl.value.substring(this._containerEl.selectionStart, this._containerEl.selectionEnd) + "**" + this._containerEl.value.substring(this._containerEl.selectionEnd);
    if ((evt.metaKey || evt.ctrlKey) && evt.key === "i")
      this._containerEl.value = this._containerEl.value.substring(0, this._containerEl.selectionStart) + "*" + this._containerEl.value.substring(this._containerEl.selectionStart, this._containerEl.selectionEnd) + "*" + this._containerEl.value.substring(this._containerEl.selectionEnd);
  }
  _inputEvent(evt) {
    var _a;
    if (this._analyser.isInSearch(this._containerEl.value, this._containerEl.selectionStart)) {
      if (this._analyser.searchTerm !== this._previousSearch || this._analyser.aliasSearch !== this._previousAlias) {
        this._previousSearch = this._analyser.searchTerm;
        this._previousAlias = this._analyser.aliasSearch;
        const getCaretCoordinates = require_pixelFinder();
        const caret = getCaretCoordinates(this._containerEl);
        const x = this._offset(this._containerEl);
        const top = x.top + caret.top;
        const left = x.left + caret.left;
        this._displayer.fill((_a = this._api.service(SearchService).search(this._analyser.searchTerm, 1 /* FuzzyElementSearch */, this._component, this._analyser.aliasSearch, this._type)) != null ? _a : [], top, left);
      }
    } else {
      this._displayer.clear();
    }
  }
  _offset(el) {
    const rect = el.getBoundingClientRect(), scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    return { top: rect.top + scrollTop, left: rect.left + scrollLeft };
  }
  confirmSelection(result, position) {
    return __async(this, null, function* () {
      var _a;
      if (result.alias !== void 0)
        this._analyser.replace(result.file.basename + "|" + result.alias);
      else
        this._analyser.replace(result.file.basename);
      this._containerEl.value = this._analyser.fullText;
      this._containerEl.selectionStart = this._analyser.lengthBeforeStart + ((_a = this._analyser.searchStartPosition) != null ? _a : 0) + position;
      this._containerEl.selectionEnd = this._containerEl.selectionStart;
      this._containerEl.focus();
    });
  }
  close() {
    this._previousSearch = void 0;
    this._previousAlias = void 0;
    this._displayer.clear();
    this._containerEl.removeEventListener("keyup", this._inputEvent);
  }
};

// src/services/linkSuggesterService/handlers/SimplifiedLinkSuggestionHandler.ts
var SimplifiedLinkSuggestionHandler = class {
  constructor(_api, _containerEl, _component, _type) {
    this._api = _api;
    this._containerEl = _containerEl;
    this._component = _component;
    this._type = _type;
    this._containerEl.addEventListener("keyup", this._inputEvent.bind(this));
    this._displayer = new LinkSuggesterPopUp(this._api, this);
  }
  close() {
    this._displayer.clear();
    this._containerEl.removeEventListener("keyup", this._inputEvent);
  }
  confirmSelection(selectedResult, position) {
    this._containerEl.value = selectedResult.file.basename;
    this._containerEl.blur();
  }
  _inputEvent(evt) {
    var _a;
    if (this._containerEl.value === this._previousSearch)
      return;
    if (this._containerEl.value === "") {
      this._displayer.clear();
      return;
    }
    this._previousSearch = this._containerEl.value;
    this._displayer.fill((_a = this._api.service(SearchService).search(this._containerEl.value, 1 /* FuzzyElementSearch */, this._component, void 0, this._type)) != null ? _a : [], this._containerEl.getBoundingClientRect().top + this._containerEl.offsetHeight, this._containerEl.getBoundingClientRect().left);
  }
};

// src/services/linkSuggesterService/LinkSuggesterService.ts
var LinkSuggesterService = class {
  constructor(_api) {
    this._api = _api;
  }
  createHandler(editorEl, model, type) {
    return new LinkSuggesterHandler(this._api, editorEl, model, type);
  }
  createSimplifiedHandler(editorEl, model, type) {
    return new SimplifiedLinkSuggestionHandler(this._api, editorEl, model, type);
  }
};

// src/services/contentEditorService/modals/ContentEditorModal.ts
var ContentEditorModal = class extends AbstractEditorModal {
  constructor(api, contentEditor, component, editableContentType, editableField, isLongText) {
    super(api, contentEditor, component, editableContentType, editableField, isLongText);
    let title = "";
    switch (this.editableContentType) {
      case 6 /* AbtNeed */:
        title = "Need";
        break;
      case 7 /* AbtAnd */:
        title = "And";
        break;
      case 8 /* AbtBut */:
        title = "But";
        break;
      case 9 /* AbtTherefore */:
        title = "Therefore";
        break;
      default:
        if (this.editableContentType !== void 0)
          title = EditableContentType[this.editableContentType];
        break;
    }
    this.title = "Edit the " + title + " for " + this.component.file.basename;
  }
  onOpen() {
    super.onOpen();
    this.addElements(this.contentEditorContainerEl);
    this.autocompletionHelper = this.api.service(LinkSuggesterService).createHandler(this.contentEditorEl, this.component);
  }
  onClose() {
    super.onClose();
  }
};

// src/services/contentEditorService/modals/StoryCircleContentEditorModal.ts
var import_obsidian12 = require("obsidian");
var StoryCircleContentEditorModal = class extends AbstractEditorModal {
  constructor(api, contentEditor, component, editableContentType, editableField, _relatedAbtValue) {
    super(api, contentEditor, component, editableContentType, editableField, true);
    this._relatedAbtValue = _relatedAbtValue;
    this.maxWidth = true;
    let title = "";
    switch (this.editableContentType) {
      case 10 /* StoryCircleYou */:
        title = "You";
        break;
      case 11 /* StoryCircleNeed */:
        title = "Need";
        break;
      case 12 /* StoryCircleGo */:
        title = "Go";
        break;
      case 13 /* StoryCircleSearch */:
        title = "Search";
        break;
      case 14 /* StoryCircleFind */:
        title = "Find";
        break;
      case 15 /* StoryCircleTake */:
        title = "Take";
        break;
      case 16 /* StoryCircleReturn */:
        title = "Return";
        break;
      case 17 /* StoryCircleChange */:
        title = "Change";
        break;
    }
    this.title = 'Edit the "' + title + '" part of the Story Circle Plot for ' + this.component.file.basename;
  }
  onOpen() {
    super.onOpen();
    this.rpgmContainerEl.createDiv({ cls: "rpg-manager-content-editor-plot-container" });
    if (this._relatedAbtValue !== "") {
      this.contentEditorContainerEl.addClass("clearfix");
      const alternativeTextContainerEl = this.contentEditorContainerEl.createDiv({ cls: "rpg-manager-content-editor-abt-relative" });
      alternativeTextContainerEl.createEl("h3", { text: "Relative ABT Plot" });
      const alternativeTextEl = alternativeTextContainerEl.createDiv();
      import_obsidian12.MarkdownRenderer.renderMarkdown(this._relatedAbtValue, alternativeTextEl, "", null);
      const editorContainerEl = this.contentEditorContainerEl.createDiv({ cls: "rpg-manager-content-editor-storycircle-container" });
      this.addElements(editorContainerEl);
    } else {
      this.addElements(this.contentEditorContainerEl);
    }
    this.autocompletionHelper = this.api.service(LinkSuggesterService).createHandler(this.contentEditorEl, this.component);
  }
};

// src/services/contentEditorService/modals/RelationshipEditorModal.ts
var RelationshipEditorModal = class extends AbstractEditorModal {
  constructor(api, contentEditor, component, editableField, _relationship) {
    var _a, _b, _c;
    super(api, contentEditor, component, void 0, editableField, true);
    this._relationship = _relationship;
    this.contentValue = ((_a = this._relationship.description) != null ? _a : "").replaceAll('\\"', '"');
    if (this._relationship.type === 4 /* Unidirectional */ || this._relationship.type === 16 /* Child */)
      this.title = "Edit the relationship " + this.component.file.basename + " has with " + ((_b = this._relationship.component) == null ? void 0 : _b.file.basename);
    else
      this.title = "Edit the relationship between " + this.component.file.basename + " and " + ((_c = this._relationship.component) == null ? void 0 : _c.file.basename);
  }
  onOpen() {
    super.onOpen();
    this.addElements(this.contentEditorContainerEl);
    this.autocompletionHelper = this.api.service(LinkSuggesterService).createHandler(this.contentEditorEl, this.component);
  }
  saveContent() {
    return __async(this, null, function* () {
      this._relationship.description = this.contentEditorEl.value.replaceAll('"', '\\"');
      this.api.service(CodeblockService).addOrUpdateRelationship(this._relationship);
      this.close();
    });
  }
};

// src/services/contentEditorService/ContentEditorService.ts
var ContentEditorService = class extends AbstractService {
  open(component, editableField) {
    return __async(this, null, function* () {
      const type = yield this._getContentType(editableField);
      let relatedComponent = [];
      switch (type) {
        case 0 /* Synopsis */:
        case 1 /* Goals */:
        case 3 /* Action */:
        case 4 /* Trigger */:
        case 6 /* AbtNeed */:
        case 7 /* AbtAnd */:
        case 8 /* AbtBut */:
        case 9 /* AbtTherefore */:
          new ContentEditorModal(this.api, this, component, type, editableField, true).open();
          return true;
          break;
        case 2 /* Address */:
        case 5 /* Url */:
          new ContentEditorModal(this.api, this, component, type, editableField, false).open();
          return true;
          break;
        case 10 /* StoryCircleYou */:
        case 11 /* StoryCircleNeed */:
        case 12 /* StoryCircleGo */:
        case 13 /* StoryCircleSearch */:
        case 14 /* StoryCircleFind */:
        case 15 /* StoryCircleTake */:
        case 16 /* StoryCircleReturn */:
        case 17 /* StoryCircleChange */:
          new StoryCircleContentEditorModal(this.api, this, component, type, editableField, this._readRelatedPlot(component, type)).open();
          break;
        default:
          relatedComponent = component.getRelationships().filter((relationship) => relationship.path === editableField);
          if (relatedComponent.length !== 1)
            return false;
          new RelationshipEditorModal(this.api, this, component, editableField, relatedComponent[0]).open();
          break;
      }
      return false;
    });
  }
  read(component, type) {
    let response = void 0;
    switch (type) {
      case 0 /* Synopsis */:
        response = component.synopsis;
        break;
      case 1 /* Goals */:
        response = component.goals;
        break;
      case 2 /* Address */:
        response = component.address;
        break;
      case 3 /* Action */:
        response = component.action;
        break;
      case 4 /* Trigger */:
        response = component.trigger;
        break;
      case 5 /* Url */:
        response = component.url;
        break;
      case 6 /* AbtNeed */:
        response = component.abt.need;
        break;
      case 7 /* AbtAnd */:
        response = component.abt.and;
        break;
      case 8 /* AbtBut */:
        response = component.abt.but;
        break;
      case 9 /* AbtTherefore */:
        response = component.abt.therefore;
        break;
      case 10 /* StoryCircleYou */:
        response = component.storyCircle.you;
        break;
      case 11 /* StoryCircleNeed */:
        response = component.storyCircle.need;
        break;
      case 12 /* StoryCircleGo */:
        response = component.storyCircle.go;
        break;
      case 13 /* StoryCircleSearch */:
        response = component.storyCircle.search;
        break;
      case 14 /* StoryCircleFind */:
        response = component.storyCircle.find;
        break;
      case 15 /* StoryCircleTake */:
        response = component.storyCircle.take;
        break;
      case 16 /* StoryCircleReturn */:
        response = component.storyCircle.return;
        break;
      case 17 /* StoryCircleChange */:
        response = component.storyCircle.change;
        break;
    }
    return response;
  }
  _getContentType(editableField) {
    switch (editableField.toLowerCase()) {
      case "data.synopsis":
        return 0 /* Synopsis */;
        break;
      case "data.goals":
        return 1 /* Goals */;
        break;
      case "data.address":
        return 2 /* Address */;
        break;
      case "data.action":
        return 3 /* Action */;
        break;
      case "data.trigger":
        return 4 /* Trigger */;
        break;
      case "data.url":
        return 5 /* Url */;
        break;
      case "plot.abt.need":
        return 6 /* AbtNeed */;
        break;
      case "plot.abt.and":
        return 7 /* AbtAnd */;
        break;
      case "plot.abt.but":
        return 8 /* AbtBut */;
        break;
      case "plot.abt.therefore":
        return 9 /* AbtTherefore */;
        break;
      case "plot.storycircle.you":
        return 10 /* StoryCircleYou */;
        break;
      case "plot.storycircle.need":
        return 11 /* StoryCircleNeed */;
        break;
      case "plot.storycircle.go":
        return 12 /* StoryCircleGo */;
        break;
      case "plot.storycircle.search":
        return 13 /* StoryCircleSearch */;
        break;
      case "plot.storycircle.find":
        return 14 /* StoryCircleFind */;
        break;
      case "plot.storycircle.take":
        return 15 /* StoryCircleTake */;
        break;
      case "plot.storycircle.return":
        return 16 /* StoryCircleReturn */;
        break;
      case "plot.storycircle.change":
        return 17 /* StoryCircleChange */;
        break;
    }
    return void 0;
  }
  _readRelatedPlot(component, type) {
    var _a, _b, _c, _d;
    switch (type) {
      case 10 /* StoryCircleYou */:
      case 11 /* StoryCircleNeed */:
        return (_a = component.abt.need) != null ? _a : "";
      case 12 /* StoryCircleGo */:
      case 13 /* StoryCircleSearch */:
        return (_b = component.abt.and) != null ? _b : "";
      case 14 /* StoryCircleFind */:
      case 15 /* StoryCircleTake */:
        return (_c = component.abt.but) != null ? _c : "";
      case 16 /* StoryCircleReturn */:
      case 17 /* StoryCircleChange */:
        return (_d = component.abt.therefore) != null ? _d : "";
    }
  }
};

// src/services/helpService/HelpService.ts
var import_obsidian13 = require("obsidian");
var HelpService = class extends AbstractService {
  add(containerEl, description) {
    return __async(this, null, function* () {
      const helpIconEl = containerEl.createSpan({ cls: "rpg-manager-help", text: "?" });
      const descriptionContainerEl = document.createElement("div");
      descriptionContainerEl.addClass("rpg-manager-help-content-container");
      const descriptionContentEl = descriptionContainerEl.createDiv({ cls: "rpg-manager-help-content" });
      import_obsidian13.MarkdownRenderer.renderMarkdown(description, descriptionContentEl, "", null);
      helpIconEl.addEventListener("mouseover", () => {
        descriptionContainerEl.style.left = helpIconEl.getBoundingClientRect().left.toString() + "px";
        descriptionContainerEl.style.top = (helpIconEl.getBoundingClientRect().top + helpIconEl.offsetHeight).toString() + "px";
        document.body.append(descriptionContainerEl);
      });
      helpIconEl.addEventListener("mouseout", () => {
        const descriptionEls = document.getElementsByClassName("rpg-manager-help-content-container");
        for (let index = 0; index < descriptionEls.length; index++) {
          if (descriptionEls[index].hasClass("rpg-manager-help-content-container"))
            descriptionEls[index].remove();
        }
      });
    });
  }
};

// src/services/plotsService/views/PlotView.ts
var PlotView = class extends AbstractView {
  constructor() {
    super(...arguments);
    this._abtDescription = "## ABT Plot\nThe **ABT Plot** is a way of dividing a campaign, adventure or act into manageable chunks that create a positive impact on your players.\n**Need**: The *need* part should introduce the player characters to what they need to do.\n**And**:The *and* part should see the player characters decide to try and achieve their goals and get on with it.\n**But**: The *but* part should introduce a problem for the player characters and give them a new goal\n**Therefore**: The *therefore* part should allow the player characters to achieve their new goals and succeed.";
    this._storyCircleDescription = "## Story Circle Plot\nThe **Story Plot** is a way of dividing a campaign, adventure or act into manageable chunks that create a positive impact on your players.\n**You**: Introduce the player characters to their current life.\n**Need**: Make them **feel** there is something they need to achieve.\n**Go**: Allow them to decide to try and get what they need.\n**Search**: The player characters should try and get it.\n**Find**: When they find what they were looking for, the player characters should realise there is a **problem**, and that their real goal is something different.\n**Take**: The player characters should understand what they need to do next\n**Return**: and they should find a way of reaching their new goal.\n**Change**: Finally, they should achieve the final goal and be rewarded for it.";
  }
  render(model, plot, containerEl) {
    const plotContainerEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-plot-container" });
    const plotContainerTitleEl = plotContainerEl.createDiv({ cls: "rpg-manager-header-container-info-plot-container-title" });
    const plotContainerDetailsEl = plotContainerEl.createDiv({ cls: "rpg-manager-header-container-info-plot-container-elements" });
    if (plot instanceof AbtPlot) {
      plotContainerTitleEl.textContent = "ABT Plot";
      this.api.service(HelpService).add(plotContainerTitleEl, this._abtDescription);
      this._renderAbtPlot(model, plot, plotContainerDetailsEl);
    } else if (plot instanceof StoryCirclePlot) {
      plotContainerTitleEl.textContent = "Story Circle Plot";
      this.api.service(HelpService).add(plotContainerTitleEl, this._storyCircleDescription);
      this._renderStoryCirclePlot(model, plot, plotContainerDetailsEl);
    }
  }
  _renderAbtPlot(model, plot, containerEl) {
    this._renderPlotElement(model, "plot.abt.need", "Need", plot.need, containerEl);
    this._renderPlotElement(model, "plot.abt.and", "And", plot.and, containerEl);
    this._renderPlotElement(model, "plot.abt.but", "But", plot.but, containerEl);
    this._renderPlotElement(model, "plot.abt.therefore", "Therefore", plot.therefore, containerEl);
  }
  _renderStoryCirclePlot(model, plot, containerEl) {
    this._renderPlotElement(model, "plot.storycircle.you", "You", plot.you, containerEl);
    this._renderPlotElement(model, "plot.storycircle.need", "Need", plot.need, containerEl);
    this._renderPlotElement(model, "plot.storycircle.go", "Go", plot.go, containerEl);
    this._renderPlotElement(model, "plot.storycircle.search", "Search", plot.search, containerEl);
    this._renderPlotElement(model, "plot.storycircle.find", "Find", plot.find, containerEl);
    this._renderPlotElement(model, "plot.storycircle.take", "Take", plot.take, containerEl);
    this._renderPlotElement(model, "plot.storycircle.return", "Return", plot.return, containerEl);
    this._renderPlotElement(model, "plot.storycircle.change", "Change", plot.change, containerEl);
  }
  _renderPlotElement(model, editableField, title, description, containerEl) {
    const plotElementContainerEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-plot-container-elements-container clearfix" });
    plotElementContainerEl.createDiv({ cls: "rpg-manager-header-container-info-plot-container-elements-container-title", text: title });
    const plotDescriptionEl = plotElementContainerEl.createDiv({ cls: "rpg-manager-header-container-info-plot-container-elements-container-description" });
    import_obsidian14.MarkdownRenderer.renderMarkdown(description, plotDescriptionEl, "", null);
    const plotEditorEl = plotElementContainerEl.createDiv({ cls: "rpg-manager-header-container-info-plot-container-elements-container-editor" });
    (0, import_obsidian14.setIcon)(plotEditorEl, "edit");
    plotEditorEl.addEventListener("click", () => {
      this.api.service(ContentEditorService).open(model, editableField);
    });
  }
};

// src/services/plotsService/PlotService.ts
var PlotService = class {
  constructor(api) {
    this.api = api;
  }
  getAbtStage(readableAbtStage) {
    readableAbtStage = readableAbtStage[0].toUpperCase() + readableAbtStage.substring(1).toLowerCase();
    return AbtStage[readableAbtStage];
  }
  getReadableAbtStage(type) {
    return AbtStage[type].toString().toLowerCase();
  }
  getReadableStoryCircleStage(type) {
    return StoryCircleStage[type].toString().toLowerCase();
  }
  getStoryCircleStage(readableStoryCircleStage) {
    readableStoryCircleStage = readableStoryCircleStage[0].toUpperCase() + readableStoryCircleStage.substring(1).toLowerCase();
    return StoryCircleStage[readableStoryCircleStage];
  }
  getView() {
    return new PlotView(this.api);
  }
};

// src/components/act/abstracts/AbstractActData.ts
var AbstractActData = class extends Plots {
  get abtStage() {
    var _a;
    if (((_a = this.metadata.data) == null ? void 0 : _a.abtStage) == void 0 || this.metadata.data.abtStage === "")
      return void 0;
    return this.api.service(PlotService).getAbtStage(this.metadata.data.abtStage);
  }
};

// src/components/act/models/ActModel.ts
var ActModel = class extends AbstractActData {
  constructor() {
    super(...arguments);
    this.stage = 0 /* Plot */;
  }
  validateHierarchy() {
    super.validateHierarchy();
    try {
      this.adventure.validateHierarchy();
    } catch (e) {
      throw new ComponentNotFoundError(this.api, this.index);
    }
  }
  get adventure() {
    return this.api.database.readById(this.index.parentId);
  }
  get nextAct() {
    return this._adjacentAct(true);
  }
  get previousAct() {
    return this._adjacentAct(false);
  }
  _adjacentAct(next) {
    var _a;
    const response = this.api.database.read((act) => act.index.type === 4 /* Act */ && act.index.campaignId === this.index.campaignId && act.index.positionInParent === (next ? act.index.positionInParent + 1 : act.index.positionInParent - 1));
    return (_a = response[0]) != null ? _a : null;
  }
  getRelationships(database) {
    const response = super.getRelationships(database);
    this.api.database.read((scene) => scene.index.type === 8 /* Scene */ && scene.index.campaignId === this.index.campaignId && scene.index.parentId === this.index.id).forEach((scene) => {
      scene.getRelationships().forEach((sceneRelationship) => {
        if (sceneRelationship.component !== void 0)
          response.add(this.api.service(RelationshipService).createRelationship(4 /* Unidirectional */, sceneRelationship.path, void 0, sceneRelationship.component));
      });
      response.add(this.api.service(RelationshipService).createRelationship(32 /* Hierarchy */, scene.file.path, void 0, scene));
    });
    return response;
  }
};

// src/services/breadcrumbService/BreadcrumbElement.ts
var BreadcrumbElement = class {
  constructor(model) {
    this.model = model;
    this.isInNewLine = false;
    this.mainTitle = null;
    this.function = null;
  }
};

// src/services/fileCreationService/FileCreationService.ts
var import_obsidian15 = require("obsidian");
var path = require("path");
var FileCreationService = class extends AbstractService {
  create(settings, type, create, templateName, name, campaignId, parentId, positionInParent = 0, additionalInformation) {
    return __async(this, null, function* () {
      let pathSeparator = "";
      try {
        pathSeparator = path.sep;
      } catch (e) {
        pathSeparator = "/";
      }
      let folder = pathSeparator;
      const campaigns = this.api.database.read((campaign) => campaign.index.type === 1 /* Campaign */ && campaign.index.id === campaignId);
      if (campaigns.length === 1) {
        settings = campaigns[0].campaignSettings;
        folder = campaigns[0].folder;
      }
      const template = this.api.templates.get(settings, type, templateName, name, campaignId, parentId, positionInParent, additionalInformation);
      const fileName = yield this._generateFilePath(type, folder, name, pathSeparator);
      let file = void 0;
      if (!create) {
        const activeView = app.workspace.getActiveViewOfType(import_obsidian15.MarkdownView);
        if (activeView != null)
          file = activeView.file;
      }
      template.generateData(file).then((data) => {
        if (create) {
          this._createNewFile(data, fileName);
        } else {
          this._editExistingFile(data, fileName);
        }
      });
    });
  }
  _createNewFile(data, fileName) {
    return __async(this, null, function* () {
      const newFile = yield app.vault.create(fileName, data);
      const currentLeaf = app.workspace.getActiveViewOfType(import_obsidian15.MarkdownView);
      const leaf = app.workspace.getLeaf(currentLeaf != null);
      yield leaf.openFile(newFile);
    });
  }
  _editExistingFile(data, fileName) {
    return __async(this, null, function* () {
      const activeView = app.workspace.getActiveViewOfType(import_obsidian15.MarkdownView);
      if (activeView != null) {
        const editor = activeView.editor;
        let file = activeView.file;
        let currentValue = editor.getValue();
        const metadata = this.api.app.metadataCache.getFileCache(file);
        if (metadata != void 0 && metadata.sections != void 0 && metadata.sections.length > 0) {
          if (metadata.sections[0].type === "yaml") {
            const editor2 = activeView.editor;
            const codeblockStart = { line: metadata.sections[0].position.start.line + 1, ch: 0 };
            const codeblockEnd = { line: metadata.sections[0].position.end.line, ch: 0 };
            const codeblockContent = yield editor2.getRange(codeblockStart, codeblockEnd);
            currentValue = currentValue.replace("---\n" + codeblockContent + "---", "");
          }
        }
        editor.setValue(data + "\n" + currentValue);
        yield this.api.app.fileManager.renameFile(file, fileName);
        file = activeView.file;
        app.workspace.getLeaf().openFile(file);
      }
    });
  }
  silentCreate(type, name, campaignId, parentId, positionInParent, additionalInformation, openView) {
    return __async(this, null, function* () {
      let folder = "";
      let settings = 0 /* Agnostic */;
      const campaigns = this.api.database.read((campaign) => campaign.index.type === 1 /* Campaign */ && campaign.index.id === campaignId);
      if (campaigns.length === 1) {
        settings = campaigns[0].campaignSettings;
        folder = campaigns[0].folder;
      }
      const template = yield this.api.templates.get(settings, type, "internal" + ComponentType[type], name, campaignId, parentId, positionInParent, additionalInformation);
      const fileName = yield this._generateFilePath(type, folder, name, "/");
      const data = yield template.generateData();
      const newFile = yield app.vault.create(fileName, data);
      if (openView) {
        const leaf = app.workspace.getLeaf(true);
        yield leaf.openFile(newFile);
      }
      return newFile;
    });
  }
  _generateFilePath(type, folder, name, pathSeparator) {
    return __async(this, null, function* () {
      if (folder.startsWith(pathSeparator))
        folder = folder.substring(pathSeparator.length);
      if (folder.endsWith(pathSeparator))
        folder = folder.substring(0, folder.length - pathSeparator.length);
      let response = name + ".md";
      if (this.api.settings.automaticMove) {
        let fullPath;
        if (type !== 1 /* Campaign */) {
          fullPath = folder + pathSeparator + ComponentType[type] + "s";
          if (fullPath.startsWith(pathSeparator))
            fullPath = fullPath.substring(pathSeparator.length);
          const fileOrFolder = yield this.api.app.vault.getAbstractFileByPath(fullPath);
          if (fileOrFolder == null) {
            try {
              yield this.api.app.vault.createFolder(fullPath);
            } catch (e) {
            }
          }
        } else {
          fullPath = folder;
          if (fullPath.startsWith(pathSeparator))
            fullPath = fullPath.substring(1);
        }
        response = fullPath + pathSeparator + response;
      }
      return response;
    });
  }
};

// src/services/breadcrumbService/factories/BreadcrumbFactory.ts
var BreadcrumbFactory = class {
  constructor(_api) {
    this._api = _api;
    this.sceneCreator = function(scene, fileFactory) {
      var _a, _b;
      const scenePosition = ((_a = scene.index.positionInParent) != null ? _a : 0) + 1;
      fileFactory.silentCreate(8 /* Scene */, "a" + (((_b = scene.act.index.parentPosition) != null ? _b : 0) < 10 ? "0" + scene.act.index.parentPosition.toString() : scene.act.index.parentPosition.toString()) + "s" + (scenePosition < 10 ? "0" + scenePosition.toString() : scenePosition.toString()), scene.campaign.index.campaignId, scene.act.index.id, scenePosition, void 0, true);
    };
  }
  create(model) {
    const response = this._generateElementBreadcrumb(null, 1 /* Campaign */, model.campaign);
    if (model.index.type !== 1 /* Campaign */) {
      response.mainTitle = ComponentType[model.index.type];
      switch (model.index.type) {
        case 2 /* Adventure */:
          this._generateAventureBreadcrumb(response, model);
          break;
        case 16 /* Session */:
          this._generateSessionBreadcrumb(response, model);
          break;
        case 4 /* Act */:
          this._generateActBreadcrumb(response, model);
          break;
        case 8 /* Scene */:
          this._generateSceneBreadcrumb(response, model);
          break;
        default:
          this._generateElementBreadcrumb(response, model.index.type, model);
          break;
      }
    }
    response.model = model;
    return response;
  }
  _generateElementBreadcrumb(parent, type, data, linkText = null, isNewLine = false) {
    const response = new BreadcrumbElement(data);
    response.link = data.link;
    response.title = ComponentType[type];
    if (linkText != null)
      response.linkText = linkText;
    if (isNewLine)
      response.isInNewLine = isNewLine;
    if (parent != null)
      parent.nextBreadcrumb = response;
    return response;
  }
  _generateAventureBreadcrumb(parent, adventure) {
    const adventureBreadcrumb = this._generateElementBreadcrumb(parent, 2 /* Adventure */, adventure);
    let previousAdventure;
    let nextAdventure;
    try {
      previousAdventure = this._api.database.readNeighbour(2 /* Adventure */, adventure.index, true);
    } catch (e) {
    }
    try {
      nextAdventure = this._api.database.readNeighbour(2 /* Adventure */, adventure.index, false);
    } catch (e) {
    }
    let previousBreadcrumb = void 0;
    let nextBreadcrumb = void 0;
    if (previousAdventure !== void 0) {
      previousBreadcrumb = this._generateElementBreadcrumb(adventureBreadcrumb, 2 /* Adventure */, previousAdventure, "<< prev adventure", true);
    }
    if (nextAdventure !== void 0) {
      nextBreadcrumb = this._generateElementBreadcrumb(previousBreadcrumb != null ? previousBreadcrumb : adventureBreadcrumb, 2 /* Adventure */, nextAdventure, "next adventure >>", previousAdventure === void 0);
    }
    if (nextBreadcrumb !== void 0) {
      return nextBreadcrumb;
    } else {
      if (previousBreadcrumb !== void 0)
        return previousBreadcrumb;
      return adventureBreadcrumb;
    }
  }
  _generateSessionBreadcrumb(parent, session) {
    const sessionBreadcrumb = this._generateElementBreadcrumb(parent, 16 /* Session */, session);
    let previousSession;
    let nextSession;
    try {
      previousSession = this._api.database.readNeighbour(16 /* Session */, session.index, true);
    } catch (e) {
    }
    try {
      nextSession = this._api.database.readNeighbour(16 /* Session */, session.index, false);
    } catch (e) {
    }
    let previousBreadcrumb = void 0;
    let nextBreadcrumb = void 0;
    if (previousSession !== void 0) {
      previousBreadcrumb = this._generateElementBreadcrumb(sessionBreadcrumb, 16 /* Session */, previousSession, "<< prev session", true);
    }
    if (nextSession !== void 0) {
      nextBreadcrumb = this._generateElementBreadcrumb(previousBreadcrumb != null ? previousBreadcrumb : sessionBreadcrumb, 16 /* Session */, nextSession, "next session >>", previousSession === void 0);
    }
    if (nextBreadcrumb !== void 0) {
      return nextBreadcrumb;
    } else {
      if (previousBreadcrumb !== void 0)
        return previousBreadcrumb;
      return sessionBreadcrumb;
    }
  }
  _generateActBreadcrumb(parent, act) {
    const adventureBreadcrumb = this._generateElementBreadcrumb(parent, 2 /* Adventure */, act.adventure);
    const actBreadcrumb = this._generateElementBreadcrumb(adventureBreadcrumb, 4 /* Act */, act);
    let previousBreadcrumb = null;
    if (act.previousAct != null)
      previousBreadcrumb = this._generateElementBreadcrumb(actBreadcrumb, 4 /* Act */, act.previousAct, "<< prev act", true);
    let nextBreadcrumb = null;
    if (act.nextAct != null)
      nextBreadcrumb = this._generateElementBreadcrumb(previousBreadcrumb != null ? previousBreadcrumb : actBreadcrumb, 4 /* Act */, act.nextAct, "next act >>", previousBreadcrumb == null);
    return nextBreadcrumb != null ? nextBreadcrumb : previousBreadcrumb != null ? previousBreadcrumb : actBreadcrumb;
  }
  _generateSceneBreadcrumb(parent, scene) {
    const adventureBreadcrumb = this._generateElementBreadcrumb(parent, 2 /* Adventure */, scene.adventure);
    const actBreadcrumb = this._generateElementBreadcrumb(adventureBreadcrumb, 4 /* Act */, scene.act);
    const sceneBreadcrumb = this._generateElementBreadcrumb(actBreadcrumb, 8 /* Scene */, scene);
    let previousBreadcrumb = null;
    if (scene.previousScene != null)
      previousBreadcrumb = this._generateElementBreadcrumb(sceneBreadcrumb, 8 /* Scene */, scene.previousScene, "<< prev scene", true);
    let nextBreadcrumb = null;
    if (scene.nextScene != null) {
      nextBreadcrumb = this._generateElementBreadcrumb(previousBreadcrumb != null ? previousBreadcrumb : sceneBreadcrumb, 8 /* Scene */, scene.nextScene, "next scene >>", previousBreadcrumb == null);
    } else {
      const newSceneBreadcrumb = new BreadcrumbElement(scene);
      newSceneBreadcrumb.link = "";
      newSceneBreadcrumb.linkText = "+ add scene >>";
      newSceneBreadcrumb.functionParameters = [scene, this._api.service(FileCreationService)];
      newSceneBreadcrumb.function = this.sceneCreator;
      if (previousBreadcrumb == null) {
        newSceneBreadcrumb.isInNewLine = true;
        sceneBreadcrumb.nextBreadcrumb = newSceneBreadcrumb;
      } else {
        previousBreadcrumb.nextBreadcrumb = newSceneBreadcrumb;
      }
    }
    return nextBreadcrumb != null ? nextBreadcrumb : previousBreadcrumb != null ? previousBreadcrumb : sceneBreadcrumb;
  }
};

// src/services/breadcrumbService/views/BreadcrumbView.ts
var import_obsidian16 = require("obsidian");
var BreadcrumbView = class {
  render(container, data) {
    if (data.model === void 0)
      return;
    this._model = data.model;
    const breadcrumbLine = container.createDiv({ cls: "line" });
    this._renderBreadcrumb(container, breadcrumbLine, data);
  }
  _renderBreadcrumb(breadcrumb, line, data, isFirstLine = true) {
    let lineToUse = line;
    if (data.isInNewLine) {
      lineToUse = breadcrumb.createDiv({ cls: "line clearfix" });
      isFirstLine = false;
    }
    const crumb = lineToUse.createDiv({ cls: "crumb" });
    crumb.createDiv({ cls: "title", text: data.title ? data.title : " " });
    const value = crumb.createDiv({ cls: "value" });
    if (data.function != null) {
      const functionLink = value.createEl("a");
      functionLink.textContent = data.linkText;
      functionLink.addEventListener("click", () => {
        if (data.functionParameters != null) {
          data.function(...data.functionParameters);
        } else {
          data.function();
        }
      });
    } else {
      let link = data.link;
      if (data.linkText != null) {
        if (link.indexOf("|") !== -1) {
          link = link.substring(0, link.indexOf("|") + 1) + data.linkText + "]]";
        } else {
          link = link.substring(0, link.indexOf("]]")) + "|" + data.linkText + "]]";
        }
      }
      import_obsidian16.MarkdownRenderer.renderMarkdown(link, value, "", null);
    }
    if (data.nextBreadcrumb != null) {
      if (data.nextBreadcrumb.isInNewLine === false) {
        const separator = lineToUse.createDiv({ cls: "separator" });
        separator.createDiv({ cls: "title", text: " " });
        const separatorText = separator.createDiv({ cls: "value" });
        separatorText.createEl("p").textContent = isFirstLine ? ">" : "|";
      }
      this._renderBreadcrumb(breadcrumb, lineToUse, data.nextBreadcrumb, isFirstLine);
    }
  }
};

// src/services/breadcrumbService/BreadcrumbService.ts
var BreadcrumbService = class extends AbstractService {
  constructor(api) {
    super(api);
    this._factory = new BreadcrumbFactory(this.api);
  }
  render(model, containerEl) {
    const view = new BreadcrumbView();
    view.render(containerEl, this._factory.create(model));
  }
};

// src/services/relationshipsService/modals/RelationshipsSelectionModal.ts
var import_obsidian17 = require("obsidian");

// src/services/sorterService/SorterComparisonElement.ts
var SorterComparisonElement = class {
  constructor(comparisonElement, sortType = 0 /* Ascending */) {
    this.comparisonElement = comparisonElement;
    this.sortType = sortType;
  }
  sortFunction(leftData, rightData) {
    if (this.comparisonElement(leftData) > this.comparisonElement(rightData))
      return this.sortType === 0 /* Ascending */ ? 1 : -1;
    if (this.comparisonElement(leftData) < this.comparisonElement(rightData))
      return this.sortType === 0 /* Ascending */ ? -1 : 1;
    return 0;
  }
};

// src/services/sorterService/Sorter.ts
var Sorter = class {
  constructor(comparisonElements) {
    if (comparisonElements !== void 0) {
      this.comparisonElements = comparisonElements;
    } else {
      this.comparisonElements = [];
    }
  }
  getSortingFunction(leftData, rightData) {
    for (let index = 0; index < this.comparisonElements.length; index++) {
      const comparer = this.comparisonElements[index];
      if (typeof comparer.comparisonElement === "function") {
        const comparisonResult = comparer.sortFunction(leftData, rightData);
        if (comparisonResult !== 0)
          return comparisonResult;
      } else {
        if (this.getObjectValue(leftData, comparer.comparisonElement) > this.getObjectValue(rightData, comparer.comparisonElement))
          return comparer.sortType === 0 /* Ascending */ ? 1 : -1;
        if (this.getObjectValue(leftData, comparer.comparisonElement) < this.getObjectValue(rightData, comparer.comparisonElement))
          return comparer.sortType === 0 /* Ascending */ ? -1 : 1;
      }
    }
    return 0;
  }
  getObjectValue(object, value) {
    let response = object;
    const litteralValue = value.toString();
    const valueElements = litteralValue.split(".");
    valueElements.shift();
    while (valueElements.length > 0) {
      const id = valueElements.shift();
      const idKey = id;
      response = response[idKey];
    }
    return response;
  }
};

// src/services/sorterService/SorterService.ts
var SorterService = class extends AbstractService {
  create(comparisonElements) {
    const sorter = new Sorter(comparisonElements);
    return sorter.getSortingFunction.bind(sorter);
  }
};

// src/services/relationshipsService/modals/RelationshipsSelectionModal.ts
var RelationshipsSelectionModal = class extends AbstractModal {
  constructor(api, _currentComponent) {
    super(api);
    this._currentComponent = _currentComponent;
    this._selectedType = void 0;
    this.maxWidth = true;
    this.title = "Relationship Selector";
    this._availableRelationships = /* @__PURE__ */ new Map([
      [1 /* Campaign */, []],
      [2 /* Adventure */, [64 /* NonPlayerCharacter */, 1024 /* Faction */, 128 /* Location */, 512 /* Clue */, 256 /* Event */, 32 /* Character */]],
      [4 /* Act */, [64 /* NonPlayerCharacter */, 1024 /* Faction */, 128 /* Location */, 512 /* Clue */, 256 /* Event */, 32 /* Character */]],
      [8 /* Scene */, [64 /* NonPlayerCharacter */, 1024 /* Faction */, 128 /* Location */, 512 /* Clue */, 256 /* Event */, 32 /* Character */]],
      [16 /* Session */, []],
      [4096 /* Subplot */, [64 /* NonPlayerCharacter */, 1024 /* Faction */, 128 /* Location */, 512 /* Clue */, 256 /* Event */, 4096 /* Subplot */]],
      [32 /* Character */, [64 /* NonPlayerCharacter */, 32 /* Character */, 1024 /* Faction */, 128 /* Location */, 512 /* Clue */]],
      [64 /* NonPlayerCharacter */, [64 /* NonPlayerCharacter */, 32 /* Character */, 1024 /* Faction */, 128 /* Location */, 512 /* Clue */, 256 /* Event */, 4096 /* Subplot */]],
      [512 /* Clue */, [512 /* Clue */, 256 /* Event */, 128 /* Location */, 1024 /* Faction */, 64 /* NonPlayerCharacter */, 4096 /* Subplot */]],
      [256 /* Event */, [256 /* Event */, 512 /* Clue */, 128 /* Location */, 1024 /* Faction */, 64 /* NonPlayerCharacter */, 4096 /* Subplot */]],
      [1024 /* Faction */, [1024 /* Faction */, 128 /* Location */, 256 /* Event */, 512 /* Clue */, 4096 /* Subplot */]],
      [128 /* Location */, [128 /* Location */, 1024 /* Faction */, 32 /* Character */, 64 /* NonPlayerCharacter */, 512 /* Clue */, 256 /* Event */]],
      [2048 /* Music */, [2048 /* Music */]]
    ]);
    this._relationshipTypeAllowedChildren = /* @__PURE__ */ new Map([
      [512 /* Clue */, true],
      [256 /* Event */, true],
      [1024 /* Faction */, true],
      [128 /* Location */, true],
      [2048 /* Music */, true]
    ]);
  }
  onOpen() {
    super.onOpen();
    this.rpgmContainerEl.addClass("rpg-manager-modal-relationships");
    this._navigationEl = this.rpgmContainerEl.createDiv({ cls: "rpg-manager-modal-relationships-navigation" });
    this._addNavigation();
    const searchEl = this.rpgmContainerEl.createDiv({ cls: "rpg-manager-modal-relationships-navigation" });
    this._componentSearcher(searchEl);
    const relationshipsModalEl = this.rpgmContainerEl.createDiv({ cls: "rpg-manager-modal-relationships-container clearfix" });
    this._relationshipsEl = relationshipsModalEl.createDiv({ cls: "relationships", text: "" });
    this._addElementsToList();
  }
  _addNavigation() {
    const availableRelationships = this._availableRelationships.get(this._currentComponent.index.type);
    this._addLinkWithFunction(this._navigationEl, "Existing", () => {
      this._relationshipsEl.empty();
      this._selectedType = void 0;
      this._addElementsToList();
    });
    if (availableRelationships !== void 0 && availableRelationships.length > 0) {
      availableRelationships.forEach((type) => {
        this._addSeparator(this._navigationEl);
        this._addLinkWithFunction(this._navigationEl, ComponentType[type] + "s", () => {
          this._relationshipsEl.empty();
          this._selectedType = type;
          this._addElementsToList(type);
        });
      });
    }
  }
  _componentSearcher(contentEl) {
    const componentSearchContainerEl = contentEl.createDiv({ cls: "relationship-select" });
    componentSearchContainerEl.createDiv().createEl("label", { text: "Search" });
    const searchTermEl = componentSearchContainerEl.createEl("input", { type: "text" });
    searchTermEl.addEventListener("keyup", () => {
      this._relationshipsEl.empty();
      this._addElementsToList(this._selectedType, searchTermEl.value);
    });
  }
  _addElementsToList(type, searchTerm) {
    const relationshipsTableEl = this._relationshipsEl.createEl("table").createTBody();
    const components = this.search(type, searchTerm);
    components.forEach((component) => {
      var _a, _b;
      if (component.index !== this._currentComponent.index) {
        const relationships = this._currentComponent.getRelationships().filter((relationship2) => {
          var _a2;
          return ((_a2 = relationship2.component) == null ? void 0 : _a2.file.basename) === component.file.basename;
        });
        const relationship = (_a = relationships[0]) != null ? _a : void 0;
        const rowEl = relationshipsTableEl.insertRow();
        const checkboxEl = rowEl.insertCell().createEl("input");
        checkboxEl.type = "checkbox";
        checkboxEl.value = component.file.path;
        checkboxEl.id = component.file.basename;
        if (relationship !== void 0) {
          checkboxEl.checked = true;
          if (relationship.isInContent || relationship.type === 8 /* Parent */ || relationship.isAlsoInContent)
            checkboxEl.disabled = true;
        }
        if (relationship !== void 0)
          checkboxEl.checked = true;
        const imageCellEl = rowEl.insertCell();
        if (component.images.length > 0) {
          const img = new Image(40, 40);
          img.onload = (evt) => {
            img.style.objectFit = "cover";
            imageCellEl.append(img);
          };
          img.src = component.images[0].src;
        }
        const relationshipTypeSelectorEl = this._addRelationshipTypeSelector(component, relationship, rowEl.insertCell(), checkboxEl);
        const titleCell = rowEl.insertCell();
        titleCell.addClass("label");
        const checkboxLabel = titleCell.createEl("label", { text: component.file.basename });
        checkboxLabel.htmlFor = component.file.basename;
        if (relationship !== void 0) {
          if (relationship.isInContent) {
            titleCell.createEl("br");
            titleCell.createSpan({ text: "relationship in the notes cannot be removed" });
          } else if (relationship.type === 8 /* Parent */) {
            titleCell.createEl("br");
            titleCell.createSpan({ text: "parent element can only be removed from the parent" });
          } else if (relationship.description != void 0 && relationship.description !== "") {
            titleCell.createEl("br");
            titleCell.createSpan({ text: "removing this relationship deletes its description" });
          }
        }
        const synopsisEl = rowEl.insertCell();
        synopsisEl.addClass("description");
        import_obsidian17.MarkdownRenderer.renderMarkdown(relationship !== void 0 && relationship.description != void 0 && relationship.description !== "" ? relationship.description : (_b = component.synopsis) != null ? _b : "", synopsisEl, "", null);
        checkboxEl.addEventListener("change", () => {
          this._addOrRemoveElementRelationship(checkboxEl, relationshipTypeSelectorEl, component, relationship);
        });
      }
    });
  }
  _addRelationshipTypeSelector(component, relationship, containerEl, checkboxEl) {
    containerEl.addClass("selector");
    const availableRelationshipsType = /* @__PURE__ */ new Map();
    if (this._currentComponent.index.type !== component.index.type)
      availableRelationshipsType.set(2 /* Bidirectional */, this.api.service(RelationshipService).getReadableRelationshipType(2 /* Bidirectional */));
    availableRelationshipsType.set(4 /* Unidirectional */, this.api.service(RelationshipService).getReadableRelationshipType(4 /* Unidirectional */));
    if (this._currentComponent.index.type === component.index.type && this._relationshipTypeAllowedChildren.has(component.index.type))
      availableRelationshipsType.set(16 /* Child */, this.api.service(RelationshipService).getReadableRelationshipType(16 /* Child */));
    const relationshipTypeSelectorEl = containerEl.createEl("select");
    if (availableRelationshipsType.size === 1) {
      const [singleValue] = availableRelationshipsType.values();
      relationshipTypeSelectorEl.createEl("option", {
        text: singleValue,
        value: singleValue
      }).selected = true;
    } else {
      let isFirst = true;
      availableRelationshipsType.forEach((relationshipTypeDescription, relationshipType) => {
        const currentOptionEl = relationshipTypeSelectorEl.createEl("option", {
          text: relationshipTypeDescription,
          value: relationshipTypeDescription
        });
        if (isFirst) {
          currentOptionEl.selected = true;
          isFirst = false;
        } else if (relationship !== void 0 && relationship.type === relationshipType)
          currentOptionEl.selected = true;
        if (relationship !== void 0 && relationship.type === 8 /* Parent */) {
          relationshipTypeSelectorEl.createEl("option", {
            text: "parent",
            value: "parent"
          }).selected = true;
        }
      });
    }
    if (relationship !== void 0 && relationship.type === 8 /* Parent */)
      relationshipTypeSelectorEl.disabled = true;
    relationshipTypeSelectorEl.addEventListener("change", () => {
      if (checkboxEl.checked === false)
        checkboxEl.checked = true;
      this._addOrRemoveElementRelationship(checkboxEl, relationshipTypeSelectorEl, component, relationship);
    });
    return relationshipTypeSelectorEl;
  }
  _addOrRemoveElementRelationship(checkboxEl, relationshipTypeSelectorEl, relatedComponent, existingRelationship) {
    if (checkboxEl.checked) {
      const relationshipType = relationshipTypeSelectorEl.value === "" ? 2 /* Bidirectional */ : this.api.service(RelationshipService).getTypeFromString(relationshipTypeSelectorEl.value);
      const newRelationship = this.api.service(RelationshipService).createRelationship(relationshipType, relatedComponent.file.path, existingRelationship == null ? void 0 : existingRelationship.description, relatedComponent, false, this._currentComponent.getRelationships());
      this.api.service(CodeblockService).addOrUpdateRelationship(newRelationship);
    } else {
      this.api.service(CodeblockService).removeRelationship(relatedComponent.file.path);
      if (existingRelationship !== void 0)
        this._currentComponent.getRelationships().remove(existingRelationship);
    }
  }
  onClose() {
    super.onClose();
  }
  search(type, term) {
    let components = [];
    if (type !== void 0) {
      components = this.api.database.readChildren(type, this._currentComponent.index.campaignId).sort(this.api.service(SorterService).create([
        new SorterComparisonElement((component) => this._currentComponent.getRelationships().existsAlready(component), 1 /* Descending */),
        new SorterComparisonElement((component) => component.file.stat.mtime, 1 /* Descending */)
      ]));
    } else {
      components = this.api.database.recordset.filter((component) => this._currentComponent.getRelationships().existsAlready(component)).sort(this.api.service(SorterService).create([
        new SorterComparisonElement((component) => component.file.stat.mtime, 1 /* Descending */)
      ]));
    }
    if (term === void 0)
      return components;
    const matches = /* @__PURE__ */ new Map();
    const query = (0, import_obsidian17.prepareQuery)(term);
    components.forEach((component) => {
      component.alias.forEach((alias) => {
        if (alias.toLowerCase().startsWith(term.toLowerCase()))
          matches.set(component.index, { component });
      });
      if (!matches.has(component.index)) {
        const fuzzySearchResult = (0, import_obsidian17.fuzzySearch)(query, component.file.basename + " " + component.synopsis);
        if (fuzzySearchResult != null && fuzzySearchResult.matches !== null)
          matches.set(component.index, { component, result: fuzzySearchResult });
      }
    });
    if (matches.size === 0)
      return [];
    const resultArray = [];
    matches.forEach((value) => {
      resultArray.push(value);
    });
    resultArray.sort((a, b) => {
      var _a, _b, _c, _d;
      if (a.result === void 0 && b.result !== void 0)
        return -1;
      if (a.result !== void 0 && b.result === void 0)
        return 1;
      if (a.result === void 0 && b.result === void 0)
        return 0;
      if (a.result !== void 0 && b.result !== void 0) {
        if (((_a = a.result) == null ? void 0 : _a.score) !== void 0 && ((_b = b.result) == null ? void 0 : _b.score) === void 0)
          return -1;
        if (((_c = a.result) == null ? void 0 : _c.score) === void 0 && ((_d = b.result) == null ? void 0 : _d.score) !== void 0)
          return 1;
        return b.result.score - a.result.score;
      }
      return 0;
    });
    const response = [];
    resultArray.forEach((value) => {
      response.push(value.component);
    });
    return response;
  }
  _addSeparator(containerEl) {
    containerEl.createSpan({ cls: "separator", text: " | " });
  }
  _addLinkWithFunction(containerEl, text, fn, isLast = false) {
    const containerSpanEl = containerEl.createSpan({ cls: "link" });
    if (isLast)
      containerSpanEl.addClass("clearfix");
    const anchorEl = containerSpanEl.createEl("a", { href: "#", text });
    anchorEl.addEventListener("click", fn.bind(this));
  }
};

// src/services/galleryService/enums/GalleryViewType.ts
var GalleryViewType = /* @__PURE__ */ ((GalleryViewType2) => {
  GalleryViewType2[GalleryViewType2["Carousel"] = 0] = "Carousel";
  GalleryViewType2[GalleryViewType2["ModalNavigation"] = 1] = "ModalNavigation";
  GalleryViewType2[GalleryViewType2["ModalList"] = 2] = "ModalList";
  GalleryViewType2[GalleryViewType2["ModalAddLocal"] = 3] = "ModalAddLocal";
  GalleryViewType2[GalleryViewType2["ModalEdit"] = 4] = "ModalEdit";
  GalleryViewType2[GalleryViewType2["ModalAddRemote"] = 5] = "ModalAddRemote";
  GalleryViewType2[GalleryViewType2["ModalUpload"] = 6] = "ModalUpload";
  return GalleryViewType2;
})(GalleryViewType || {});

// src/services/galleryService/modals/GalleryManagementModal.ts
var GalleryManagementModal = class extends AbstractModal {
  constructor(api, _model, _gallery) {
    super(api);
    this._model = _model;
    this._gallery = _gallery;
    this.title = "Gallery Manager";
  }
  onClose() {
    super.onClose();
    this.rpgmContainerEl.empty();
  }
  onOpen() {
    super.onOpen();
    this.modalEl.style.width = "var(--modal-max-width)";
    this._containerEl = this.rpgmContainerEl.createDiv({ cls: "gallery" });
    const view = this._gallery.createView(1 /* ModalNavigation */, this._model);
    view.render(this._containerEl);
  }
};

// src/services/galleryService/abstracts/AbstractGalleryModalView.ts
var AbstractGalleryModalView = class extends AbstractView {
  get model() {
    return this._model;
  }
  set model(model) {
    this._model = model;
  }
};

// src/services/galleryService/views/modals/GalleryNavigationModalView.ts
var GalleryNavigationModalView = class extends AbstractGalleryModalView {
  constructor(api, _gallery) {
    super(api);
    this._gallery = _gallery;
  }
  render(containerEl) {
    const navigationEl = containerEl.createDiv({ cls: "gallery-navigation" });
    this._operationsEl = containerEl.createDiv({ cls: "gallery-operations" });
    this.addLinkWithFunction(navigationEl, "Current Images", () => {
      this._loadView(2 /* ModalList */);
    });
    this.addSeparator(navigationEl);
    this.addLinkWithFunction(navigationEl, "Add Local Image", () => {
      this._loadView(3 /* ModalAddLocal */);
    });
    this.addSeparator(navigationEl);
    this.addLinkWithFunction(navigationEl, "Upload Image", () => {
      this._loadView(6 /* ModalUpload */);
    });
    this.addSeparator(navigationEl);
    this.addLinkWithFunction(navigationEl, "Add Online Image", () => {
      this._loadView(5 /* ModalAddRemote */);
    }, true);
    this._loadView(2 /* ModalList */);
  }
  _loadView(type) {
    this._operationsEl.empty();
    const view = this._gallery.createView(type, this.model);
    view.render(this._operationsEl);
  }
};

// src/services/galleryService/views/modals/GalleryListModalView.ts
var import_obsidian18 = require("obsidian");
var GalleryListModalView = class extends AbstractGalleryModalView {
  constructor(api, _gallery) {
    super(api);
    this._gallery = _gallery;
  }
  render(containerEl) {
    containerEl.empty();
    this._masonryEl = containerEl.createDiv({ cls: "gallery-operations-masonry" });
    this.model.images.forEach((image) => {
      const masonryItemEl = this._masonryEl.createDiv({ cls: "gallery-operations-masonry-item" });
      const imageContainerEl = masonryItemEl.createDiv({ cls: "gallery-operations-masonry-item-container" });
      const imageEl = new Image();
      imageEl.addClass("image");
      imageEl.src = image.src;
      imageContainerEl.append(imageEl);
      const imageCaptionEl = imageContainerEl.createDiv({ cls: "caption" });
      if (image.caption !== "") {
        import_obsidian18.MarkdownRenderer.renderMarkdown(image.caption, imageCaptionEl, "", null);
      }
      imageEl.addEventListener("click", () => {
        const view = this._gallery.createView(4 /* ModalEdit */, this.model);
        view.image = image;
        view.render(containerEl);
      });
    });
  }
};

// src/services/galleryService/views/modals/GalleryEditModalView.ts
var GalleryEditModalView = class extends AbstractGalleryModalView {
  constructor(api, _gallery) {
    super(api);
    this._gallery = _gallery;
  }
  set image(image) {
    this._image = image;
    this.model;
  }
  render(containerEl) {
    containerEl.empty();
    const editorDeletedContainerEl = containerEl.createDiv({ cls: "gallery-operations-edit-deleted" });
    editorDeletedContainerEl.createDiv({ text: "The image has been removed from " + this.model.file.basename });
    editorDeletedContainerEl.createDiv({ text: "Click to return to its gallery" });
    editorDeletedContainerEl.addEventListener("click", () => {
      const view = this._gallery.createView(2 /* ModalList */, this.model);
      view.render(containerEl);
    });
    const editorContainerEl = containerEl.createDiv({ cls: "gallery-operations-edit" });
    const editorImageContainerEl = editorContainerEl.createDiv({ cls: "gallery-operations-edit-image" });
    const editorEditorContainerEl = editorContainerEl.createDiv({ cls: "gallery-operations-edit-editor clearfix" });
    this._imageEl = new Image();
    this._imageEl.addClass("image");
    this._imageEl.src = this._image.src;
    editorImageContainerEl.append(this._imageEl);
    editorEditorContainerEl.createEl("h3", { text: "Edit Image" });
    editorEditorContainerEl.createEl("label", { text: "Caption" });
    this._captionEl = editorEditorContainerEl.createEl("textarea", { text: this._image.caption });
    editorEditorContainerEl.createEl("button", { text: "Save Caption" }).addEventListener("click", () => {
      this.api.service(CodeblockService).addOrUpdateImage(this._image.path, this._captionEl.value);
    });
    editorEditorContainerEl.createEl("button", { cls: "danger", text: "Remove Image from " + this.model.file.basename }).addEventListener("click", () => {
      this.api.service(CodeblockService).removeImage(this._image.path).then(() => {
        editorDeletedContainerEl.style.display = "block";
      });
    });
  }
};

// src/services/galleryService/views/modals/abstracts/AbstractConfirmationGalleryModalView.ts
var AbstractConfirmationGalleryModalView = class extends AbstractGalleryModalView {
  constructor(api, gallery) {
    super(api);
    this.gallery = gallery;
  }
  render(containerEl) {
    this.containerEl = containerEl;
    this.containerEl.empty();
    this.confirmationOverlayEl = this.containerEl.createDiv({ cls: "gallery-operations-edit-deleted" });
    this.confirmationOverlayEl.createDiv({ text: "The image has been added to " + this.model.file.basename });
    this.confirmationOverlayEl.createDiv({ text: "Click to edit its caption" });
    this.confirmationOverlayEl.addEventListener("click", () => {
      if (this.selectedImage !== void 0) {
        const view = this.gallery.createView(4 /* ModalEdit */, this.model);
        view.image = this.selectedImage;
        view.render(this.containerEl);
      } else {
        const view = this.gallery.createView(2 /* ModalList */, this.model);
        view.render(containerEl);
      }
    });
  }
};

// src/services/galleryService/views/modals/GalleryAddLocalModalView.ts
var GalleryAddLocalModalView = class extends AbstractConfirmationGalleryModalView {
  constructor(api, gallery) {
    super(api, gallery);
  }
  render(containerEl) {
    super.render(containerEl);
    this.containerEl.createEl("label", { text: "Search your image" });
    const searchEl = this.containerEl.createEl("input", { type: "text" });
    searchEl.addEventListener("keyup", () => {
      this._populateGrid(searchEl.value);
    });
    this._masonryEl = this.containerEl.createDiv({ cls: "gallery-operations-masonry-x" });
    this._attachmentFolder = this.api.settings.imagesFolder !== void 0 && this.api.settings.imagesFolder !== "" ? this.api.settings.imagesFolder : this.api.app.vault.config.attachmentFolderPath;
    if (this._attachmentFolder === void 0)
      return;
    this._attachmentFolder = this._attachmentFolder.toLowerCase();
    const existingImages = [];
    this.model.images.forEach((image) => {
      existingImages.push(image.path);
    });
    this._allImages = this.api.app.vault.getFiles().filter((file) => file.path.toLowerCase().startsWith(this._attachmentFolder) && !existingImages.contains(file.path));
    this._populateGrid();
  }
  _populateGrid(searchedText) {
    this._masonryEl.empty();
    let images = this._allImages;
    if (searchedText !== void 0)
      images = this._allImages.filter((image) => image.path.toLowerCase().indexOf(searchedText.toLowerCase()) !== -1);
    images.forEach((image) => {
      const imageEl = new Image();
      imageEl.addClass("image");
      imageEl.src = this.api.root + image.path;
      imageEl.dataset.id = image.path;
      imageEl.addEventListener("click", () => {
        if (imageEl.dataset.id !== void 0) {
          this.api.service(CodeblockService).addOrUpdateImage(imageEl.dataset.id, "").then((image2) => {
            if (image2 !== void 0) {
              this.selectedImage = image2;
              this.confirmationOverlayEl.style.display = "block";
            }
          });
        }
      });
      this._masonryEl.append(imageEl);
    });
  }
};

// src/services/galleryService/views/modals/GalleryAddRemoteModalView.ts
var GalleryAddRemoteModalView = class extends AbstractConfirmationGalleryModalView {
  constructor(api, gallery) {
    super(api, gallery);
  }
  render(containerEl) {
    super.render(containerEl);
    this.containerEl.createEl("label", { text: "Add the URL of the online image" });
    this._urlEl = this.containerEl.createEl("input", { type: "text" });
    this._addButtonEl = this.containerEl.createEl("button", { text: "Add image" });
    this._addButtonEl.disabled = true;
    this._errorEl = this.containerEl.createDiv({ cls: "error" });
    this._imageContainerEl = this.containerEl.createDiv({ cls: "image-container" });
    this._urlEl.addEventListener("paste", this._showPreview.bind(this));
    this._urlEl.addEventListener("keyup", this._showPreview.bind(this));
    this._addButtonEl.addEventListener("click", () => {
      const imageEl = new Image();
      for (let index = 0; index < this.model.images.length; index++) {
        if (this._urlEl.value === this.model.images[index].src) {
          this._errorEl.style.display = "";
          this._errorEl.textContent = "The URL to the image is invalid.";
          return;
        }
      }
      imageEl.onerror = (evt) => {
        this._errorEl.style.display = "";
        this._errorEl.textContent = "The URL to the image is invalid.";
        return;
      };
      imageEl.onload = (evt) => {
        this.api.service(CodeblockService).addOrUpdateImage(this._urlEl.value, "").then((image) => {
          if (image !== void 0) {
            this.selectedImage = image;
            this.confirmationOverlayEl.style.display = "block";
          }
        });
      };
      imageEl.src = this._urlEl.value;
    });
  }
  _showPreview() {
    const imageEl = new Image();
    imageEl.onerror = (evt) => {
      this._errorEl.style.display = "";
      this._addButtonEl.disabled = true;
      return;
    };
    imageEl.onload = (evt) => {
      this._imageContainerEl.empty();
      this._imageContainerEl.append(imageEl);
      this._addButtonEl.disabled = false;
    };
    imageEl.src = this._urlEl.value;
  }
};

// src/services/galleryService/views/modals/GalleryUploadModalView.ts
var import_obsidian19 = require("obsidian");
var fs = require("fs");
var GalleryUploadModalView = class extends AbstractConfirmationGalleryModalView {
  constructor(api, gallery) {
    super(api, gallery);
  }
  render(containerEl) {
    super.render(containerEl);
    this._dropZoneEl = this.containerEl.createDiv({ cls: "dropzone" });
    this._dropZoneEl.createDiv();
    (0, import_obsidian19.setIcon)(this._dropZoneEl, "download");
    this._dropZoneEl.createDiv({ text: "Drag and drop your image here to add it to your Vault" });
    if (this._isAdvancedUpload()) {
      this._dropZoneEl.ondrag = (e) => {
        this._onDrag(e);
      };
      this._dropZoneEl.ondragstart = (e) => {
        this._onDrag(e);
      };
      this._dropZoneEl.ondragend = (e) => {
        this._onDrag(e);
      };
      this._dropZoneEl.ondragover = (e) => {
        this._onDrag(e);
      };
      this._dropZoneEl.ondragenter = (e) => {
        this._onDrag(e);
      };
      this._dropZoneEl.ondragleave = (e) => {
        this._onDrag(e);
      };
      this._dropZoneEl.ondrop = (e) => {
        this._onDrag(e);
        if (e.dataTransfer != null) {
          for (let index = 0; index < e.dataTransfer.files.length; index++) {
            const file = e.dataTransfer.files[index];
            const folder = this.api.settings.imagesFolder !== void 0 && this.api.settings.imagesFolder !== "" ? this.api.settings.imagesFolder : this.api.app.vault.config.attachmentFolderPath;
            let fileName = file.name;
            let fileIndex = 0;
            while (this.api.app.vault.getAbstractFileByPath(folder + "/" + fileName) != void 0) {
              const indexOfExtension = fileName.lastIndexOf(".");
              const name = fileName.substring(0, indexOfExtension);
              const extension = fileName.substring(indexOfExtension);
              fileIndex++;
              fileName = name + "_" + fileIndex.toString() + extension;
            }
            const path2 = this.api.app.vault.adapter.basePath + "/" + folder + "/" + fileName;
            const originalFilePath = file["path"];
            fs.copyFile(originalFilePath, path2, (err) => {
              if (err)
                throw err;
              this.api.service(CodeblockService).addOrUpdateImage(folder + "/" + fileName, "").then((image) => {
                if (image !== void 0) {
                  this.selectedImage = image;
                  this.confirmationOverlayEl.style.display = "block";
                }
              });
            });
          }
        }
      };
    }
  }
  _onDrag(e) {
    e.preventDefault();
    e.stopPropagation();
  }
  _isAdvancedUpload() {
    return ("draggable" in this._dropZoneEl || "ondragstart" in this._dropZoneEl && "ondrop" in this._dropZoneEl) && "FormData" in window && "FileReader" in window;
  }
};

// src/services/galleryService/GalleryService.ts
var GalleryService = class extends AbstractService {
  constructor() {
    super(...arguments);
    this._imageExtensions = ["jpeg", "jpg", "png", "webp"];
    this.views = /* @__PURE__ */ new Map([
      [1 /* ModalNavigation */, GalleryNavigationModalView],
      [2 /* ModalList */, GalleryListModalView],
      [4 /* ModalEdit */, GalleryEditModalView],
      [3 /* ModalAddLocal */, GalleryAddLocalModalView],
      [5 /* ModalAddRemote */, GalleryAddRemoteModalView],
      [6 /* ModalUpload */, GalleryUploadModalView]
    ]);
  }
  get imageExtensions() {
    return this._imageExtensions;
  }
  createView(type, model) {
    const view = this.views.get(type);
    if (view === void 0) {
      this.api.service(LoggerService).createError(1 /* System */, "The requested gallery view (" + GalleryViewType[type] + ") does not exist");
      throw new Error("The requested gallery view (" + GalleryViewType[type] + ") does not exist");
    }
    const response = new view(this.api, this);
    response.model = model;
    return response;
  }
};

// src/services/plotsService/plots/PlotsAbtOnly.ts
var PlotsAbtOnly = class extends AbstractModel {
  get abt() {
    return new AbtPlot(this.metadata);
  }
};

// src/services/fantasyCalendarService/FantasyCalendarService.ts
var import_obsidian20 = require("obsidian");
var FantasyCalendarService = class extends AbstractService {
  constructor(api) {
    super(api);
    this._isReady = false;
    this._isDatabaseReady = false;
    this._fantasyCalendarUpdated = (0, import_obsidian20.debounce)(this._fantasyCalendarUpdated, 250, true);
    this.registerEvent(this.api.app.workspace.on("rpgmanager:database-ready", this._dbReady.bind(this)));
    this.registerEvent(this.api.app.workspace.on("fantasy-calendars-settings-loaded", this.ready.bind(this)));
    this.registerEvent(this.api.app.workspace.on("fantasy-calendars-updated", this._fantasyCalendarUpdated.bind(this)));
  }
  _fantasyCalendarUpdated() {
    if (this._events === void 0)
      return;
    const calendars = this.calendars;
    let anyUpdate = false;
    for (let index = 0; index < calendars.length; index++) {
      const calendar = calendars[index];
      let calendarMap = this._events.get(calendar.name);
      if (calendarMap === void 0)
        calendarMap = this._events.set(calendar.name, /* @__PURE__ */ new Map()).get(calendar.name);
      if (calendarMap === void 0)
        continue;
      for (let eventIndex = 0; eventIndex < calendars[index].events.length; eventIndex++) {
        const event = calendar.events[eventIndex];
        if (event.note == null || event.category == null)
          continue;
        const model = this.api.database.readByPath(event.note + ".md");
        if (model === void 0)
          continue;
        let modelMap = calendarMap.get(model);
        if (modelMap === void 0)
          modelMap = calendarMap.set(model, /* @__PURE__ */ new Map()).get(model);
        if (modelMap === void 0)
          continue;
        const modelDate = this._getModelDate(model, event.category);
        const fantasyCalendaDate = modelMap.get(event.category);
        if (modelDate === void 0 || modelDate.year !== (fantasyCalendaDate == null ? void 0 : fantasyCalendaDate.year) && modelDate.month !== (fantasyCalendaDate == null ? void 0 : fantasyCalendaDate.month) && modelDate.day !== (fantasyCalendaDate == null ? void 0 : fantasyCalendaDate.day)) {
          anyUpdate = true;
          model.touch(true);
        }
      }
    }
    if (anyUpdate)
      this.api.app.workspace.trigger("rpgmanager:refresh-views");
  }
  _getModelDate(model, category) {
    var _a, _b, _c, _d, _e, _f;
    switch (category) {
      case "current" /* CurrentDate */:
        return (_a = model.date) == null ? void 0 : _a.date;
        break;
      case "RPG Manager Event" /* Event */:
        return (_b = model.date) == null ? void 0 : _b.date;
        break;
      case "RPG Manager Birth" /* Birth */:
        return (_c = model.dob) == null ? void 0 : _c.date;
        break;
      case "RPG Manager Death" /* Death */:
        return (_d = model.death) == null ? void 0 : _d.date;
        break;
      case "RPG Manager Scene" /* Scene */:
        return (_e = model.date) == null ? void 0 : _e.date;
        break;
      case "RPG Manager Clue Found" /* ClueFound */:
        return (_f = model.found) == null ? void 0 : _f.date;
        break;
    }
    return void 0;
  }
  _dbReady() {
    this._isDatabaseReady = true;
    if (this._isReady)
      this._processInitialEvents();
  }
  ready() {
    this._isReady = true;
    if (this._isDatabaseReady)
      this._processInitialEvents();
  }
  _processInitialEvents() {
    this._events = /* @__PURE__ */ new Map();
    this.calendars.forEach((calendar) => {
      this._events.set(calendar.name, /* @__PURE__ */ new Map());
      const calendarMap = this._events.get(calendar.name);
      if (calendarMap !== void 0) {
        calendar.events.forEach((event) => {
          if (event.note != null && event.category != void 0) {
            const model = this.api.database.readByPath(event.note);
            if (model !== void 0) {
              let modelMap = calendarMap.get(model);
              if (modelMap === void 0)
                modelMap = calendarMap.set(model, /* @__PURE__ */ new Map()).get(model);
              if (modelMap !== void 0) {
                const eventDate = modelMap.get(event.category);
                if (eventDate === void 0)
                  modelMap.set(event.category, event.date);
              }
            }
          }
        });
      }
    });
  }
  get calendars() {
    return window.FantasyCalendarAPI.getCalendars();
  }
  addCategory(category, calendar) {
    return __async(this, null, function* () {
      let colour = "";
      switch (category) {
        case "RPG Manager Birth" /* Birth */:
          colour = "#00CC00";
          break;
        case "RPG Manager Clue Found" /* ClueFound */:
          colour = "#0066CC";
          break;
        case "RPG Manager Death" /* Death */:
          colour = "#CC0000";
          break;
        case "RPG Manager Event" /* Event */:
          colour = "#CC00CC";
          break;
        case "RPG Manager Scene" /* Scene */:
          colour = "#606060";
          break;
        default:
          colour = "";
          break;
      }
      const fantasyCalendarCategory = {
        name: category,
        id: "rpgm-" + category.toLowerCase(),
        color: colour
      };
      calendar.categories.push(fantasyCalendarCategory);
      this.api.app.plugins.getPlugin("fantasy-calendar").saveCalendar();
      return fantasyCalendarCategory;
    });
  }
  getDay(date, calendar) {
    return this.api.app.plugins.getPlugin("fantasy-calendar").api.getDay(date, calendar);
  }
};

// node_modules/luxon/src/errors.js
var LuxonError = class extends Error {
};
var InvalidDateTimeError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid DateTime: ${reason.toMessage()}`);
  }
};
var InvalidIntervalError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid Interval: ${reason.toMessage()}`);
  }
};
var InvalidDurationError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid Duration: ${reason.toMessage()}`);
  }
};
var ConflictingSpecificationError = class extends LuxonError {
};
var InvalidUnitError = class extends LuxonError {
  constructor(unit) {
    super(`Invalid unit ${unit}`);
  }
};
var InvalidArgumentError = class extends LuxonError {
};
var ZoneIsAbstractError = class extends LuxonError {
  constructor() {
    super("Zone is an abstract class");
  }
};

// node_modules/luxon/src/impl/formats.js
var n = "numeric";
var s = "short";
var l = "long";
var DATE_SHORT = {
  year: n,
  month: n,
  day: n
};
var DATE_MED = {
  year: n,
  month: s,
  day: n
};
var DATE_MED_WITH_WEEKDAY = {
  year: n,
  month: s,
  day: n,
  weekday: s
};
var DATE_FULL = {
  year: n,
  month: l,
  day: n
};
var DATE_HUGE = {
  year: n,
  month: l,
  day: n,
  weekday: l
};
var TIME_SIMPLE = {
  hour: n,
  minute: n
};
var TIME_WITH_SECONDS = {
  hour: n,
  minute: n,
  second: n
};
var TIME_WITH_SHORT_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  timeZoneName: s
};
var TIME_WITH_LONG_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  timeZoneName: l
};
var TIME_24_SIMPLE = {
  hour: n,
  minute: n,
  hourCycle: "h23"
};
var TIME_24_WITH_SECONDS = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23"
};
var TIME_24_WITH_SHORT_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23",
  timeZoneName: s
};
var TIME_24_WITH_LONG_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23",
  timeZoneName: l
};
var DATETIME_SHORT = {
  year: n,
  month: n,
  day: n,
  hour: n,
  minute: n
};
var DATETIME_SHORT_WITH_SECONDS = {
  year: n,
  month: n,
  day: n,
  hour: n,
  minute: n,
  second: n
};
var DATETIME_MED = {
  year: n,
  month: s,
  day: n,
  hour: n,
  minute: n
};
var DATETIME_MED_WITH_SECONDS = {
  year: n,
  month: s,
  day: n,
  hour: n,
  minute: n,
  second: n
};
var DATETIME_MED_WITH_WEEKDAY = {
  year: n,
  month: s,
  day: n,
  weekday: s,
  hour: n,
  minute: n
};
var DATETIME_FULL = {
  year: n,
  month: l,
  day: n,
  hour: n,
  minute: n,
  timeZoneName: s
};
var DATETIME_FULL_WITH_SECONDS = {
  year: n,
  month: l,
  day: n,
  hour: n,
  minute: n,
  second: n,
  timeZoneName: s
};
var DATETIME_HUGE = {
  year: n,
  month: l,
  day: n,
  weekday: l,
  hour: n,
  minute: n,
  timeZoneName: l
};
var DATETIME_HUGE_WITH_SECONDS = {
  year: n,
  month: l,
  day: n,
  weekday: l,
  hour: n,
  minute: n,
  second: n,
  timeZoneName: l
};

// node_modules/luxon/src/impl/util.js
function isUndefined(o) {
  return typeof o === "undefined";
}
function isNumber(o) {
  return typeof o === "number";
}
function isInteger(o) {
  return typeof o === "number" && o % 1 === 0;
}
function isString(o) {
  return typeof o === "string";
}
function isDate(o) {
  return Object.prototype.toString.call(o) === "[object Date]";
}
function hasRelative() {
  try {
    return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
  } catch (e) {
    return false;
  }
}
function maybeArray(thing) {
  return Array.isArray(thing) ? thing : [thing];
}
function bestBy(arr, by, compare) {
  if (arr.length === 0) {
    return void 0;
  }
  return arr.reduce((best, next) => {
    const pair = [by(next), next];
    if (!best) {
      return pair;
    } else if (compare(best[0], pair[0]) === best[0]) {
      return best;
    } else {
      return pair;
    }
  }, null)[1];
}
function pick(obj, keys) {
  return keys.reduce((a, k) => {
    a[k] = obj[k];
    return a;
  }, {});
}
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
function integerBetween(thing, bottom, top) {
  return isInteger(thing) && thing >= bottom && thing <= top;
}
function floorMod(x, n2) {
  return x - n2 * Math.floor(x / n2);
}
function padStart(input, n2 = 2) {
  const isNeg = input < 0;
  let padded;
  if (isNeg) {
    padded = "-" + ("" + -input).padStart(n2, "0");
  } else {
    padded = ("" + input).padStart(n2, "0");
  }
  return padded;
}
function parseInteger(string) {
  if (isUndefined(string) || string === null || string === "") {
    return void 0;
  } else {
    return parseInt(string, 10);
  }
}
function parseFloating(string) {
  if (isUndefined(string) || string === null || string === "") {
    return void 0;
  } else {
    return parseFloat(string);
  }
}
function parseMillis(fraction) {
  if (isUndefined(fraction) || fraction === null || fraction === "") {
    return void 0;
  } else {
    const f = parseFloat("0." + fraction) * 1e3;
    return Math.floor(f);
  }
}
function roundTo(number, digits, towardZero = false) {
  const factor = 10 ** digits, rounder = towardZero ? Math.trunc : Math.round;
  return rounder(number * factor) / factor;
}
function isLeapYear(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function daysInYear(year) {
  return isLeapYear(year) ? 366 : 365;
}
function daysInMonth(year, month) {
  const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12;
  if (modMonth === 2) {
    return isLeapYear(modYear) ? 29 : 28;
  } else {
    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
  }
}
function objToLocalTS(obj) {
  let d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond);
  if (obj.year < 100 && obj.year >= 0) {
    d = new Date(d);
    d.setUTCFullYear(d.getUTCFullYear() - 1900);
  }
  return +d;
}
function weeksInWeekYear(weekYear) {
  const p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7, last = weekYear - 1, p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;
  return p1 === 4 || p2 === 3 ? 53 : 52;
}
function untruncateYear(year) {
  if (year > 99) {
    return year;
  } else
    return year > 60 ? 1900 + year : 2e3 + year;
}
function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {
  const date = new Date(ts), intlOpts = {
    hourCycle: "h23",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit"
  };
  if (timeZone) {
    intlOpts.timeZone = timeZone;
  }
  const modified = __spreadValues({ timeZoneName: offsetFormat }, intlOpts);
  const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename");
  return parsed ? parsed.value : null;
}
function signedOffset(offHourStr, offMinuteStr) {
  let offHour = parseInt(offHourStr, 10);
  if (Number.isNaN(offHour)) {
    offHour = 0;
  }
  const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
  return offHour * 60 + offMinSigned;
}
function asNumber(value) {
  const numericValue = Number(value);
  if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue))
    throw new InvalidArgumentError(`Invalid unit value ${value}`);
  return numericValue;
}
function normalizeObject(obj, normalizer) {
  const normalized = {};
  for (const u in obj) {
    if (hasOwnProperty(obj, u)) {
      const v = obj[u];
      if (v === void 0 || v === null)
        continue;
      normalized[normalizer(u)] = asNumber(v);
    }
  }
  return normalized;
}
function formatOffset(offset2, format) {
  const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign = offset2 >= 0 ? "+" : "-";
  switch (format) {
    case "short":
      return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;
    case "narrow":
      return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`;
    case "techie":
      return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;
    default:
      throw new RangeError(`Value format ${format} is out of range for property format`);
  }
}
function timeObject(obj) {
  return pick(obj, ["hour", "minute", "second", "millisecond"]);
}
var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;

// node_modules/luxon/src/impl/english.js
var monthsLong = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];
var monthsShort = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec"
];
var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
function months(length) {
  switch (length) {
    case "narrow":
      return [...monthsNarrow];
    case "short":
      return [...monthsShort];
    case "long":
      return [...monthsLong];
    case "numeric":
      return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
    case "2-digit":
      return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
    default:
      return null;
  }
}
var weekdaysLong = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday"
];
var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
function weekdays(length) {
  switch (length) {
    case "narrow":
      return [...weekdaysNarrow];
    case "short":
      return [...weekdaysShort];
    case "long":
      return [...weekdaysLong];
    case "numeric":
      return ["1", "2", "3", "4", "5", "6", "7"];
    default:
      return null;
  }
}
var meridiems = ["AM", "PM"];
var erasLong = ["Before Christ", "Anno Domini"];
var erasShort = ["BC", "AD"];
var erasNarrow = ["B", "A"];
function eras(length) {
  switch (length) {
    case "narrow":
      return [...erasNarrow];
    case "short":
      return [...erasShort];
    case "long":
      return [...erasLong];
    default:
      return null;
  }
}
function meridiemForDateTime(dt) {
  return meridiems[dt.hour < 12 ? 0 : 1];
}
function weekdayForDateTime(dt, length) {
  return weekdays(length)[dt.weekday - 1];
}
function monthForDateTime(dt, length) {
  return months(length)[dt.month - 1];
}
function eraForDateTime(dt, length) {
  return eras(length)[dt.year < 0 ? 0 : 1];
}
function formatRelativeTime(unit, count, numeric = "always", narrow = false) {
  const units = {
    years: ["year", "yr."],
    quarters: ["quarter", "qtr."],
    months: ["month", "mo."],
    weeks: ["week", "wk."],
    days: ["day", "day", "days"],
    hours: ["hour", "hr."],
    minutes: ["minute", "min."],
    seconds: ["second", "sec."]
  };
  const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1;
  if (numeric === "auto" && lastable) {
    const isDay = unit === "days";
    switch (count) {
      case 1:
        return isDay ? "tomorrow" : `next ${units[unit][0]}`;
      case -1:
        return isDay ? "yesterday" : `last ${units[unit][0]}`;
      case 0:
        return isDay ? "today" : `this ${units[unit][0]}`;
      default:
    }
  }
  const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit;
  return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;
}

// node_modules/luxon/src/impl/formatter.js
function stringifyTokens(splits, tokenToString) {
  let s2 = "";
  for (const token of splits) {
    if (token.literal) {
      s2 += token.val;
    } else {
      s2 += tokenToString(token.val);
    }
  }
  return s2;
}
var macroTokenToFormatOpts = {
  D: DATE_SHORT,
  DD: DATE_MED,
  DDD: DATE_FULL,
  DDDD: DATE_HUGE,
  t: TIME_SIMPLE,
  tt: TIME_WITH_SECONDS,
  ttt: TIME_WITH_SHORT_OFFSET,
  tttt: TIME_WITH_LONG_OFFSET,
  T: TIME_24_SIMPLE,
  TT: TIME_24_WITH_SECONDS,
  TTT: TIME_24_WITH_SHORT_OFFSET,
  TTTT: TIME_24_WITH_LONG_OFFSET,
  f: DATETIME_SHORT,
  ff: DATETIME_MED,
  fff: DATETIME_FULL,
  ffff: DATETIME_HUGE,
  F: DATETIME_SHORT_WITH_SECONDS,
  FF: DATETIME_MED_WITH_SECONDS,
  FFF: DATETIME_FULL_WITH_SECONDS,
  FFFF: DATETIME_HUGE_WITH_SECONDS
};
var Formatter = class {
  static create(locale, opts = {}) {
    return new Formatter(locale, opts);
  }
  static parseFormat(fmt) {
    let current = null, currentFull = "", bracketed = false;
    const splits = [];
    for (let i = 0; i < fmt.length; i++) {
      const c = fmt.charAt(i);
      if (c === "'") {
        if (currentFull.length > 0) {
          splits.push({ literal: bracketed, val: currentFull });
        }
        current = null;
        currentFull = "";
        bracketed = !bracketed;
      } else if (bracketed) {
        currentFull += c;
      } else if (c === current) {
        currentFull += c;
      } else {
        if (currentFull.length > 0) {
          splits.push({ literal: false, val: currentFull });
        }
        currentFull = c;
        current = c;
      }
    }
    if (currentFull.length > 0) {
      splits.push({ literal: bracketed, val: currentFull });
    }
    return splits;
  }
  static macroTokenToFormatOpts(token) {
    return macroTokenToFormatOpts[token];
  }
  constructor(locale, formatOpts) {
    this.opts = formatOpts;
    this.loc = locale;
    this.systemLoc = null;
  }
  formatWithSystemDefault(dt, opts) {
    if (this.systemLoc === null) {
      this.systemLoc = this.loc.redefaultToSystem();
    }
    const df = this.systemLoc.dtFormatter(dt, __spreadValues(__spreadValues({}, this.opts), opts));
    return df.format();
  }
  formatDateTime(dt, opts = {}) {
    const df = this.loc.dtFormatter(dt, __spreadValues(__spreadValues({}, this.opts), opts));
    return df.format();
  }
  formatDateTimeParts(dt, opts = {}) {
    const df = this.loc.dtFormatter(dt, __spreadValues(__spreadValues({}, this.opts), opts));
    return df.formatToParts();
  }
  resolvedOptions(dt, opts = {}) {
    const df = this.loc.dtFormatter(dt, __spreadValues(__spreadValues({}, this.opts), opts));
    return df.resolvedOptions();
  }
  num(n2, p = 0) {
    if (this.opts.forceSimple) {
      return padStart(n2, p);
    }
    const opts = __spreadValues({}, this.opts);
    if (p > 0) {
      opts.padTo = p;
    }
    return this.loc.numberFormatter(opts).format(n2);
  }
  formatDateTimeFromString(dt, fmt) {
    const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => {
      if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
        return "Z";
      }
      return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
    }, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, "weekday"), maybeMacro = (token) => {
      const formatOpts = Formatter.macroTokenToFormatOpts(token);
      if (formatOpts) {
        return this.formatWithSystemDefault(dt, formatOpts);
      } else {
        return token;
      }
    }, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"), tokenToString = (token) => {
      switch (token) {
        case "S":
          return this.num(dt.millisecond);
        case "u":
        case "SSS":
          return this.num(dt.millisecond, 3);
        case "s":
          return this.num(dt.second);
        case "ss":
          return this.num(dt.second, 2);
        case "uu":
          return this.num(Math.floor(dt.millisecond / 10), 2);
        case "uuu":
          return this.num(Math.floor(dt.millisecond / 100));
        case "m":
          return this.num(dt.minute);
        case "mm":
          return this.num(dt.minute, 2);
        case "h":
          return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
        case "hh":
          return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
        case "H":
          return this.num(dt.hour);
        case "HH":
          return this.num(dt.hour, 2);
        case "Z":
          return formatOffset2({ format: "narrow", allowZ: this.opts.allowZ });
        case "ZZ":
          return formatOffset2({ format: "short", allowZ: this.opts.allowZ });
        case "ZZZ":
          return formatOffset2({ format: "techie", allowZ: this.opts.allowZ });
        case "ZZZZ":
          return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale });
        case "ZZZZZ":
          return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale });
        case "z":
          return dt.zoneName;
        case "a":
          return meridiem();
        case "d":
          return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day);
        case "dd":
          return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2);
        case "c":
          return this.num(dt.weekday);
        case "ccc":
          return weekday("short", true);
        case "cccc":
          return weekday("long", true);
        case "ccccc":
          return weekday("narrow", true);
        case "E":
          return this.num(dt.weekday);
        case "EEE":
          return weekday("short", false);
        case "EEEE":
          return weekday("long", false);
        case "EEEEE":
          return weekday("narrow", false);
        case "L":
          return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month);
        case "LL":
          return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2);
        case "LLL":
          return month("short", true);
        case "LLLL":
          return month("long", true);
        case "LLLLL":
          return month("narrow", true);
        case "M":
          return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt.month);
        case "MM":
          return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt.month, 2);
        case "MMM":
          return month("short", false);
        case "MMMM":
          return month("long", false);
        case "MMMMM":
          return month("narrow", false);
        case "y":
          return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year);
        case "yy":
          return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2);
        case "yyyy":
          return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 4);
        case "yyyyyy":
          return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 6);
        case "G":
          return era("short");
        case "GG":
          return era("long");
        case "GGGGG":
          return era("narrow");
        case "kk":
          return this.num(dt.weekYear.toString().slice(-2), 2);
        case "kkkk":
          return this.num(dt.weekYear, 4);
        case "W":
          return this.num(dt.weekNumber);
        case "WW":
          return this.num(dt.weekNumber, 2);
        case "o":
          return this.num(dt.ordinal);
        case "ooo":
          return this.num(dt.ordinal, 3);
        case "q":
          return this.num(dt.quarter);
        case "qq":
          return this.num(dt.quarter, 2);
        case "X":
          return this.num(Math.floor(dt.ts / 1e3));
        case "x":
          return this.num(dt.ts);
        default:
          return maybeMacro(token);
      }
    };
    return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);
  }
  formatDurationFromString(dur, fmt) {
    const tokenToField = (token) => {
      switch (token[0]) {
        case "S":
          return "millisecond";
        case "s":
          return "second";
        case "m":
          return "minute";
        case "h":
          return "hour";
        case "d":
          return "day";
        case "w":
          return "week";
        case "M":
          return "month";
        case "y":
          return "year";
        default:
          return null;
      }
    }, tokenToString = (lildur) => (token) => {
      const mapped = tokenToField(token);
      if (mapped) {
        return this.num(lildur.get(mapped), token.length);
      } else {
        return token;
      }
    }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce((found, { literal, val }) => literal ? found : found.concat(val), []), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));
    return stringifyTokens(tokens, tokenToString(collapsed));
  }
};

// node_modules/luxon/src/impl/invalid.js
var Invalid = class {
  constructor(reason, explanation) {
    this.reason = reason;
    this.explanation = explanation;
  }
  toMessage() {
    if (this.explanation) {
      return `${this.reason}: ${this.explanation}`;
    } else {
      return this.reason;
    }
  }
};

// node_modules/luxon/src/zone.js
var Zone = class {
  get type() {
    throw new ZoneIsAbstractError();
  }
  get name() {
    throw new ZoneIsAbstractError();
  }
  get ianaName() {
    return this.name;
  }
  get isUniversal() {
    throw new ZoneIsAbstractError();
  }
  offsetName(ts, opts) {
    throw new ZoneIsAbstractError();
  }
  formatOffset(ts, format) {
    throw new ZoneIsAbstractError();
  }
  offset(ts) {
    throw new ZoneIsAbstractError();
  }
  equals(otherZone) {
    throw new ZoneIsAbstractError();
  }
  get isValid() {
    throw new ZoneIsAbstractError();
  }
};

// node_modules/luxon/src/zones/systemZone.js
var singleton = null;
var SystemZone = class extends Zone {
  static get instance() {
    if (singleton === null) {
      singleton = new SystemZone();
    }
    return singleton;
  }
  get type() {
    return "system";
  }
  get name() {
    return new Intl.DateTimeFormat().resolvedOptions().timeZone;
  }
  get isUniversal() {
    return false;
  }
  offsetName(ts, { format, locale }) {
    return parseZoneInfo(ts, format, locale);
  }
  formatOffset(ts, format) {
    return formatOffset(this.offset(ts), format);
  }
  offset(ts) {
    return -new Date(ts).getTimezoneOffset();
  }
  equals(otherZone) {
    return otherZone.type === "system";
  }
  get isValid() {
    return true;
  }
};

// node_modules/luxon/src/zones/IANAZone.js
var dtfCache = {};
function makeDTF(zone) {
  if (!dtfCache[zone]) {
    dtfCache[zone] = new Intl.DateTimeFormat("en-US", {
      hour12: false,
      timeZone: zone,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      era: "short"
    });
  }
  return dtfCache[zone];
}
var typeToPos = {
  year: 0,
  month: 1,
  day: 2,
  era: 3,
  hour: 4,
  minute: 5,
  second: 6
};
function hackyOffset(dtf, date) {
  const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;
  return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];
}
function partsOffset(dtf, date) {
  const formatted = dtf.formatToParts(date);
  const filled = [];
  for (let i = 0; i < formatted.length; i++) {
    const { type, value } = formatted[i];
    const pos = typeToPos[type];
    if (type === "era") {
      filled[pos] = value;
    } else if (!isUndefined(pos)) {
      filled[pos] = parseInt(value, 10);
    }
  }
  return filled;
}
var ianaZoneCache = {};
var IANAZone = class extends Zone {
  static create(name) {
    if (!ianaZoneCache[name]) {
      ianaZoneCache[name] = new IANAZone(name);
    }
    return ianaZoneCache[name];
  }
  static resetCache() {
    ianaZoneCache = {};
    dtfCache = {};
  }
  static isValidSpecifier(s2) {
    return this.isValidZone(s2);
  }
  static isValidZone(zone) {
    if (!zone) {
      return false;
    }
    try {
      new Intl.DateTimeFormat("en-US", { timeZone: zone }).format();
      return true;
    } catch (e) {
      return false;
    }
  }
  constructor(name) {
    super();
    this.zoneName = name;
    this.valid = IANAZone.isValidZone(name);
  }
  get type() {
    return "iana";
  }
  get name() {
    return this.zoneName;
  }
  get isUniversal() {
    return false;
  }
  offsetName(ts, { format, locale }) {
    return parseZoneInfo(ts, format, locale, this.name);
  }
  formatOffset(ts, format) {
    return formatOffset(this.offset(ts), format);
  }
  offset(ts) {
    const date = new Date(ts);
    if (isNaN(date))
      return NaN;
    const dtf = makeDTF(this.name);
    let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date);
    if (adOrBc === "BC") {
      year = -Math.abs(year) + 1;
    }
    const adjustedHour = hour === 24 ? 0 : hour;
    const asUTC = objToLocalTS({
      year,
      month,
      day,
      hour: adjustedHour,
      minute,
      second,
      millisecond: 0
    });
    let asTS = +date;
    const over = asTS % 1e3;
    asTS -= over >= 0 ? over : 1e3 + over;
    return (asUTC - asTS) / (60 * 1e3);
  }
  equals(otherZone) {
    return otherZone.type === "iana" && otherZone.name === this.name;
  }
  get isValid() {
    return this.valid;
  }
};

// node_modules/luxon/src/zones/fixedOffsetZone.js
var singleton2 = null;
var FixedOffsetZone = class extends Zone {
  static get utcInstance() {
    if (singleton2 === null) {
      singleton2 = new FixedOffsetZone(0);
    }
    return singleton2;
  }
  static instance(offset2) {
    return offset2 === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset2);
  }
  static parseSpecifier(s2) {
    if (s2) {
      const r = s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
      if (r) {
        return new FixedOffsetZone(signedOffset(r[1], r[2]));
      }
    }
    return null;
  }
  constructor(offset2) {
    super();
    this.fixed = offset2;
  }
  get type() {
    return "fixed";
  }
  get name() {
    return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`;
  }
  get ianaName() {
    if (this.fixed === 0) {
      return "Etc/UTC";
    } else {
      return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`;
    }
  }
  offsetName() {
    return this.name;
  }
  formatOffset(ts, format) {
    return formatOffset(this.fixed, format);
  }
  get isUniversal() {
    return true;
  }
  offset() {
    return this.fixed;
  }
  equals(otherZone) {
    return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
  }
  get isValid() {
    return true;
  }
};

// node_modules/luxon/src/zones/invalidZone.js
var InvalidZone = class extends Zone {
  constructor(zoneName) {
    super();
    this.zoneName = zoneName;
  }
  get type() {
    return "invalid";
  }
  get name() {
    return this.zoneName;
  }
  get isUniversal() {
    return false;
  }
  offsetName() {
    return null;
  }
  formatOffset() {
    return "";
  }
  offset() {
    return NaN;
  }
  equals() {
    return false;
  }
  get isValid() {
    return false;
  }
};

// node_modules/luxon/src/impl/zoneUtil.js
function normalizeZone(input, defaultZone2) {
  let offset2;
  if (isUndefined(input) || input === null) {
    return defaultZone2;
  } else if (input instanceof Zone) {
    return input;
  } else if (isString(input)) {
    const lowered = input.toLowerCase();
    if (lowered === "default")
      return defaultZone2;
    else if (lowered === "local" || lowered === "system")
      return SystemZone.instance;
    else if (lowered === "utc" || lowered === "gmt")
      return FixedOffsetZone.utcInstance;
    else
      return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);
  } else if (isNumber(input)) {
    return FixedOffsetZone.instance(input);
  } else if (typeof input === "object" && input.offset && typeof input.offset === "number") {
    return input;
  } else {
    return new InvalidZone(input);
  }
}

// node_modules/luxon/src/settings.js
var now = () => Date.now();
var defaultZone = "system";
var defaultLocale = null;
var defaultNumberingSystem = null;
var defaultOutputCalendar = null;
var throwOnInvalid;
var Settings = class {
  static get now() {
    return now;
  }
  static set now(n2) {
    now = n2;
  }
  static set defaultZone(zone) {
    defaultZone = zone;
  }
  static get defaultZone() {
    return normalizeZone(defaultZone, SystemZone.instance);
  }
  static get defaultLocale() {
    return defaultLocale;
  }
  static set defaultLocale(locale) {
    defaultLocale = locale;
  }
  static get defaultNumberingSystem() {
    return defaultNumberingSystem;
  }
  static set defaultNumberingSystem(numberingSystem) {
    defaultNumberingSystem = numberingSystem;
  }
  static get defaultOutputCalendar() {
    return defaultOutputCalendar;
  }
  static set defaultOutputCalendar(outputCalendar) {
    defaultOutputCalendar = outputCalendar;
  }
  static get throwOnInvalid() {
    return throwOnInvalid;
  }
  static set throwOnInvalid(t) {
    throwOnInvalid = t;
  }
  static resetCaches() {
    Locale.resetCache();
    IANAZone.resetCache();
  }
};

// node_modules/luxon/src/impl/locale.js
var intlLFCache = {};
function getCachedLF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let dtf = intlLFCache[key];
  if (!dtf) {
    dtf = new Intl.ListFormat(locString, opts);
    intlLFCache[key] = dtf;
  }
  return dtf;
}
var intlDTCache = {};
function getCachedDTF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let dtf = intlDTCache[key];
  if (!dtf) {
    dtf = new Intl.DateTimeFormat(locString, opts);
    intlDTCache[key] = dtf;
  }
  return dtf;
}
var intlNumCache = {};
function getCachedINF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let inf = intlNumCache[key];
  if (!inf) {
    inf = new Intl.NumberFormat(locString, opts);
    intlNumCache[key] = inf;
  }
  return inf;
}
var intlRelCache = {};
function getCachedRTF(locString, opts = {}) {
  const _a = opts, { base } = _a, cacheKeyOpts = __objRest(_a, ["base"]);
  const key = JSON.stringify([locString, cacheKeyOpts]);
  let inf = intlRelCache[key];
  if (!inf) {
    inf = new Intl.RelativeTimeFormat(locString, opts);
    intlRelCache[key] = inf;
  }
  return inf;
}
var sysLocaleCache = null;
function systemLocale() {
  if (sysLocaleCache) {
    return sysLocaleCache;
  } else {
    sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;
    return sysLocaleCache;
  }
}
function parseLocaleString(localeStr) {
  const uIndex = localeStr.indexOf("-u-");
  if (uIndex === -1) {
    return [localeStr];
  } else {
    let options;
    const smaller = localeStr.substring(0, uIndex);
    try {
      options = getCachedDTF(localeStr).resolvedOptions();
    } catch (e) {
      options = getCachedDTF(smaller).resolvedOptions();
    }
    const { numberingSystem, calendar } = options;
    return [smaller, numberingSystem, calendar];
  }
}
function intlConfigString(localeStr, numberingSystem, outputCalendar) {
  if (outputCalendar || numberingSystem) {
    localeStr += "-u";
    if (outputCalendar) {
      localeStr += `-ca-${outputCalendar}`;
    }
    if (numberingSystem) {
      localeStr += `-nu-${numberingSystem}`;
    }
    return localeStr;
  } else {
    return localeStr;
  }
}
function mapMonths(f) {
  const ms = [];
  for (let i = 1; i <= 12; i++) {
    const dt = DateTime.utc(2016, i, 1);
    ms.push(f(dt));
  }
  return ms;
}
function mapWeekdays(f) {
  const ms = [];
  for (let i = 1; i <= 7; i++) {
    const dt = DateTime.utc(2016, 11, 13 + i);
    ms.push(f(dt));
  }
  return ms;
}
function listStuff(loc, length, defaultOK, englishFn, intlFn) {
  const mode = loc.listingMode(defaultOK);
  if (mode === "error") {
    return null;
  } else if (mode === "en") {
    return englishFn(length);
  } else {
    return intlFn(length);
  }
}
function supportsFastNumbers(loc) {
  if (loc.numberingSystem && loc.numberingSystem !== "latn") {
    return false;
  } else {
    return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn";
  }
}
var PolyNumberFormatter = class {
  constructor(intl, forceSimple, opts) {
    this.padTo = opts.padTo || 0;
    this.floor = opts.floor || false;
    const _a = opts, { padTo, floor } = _a, otherOpts = __objRest(_a, ["padTo", "floor"]);
    if (!forceSimple || Object.keys(otherOpts).length > 0) {
      const intlOpts = __spreadValues({ useGrouping: false }, opts);
      if (opts.padTo > 0)
        intlOpts.minimumIntegerDigits = opts.padTo;
      this.inf = getCachedINF(intl, intlOpts);
    }
  }
  format(i) {
    if (this.inf) {
      const fixed = this.floor ? Math.floor(i) : i;
      return this.inf.format(fixed);
    } else {
      const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);
      return padStart(fixed, this.padTo);
    }
  }
};
var PolyDateFormatter = class {
  constructor(dt, intl, opts) {
    this.opts = opts;
    let z;
    if (dt.zone.isUniversal) {
      const gmtOffset = -1 * (dt.offset / 60);
      const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;
      if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {
        z = offsetZ;
        this.dt = dt;
      } else {
        z = "UTC";
        if (opts.timeZoneName) {
          this.dt = dt;
        } else {
          this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1e3);
        }
      }
    } else if (dt.zone.type === "system") {
      this.dt = dt;
    } else {
      this.dt = dt;
      z = dt.zone.name;
    }
    const intlOpts = __spreadValues({}, this.opts);
    if (z) {
      intlOpts.timeZone = z;
    }
    this.dtf = getCachedDTF(intl, intlOpts);
  }
  format() {
    return this.dtf.format(this.dt.toJSDate());
  }
  formatToParts() {
    return this.dtf.formatToParts(this.dt.toJSDate());
  }
  resolvedOptions() {
    return this.dtf.resolvedOptions();
  }
};
var PolyRelFormatter = class {
  constructor(intl, isEnglish, opts) {
    this.opts = __spreadValues({ style: "long" }, opts);
    if (!isEnglish && hasRelative()) {
      this.rtf = getCachedRTF(intl, opts);
    }
  }
  format(count, unit) {
    if (this.rtf) {
      return this.rtf.format(count, unit);
    } else {
      return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long");
    }
  }
  formatToParts(count, unit) {
    if (this.rtf) {
      return this.rtf.formatToParts(count, unit);
    } else {
      return [];
    }
  }
};
var Locale = class {
  static fromOpts(opts) {
    return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);
  }
  static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {
    const specifiedLocale = locale || Settings.defaultLocale;
    const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale());
    const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;
    const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
    return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);
  }
  static resetCache() {
    sysLocaleCache = null;
    intlDTCache = {};
    intlNumCache = {};
    intlRelCache = {};
  }
  static fromObject({ locale, numberingSystem, outputCalendar } = {}) {
    return Locale.create(locale, numberingSystem, outputCalendar);
  }
  constructor(locale, numbering, outputCalendar, specifiedLocale) {
    const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);
    this.locale = parsedLocale;
    this.numberingSystem = numbering || parsedNumberingSystem || null;
    this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
    this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);
    this.weekdaysCache = { format: {}, standalone: {} };
    this.monthsCache = { format: {}, standalone: {} };
    this.meridiemCache = null;
    this.eraCache = {};
    this.specifiedLocale = specifiedLocale;
    this.fastNumbersCached = null;
  }
  get fastNumbers() {
    if (this.fastNumbersCached == null) {
      this.fastNumbersCached = supportsFastNumbers(this);
    }
    return this.fastNumbersCached;
  }
  listingMode() {
    const isActuallyEn = this.isEnglish();
    const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory");
    return isActuallyEn && hasNoWeirdness ? "en" : "intl";
  }
  clone(alts) {
    if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
      return this;
    } else {
      return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false);
    }
  }
  redefaultToEN(alts = {}) {
    return this.clone(__spreadProps(__spreadValues({}, alts), { defaultToEN: true }));
  }
  redefaultToSystem(alts = {}) {
    return this.clone(__spreadProps(__spreadValues({}, alts), { defaultToEN: false }));
  }
  months(length, format = false, defaultOK = true) {
    return listStuff(this, length, defaultOK, months, () => {
      const intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone";
      if (!this.monthsCache[formatStr][length]) {
        this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, "month"));
      }
      return this.monthsCache[formatStr][length];
    });
  }
  weekdays(length, format = false, defaultOK = true) {
    return listStuff(this, length, defaultOK, weekdays, () => {
      const intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone";
      if (!this.weekdaysCache[formatStr][length]) {
        this.weekdaysCache[formatStr][length] = mapWeekdays((dt) => this.extract(dt, intl, "weekday"));
      }
      return this.weekdaysCache[formatStr][length];
    });
  }
  meridiems(defaultOK = true) {
    return listStuff(this, void 0, defaultOK, () => meridiems, () => {
      if (!this.meridiemCache) {
        const intl = { hour: "numeric", hourCycle: "h12" };
        this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map((dt) => this.extract(dt, intl, "dayperiod"));
      }
      return this.meridiemCache;
    });
  }
  eras(length, defaultOK = true) {
    return listStuff(this, length, defaultOK, eras, () => {
      const intl = { era: length };
      if (!this.eraCache[length]) {
        this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) => this.extract(dt, intl, "era"));
      }
      return this.eraCache[length];
    });
  }
  extract(dt, intlOpts, field) {
    const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field);
    return matching ? matching.value : null;
  }
  numberFormatter(opts = {}) {
    return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);
  }
  dtFormatter(dt, intlOpts = {}) {
    return new PolyDateFormatter(dt, this.intl, intlOpts);
  }
  relFormatter(opts = {}) {
    return new PolyRelFormatter(this.intl, this.isEnglish(), opts);
  }
  listFormatter(opts = {}) {
    return getCachedLF(this.intl, opts);
  }
  isEnglish() {
    return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us");
  }
  equals(other) {
    return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;
  }
};

// node_modules/luxon/src/impl/regexParser.js
function combineRegexes(...regexes) {
  const full = regexes.reduce((f, r) => f + r.source, "");
  return RegExp(`^${full}$`);
}
function combineExtractors(...extractors) {
  return (m) => extractors.reduce(([mergedVals, mergedZone, cursor], ex) => {
    const [val, zone, next] = ex(m, cursor);
    return [__spreadValues(__spreadValues({}, mergedVals), val), zone || mergedZone, next];
  }, [{}, null, 1]).slice(0, 2);
}
function parse(s2, ...patterns) {
  if (s2 == null) {
    return [null, null];
  }
  for (const [regex, extractor] of patterns) {
    const m = regex.exec(s2);
    if (m) {
      return extractor(m);
    }
  }
  return [null, null];
}
function simpleParse(...keys) {
  return (match2, cursor) => {
    const ret = {};
    let i;
    for (i = 0; i < keys.length; i++) {
      ret[keys[i]] = parseInteger(match2[cursor + i]);
    }
    return [ret, null, cursor + i];
  };
}
var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/;
var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`;
var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/;
var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);
var isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);
var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/;
var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/;
var isoOrdinalRegex = /(\d{4})-?(\d{3})/;
var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay");
var extractISOOrdinalData = simpleParse("year", "ordinal");
var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/;
var sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`);
var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);
function int(match2, pos, fallback) {
  const m = match2[pos];
  return isUndefined(m) ? fallback : parseInteger(m);
}
function extractISOYmd(match2, cursor) {
  const item = {
    year: int(match2, cursor),
    month: int(match2, cursor + 1, 1),
    day: int(match2, cursor + 2, 1)
  };
  return [item, null, cursor + 3];
}
function extractISOTime(match2, cursor) {
  const item = {
    hours: int(match2, cursor, 0),
    minutes: int(match2, cursor + 1, 0),
    seconds: int(match2, cursor + 2, 0),
    milliseconds: parseMillis(match2[cursor + 3])
  };
  return [item, null, cursor + 4];
}
function extractISOOffset(match2, cursor) {
  const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset);
  return [{}, zone, cursor + 3];
}
function extractIANAZone(match2, cursor) {
  const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null;
  return [{}, zone, cursor + 1];
}
var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);
var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;
function extractISODuration(match2) {
  const [s2, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2;
  const hasNegativePrefix = s2[0] === "-";
  const negativeSeconds = secondStr && secondStr[0] === "-";
  const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num;
  return [
    {
      years: maybeNegate(parseFloating(yearStr)),
      months: maybeNegate(parseFloating(monthStr)),
      weeks: maybeNegate(parseFloating(weekStr)),
      days: maybeNegate(parseFloating(dayStr)),
      hours: maybeNegate(parseFloating(hourStr)),
      minutes: maybeNegate(parseFloating(minuteStr)),
      seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"),
      milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
    }
  ];
}
var obsOffsets = {
  GMT: 0,
  EDT: -4 * 60,
  EST: -5 * 60,
  CDT: -5 * 60,
  CST: -6 * 60,
  MDT: -6 * 60,
  MST: -7 * 60,
  PDT: -7 * 60,
  PST: -8 * 60
};
function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  const result = {
    year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),
    month: monthsShort.indexOf(monthStr) + 1,
    day: parseInteger(dayStr),
    hour: parseInteger(hourStr),
    minute: parseInteger(minuteStr)
  };
  if (secondStr)
    result.second = parseInteger(secondStr);
  if (weekdayStr) {
    result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1;
  }
  return result;
}
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;
function extractRFC2822(match2) {
  const [
    ,
    weekdayStr,
    dayStr,
    monthStr,
    yearStr,
    hourStr,
    minuteStr,
    secondStr,
    obsOffset,
    milOffset,
    offHourStr,
    offMinuteStr
  ] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  let offset2;
  if (obsOffset) {
    offset2 = obsOffsets[obsOffset];
  } else if (milOffset) {
    offset2 = 0;
  } else {
    offset2 = signedOffset(offHourStr, offMinuteStr);
  }
  return [result, new FixedOffsetZone(offset2)];
}
function preprocessRFC2822(s2) {
  return s2.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim();
}
var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/;
var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/;
var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
function extractRFC1123Or850(match2) {
  const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  return [result, FixedOffsetZone.utcInstance];
}
function extractASCII(match2) {
  const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  return [result, FixedOffsetZone.utcInstance];
}
var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);
var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);
var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);
var isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone);
var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone);
var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone);
var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
function parseISODate(s2) {
  return parse(s2, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]);
}
function parseRFC2822Date(s2) {
  return parse(preprocessRFC2822(s2), [rfc2822, extractRFC2822]);
}
function parseHTTPDate(s2) {
  return parse(s2, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]);
}
function parseISODuration(s2) {
  return parse(s2, [isoDuration, extractISODuration]);
}
var extractISOTimeOnly = combineExtractors(extractISOTime);
function parseISOTimeOnly(s2) {
  return parse(s2, [isoTimeOnly, extractISOTimeOnly]);
}
var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);
var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);
var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
function parseSQL(s2) {
  return parse(s2, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]);
}

// node_modules/luxon/src/duration.js
var INVALID = "Invalid Duration";
var lowOrderMatrix = {
  weeks: {
    days: 7,
    hours: 7 * 24,
    minutes: 7 * 24 * 60,
    seconds: 7 * 24 * 60 * 60,
    milliseconds: 7 * 24 * 60 * 60 * 1e3
  },
  days: {
    hours: 24,
    minutes: 24 * 60,
    seconds: 24 * 60 * 60,
    milliseconds: 24 * 60 * 60 * 1e3
  },
  hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 },
  minutes: { seconds: 60, milliseconds: 60 * 1e3 },
  seconds: { milliseconds: 1e3 }
};
var casualMatrix = __spreadValues({
  years: {
    quarters: 4,
    months: 12,
    weeks: 52,
    days: 365,
    hours: 365 * 24,
    minutes: 365 * 24 * 60,
    seconds: 365 * 24 * 60 * 60,
    milliseconds: 365 * 24 * 60 * 60 * 1e3
  },
  quarters: {
    months: 3,
    weeks: 13,
    days: 91,
    hours: 91 * 24,
    minutes: 91 * 24 * 60,
    seconds: 91 * 24 * 60 * 60,
    milliseconds: 91 * 24 * 60 * 60 * 1e3
  },
  months: {
    weeks: 4,
    days: 30,
    hours: 30 * 24,
    minutes: 30 * 24 * 60,
    seconds: 30 * 24 * 60 * 60,
    milliseconds: 30 * 24 * 60 * 60 * 1e3
  }
}, lowOrderMatrix);
var daysInYearAccurate = 146097 / 400;
var daysInMonthAccurate = 146097 / 4800;
var accurateMatrix = __spreadValues({
  years: {
    quarters: 4,
    months: 12,
    weeks: daysInYearAccurate / 7,
    days: daysInYearAccurate,
    hours: daysInYearAccurate * 24,
    minutes: daysInYearAccurate * 24 * 60,
    seconds: daysInYearAccurate * 24 * 60 * 60,
    milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3
  },
  quarters: {
    months: 3,
    weeks: daysInYearAccurate / 28,
    days: daysInYearAccurate / 4,
    hours: daysInYearAccurate * 24 / 4,
    minutes: daysInYearAccurate * 24 * 60 / 4,
    seconds: daysInYearAccurate * 24 * 60 * 60 / 4,
    milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 / 4
  },
  months: {
    weeks: daysInMonthAccurate / 7,
    days: daysInMonthAccurate,
    hours: daysInMonthAccurate * 24,
    minutes: daysInMonthAccurate * 24 * 60,
    seconds: daysInMonthAccurate * 24 * 60 * 60,
    milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1e3
  }
}, lowOrderMatrix);
var orderedUnits = [
  "years",
  "quarters",
  "months",
  "weeks",
  "days",
  "hours",
  "minutes",
  "seconds",
  "milliseconds"
];
var reverseUnits = orderedUnits.slice(0).reverse();
function clone(dur, alts, clear = false) {
  const conf = {
    values: clear ? alts.values : __spreadValues(__spreadValues({}, dur.values), alts.values || {}),
    loc: dur.loc.clone(alts.loc),
    conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
    matrix: alts.matrix || dur.matrix
  };
  return new Duration(conf);
}
function antiTrunc(n2) {
  return n2 < 0 ? Math.floor(n2) : Math.ceil(n2);
}
function convert(matrix, fromMap, fromUnit, toMap, toUnit) {
  const conv = matrix[toUnit][fromUnit], raw = fromMap[fromUnit] / conv, sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]), added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);
  toMap[toUnit] += added;
  fromMap[fromUnit] -= added * conv;
}
function normalizeValues(matrix, vals) {
  reverseUnits.reduce((previous, current) => {
    if (!isUndefined(vals[current])) {
      if (previous) {
        convert(matrix, vals, previous, vals, current);
      }
      return current;
    } else {
      return previous;
    }
  }, null);
}
var Duration = class {
  constructor(config) {
    const accurate = config.conversionAccuracy === "longterm" || false;
    let matrix = accurate ? accurateMatrix : casualMatrix;
    if (config.matrix) {
      matrix = config.matrix;
    }
    this.values = config.values;
    this.loc = config.loc || Locale.create();
    this.conversionAccuracy = accurate ? "longterm" : "casual";
    this.invalid = config.invalid || null;
    this.matrix = matrix;
    this.isLuxonDuration = true;
  }
  static fromMillis(count, opts) {
    return Duration.fromObject({ milliseconds: count }, opts);
  }
  static fromObject(obj, opts = {}) {
    if (obj == null || typeof obj !== "object") {
      throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`);
    }
    return new Duration({
      values: normalizeObject(obj, Duration.normalizeUnit),
      loc: Locale.fromObject(opts),
      conversionAccuracy: opts.conversionAccuracy,
      matrix: opts.matrix
    });
  }
  static fromDurationLike(durationLike) {
    if (isNumber(durationLike)) {
      return Duration.fromMillis(durationLike);
    } else if (Duration.isDuration(durationLike)) {
      return durationLike;
    } else if (typeof durationLike === "object") {
      return Duration.fromObject(durationLike);
    } else {
      throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`);
    }
  }
  static fromISO(text, opts) {
    const [parsed] = parseISODuration(text);
    if (parsed) {
      return Duration.fromObject(parsed, opts);
    } else {
      return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
    }
  }
  static fromISOTime(text, opts) {
    const [parsed] = parseISOTimeOnly(text);
    if (parsed) {
      return Duration.fromObject(parsed, opts);
    } else {
      return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
    }
  }
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidDurationError(invalid);
    } else {
      return new Duration({ invalid });
    }
  }
  static normalizeUnit(unit) {
    const normalized = {
      year: "years",
      years: "years",
      quarter: "quarters",
      quarters: "quarters",
      month: "months",
      months: "months",
      week: "weeks",
      weeks: "weeks",
      day: "days",
      days: "days",
      hour: "hours",
      hours: "hours",
      minute: "minutes",
      minutes: "minutes",
      second: "seconds",
      seconds: "seconds",
      millisecond: "milliseconds",
      milliseconds: "milliseconds"
    }[unit ? unit.toLowerCase() : unit];
    if (!normalized)
      throw new InvalidUnitError(unit);
    return normalized;
  }
  static isDuration(o) {
    return o && o.isLuxonDuration || false;
  }
  get locale() {
    return this.isValid ? this.loc.locale : null;
  }
  get numberingSystem() {
    return this.isValid ? this.loc.numberingSystem : null;
  }
  toFormat(fmt, opts = {}) {
    const fmtOpts = __spreadProps(__spreadValues({}, opts), {
      floor: opts.round !== false && opts.floor !== false
    });
    return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID;
  }
  toHuman(opts = {}) {
    const l2 = orderedUnits.map((unit) => {
      const val = this.values[unit];
      if (isUndefined(val)) {
        return null;
      }
      return this.loc.numberFormatter(__spreadProps(__spreadValues({ style: "unit", unitDisplay: "long" }, opts), { unit: unit.slice(0, -1) })).format(val);
    }).filter((n2) => n2);
    return this.loc.listFormatter(__spreadValues({ type: "conjunction", style: opts.listStyle || "narrow" }, opts)).format(l2);
  }
  toObject() {
    if (!this.isValid)
      return {};
    return __spreadValues({}, this.values);
  }
  toISO() {
    if (!this.isValid)
      return null;
    let s2 = "P";
    if (this.years !== 0)
      s2 += this.years + "Y";
    if (this.months !== 0 || this.quarters !== 0)
      s2 += this.months + this.quarters * 3 + "M";
    if (this.weeks !== 0)
      s2 += this.weeks + "W";
    if (this.days !== 0)
      s2 += this.days + "D";
    if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
      s2 += "T";
    if (this.hours !== 0)
      s2 += this.hours + "H";
    if (this.minutes !== 0)
      s2 += this.minutes + "M";
    if (this.seconds !== 0 || this.milliseconds !== 0)
      s2 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S";
    if (s2 === "P")
      s2 += "T0S";
    return s2;
  }
  toISOTime(opts = {}) {
    if (!this.isValid)
      return null;
    const millis = this.toMillis();
    if (millis < 0 || millis >= 864e5)
      return null;
    opts = __spreadValues({
      suppressMilliseconds: false,
      suppressSeconds: false,
      includePrefix: false,
      format: "extended"
    }, opts);
    const value = this.shiftTo("hours", "minutes", "seconds", "milliseconds");
    let fmt = opts.format === "basic" ? "hhmm" : "hh:mm";
    if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {
      fmt += opts.format === "basic" ? "ss" : ":ss";
      if (!opts.suppressMilliseconds || value.milliseconds !== 0) {
        fmt += ".SSS";
      }
    }
    let str = value.toFormat(fmt);
    if (opts.includePrefix) {
      str = "T" + str;
    }
    return str;
  }
  toJSON() {
    return this.toISO();
  }
  toString() {
    return this.toISO();
  }
  toMillis() {
    return this.as("milliseconds");
  }
  valueOf() {
    return this.toMillis();
  }
  plus(duration2) {
    if (!this.isValid)
      return this;
    const dur = Duration.fromDurationLike(duration2), result = {};
    for (const k of orderedUnits) {
      if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
        result[k] = dur.get(k) + this.get(k);
      }
    }
    return clone(this, { values: result }, true);
  }
  minus(duration2) {
    if (!this.isValid)
      return this;
    const dur = Duration.fromDurationLike(duration2);
    return this.plus(dur.negate());
  }
  mapUnits(fn) {
    if (!this.isValid)
      return this;
    const result = {};
    for (const k of Object.keys(this.values)) {
      result[k] = asNumber(fn(this.values[k], k));
    }
    return clone(this, { values: result }, true);
  }
  get(unit) {
    return this[Duration.normalizeUnit(unit)];
  }
  set(values) {
    if (!this.isValid)
      return this;
    const mixed = __spreadValues(__spreadValues({}, this.values), normalizeObject(values, Duration.normalizeUnit));
    return clone(this, { values: mixed });
  }
  reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {
    const loc = this.loc.clone({ locale, numberingSystem });
    const opts = { loc, matrix, conversionAccuracy };
    return clone(this, opts);
  }
  as(unit) {
    return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
  }
  normalize() {
    if (!this.isValid)
      return this;
    const vals = this.toObject();
    normalizeValues(this.matrix, vals);
    return clone(this, { values: vals }, true);
  }
  shiftTo(...units) {
    if (!this.isValid)
      return this;
    if (units.length === 0) {
      return this;
    }
    units = units.map((u) => Duration.normalizeUnit(u));
    const built = {}, accumulated = {}, vals = this.toObject();
    let lastUnit;
    for (const k of orderedUnits) {
      if (units.indexOf(k) >= 0) {
        lastUnit = k;
        let own = 0;
        for (const ak in accumulated) {
          own += this.matrix[ak][k] * accumulated[ak];
          accumulated[ak] = 0;
        }
        if (isNumber(vals[k])) {
          own += vals[k];
        }
        const i = Math.trunc(own);
        built[k] = i;
        accumulated[k] = (own * 1e3 - i * 1e3) / 1e3;
        for (const down in vals) {
          if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) {
            convert(this.matrix, vals, down, built, k);
          }
        }
      } else if (isNumber(vals[k])) {
        accumulated[k] = vals[k];
      }
    }
    for (const key in accumulated) {
      if (accumulated[key] !== 0) {
        built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
      }
    }
    return clone(this, { values: built }, true).normalize();
  }
  negate() {
    if (!this.isValid)
      return this;
    const negated = {};
    for (const k of Object.keys(this.values)) {
      negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
    }
    return clone(this, { values: negated }, true);
  }
  get years() {
    return this.isValid ? this.values.years || 0 : NaN;
  }
  get quarters() {
    return this.isValid ? this.values.quarters || 0 : NaN;
  }
  get months() {
    return this.isValid ? this.values.months || 0 : NaN;
  }
  get weeks() {
    return this.isValid ? this.values.weeks || 0 : NaN;
  }
  get days() {
    return this.isValid ? this.values.days || 0 : NaN;
  }
  get hours() {
    return this.isValid ? this.values.hours || 0 : NaN;
  }
  get minutes() {
    return this.isValid ? this.values.minutes || 0 : NaN;
  }
  get seconds() {
    return this.isValid ? this.values.seconds || 0 : NaN;
  }
  get milliseconds() {
    return this.isValid ? this.values.milliseconds || 0 : NaN;
  }
  get isValid() {
    return this.invalid === null;
  }
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  equals(other) {
    if (!this.isValid || !other.isValid) {
      return false;
    }
    if (!this.loc.equals(other.loc)) {
      return false;
    }
    function eq(v1, v2) {
      if (v1 === void 0 || v1 === 0)
        return v2 === void 0 || v2 === 0;
      return v1 === v2;
    }
    for (const u of orderedUnits) {
      if (!eq(this.values[u], other.values[u])) {
        return false;
      }
    }
    return true;
  }
};

// node_modules/luxon/src/interval.js
var INVALID2 = "Invalid Interval";
function validateStartEnd(start, end) {
  if (!start || !start.isValid) {
    return Interval.invalid("missing or invalid start");
  } else if (!end || !end.isValid) {
    return Interval.invalid("missing or invalid end");
  } else if (end < start) {
    return Interval.invalid("end before start", `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`);
  } else {
    return null;
  }
}
var Interval = class {
  constructor(config) {
    this.s = config.start;
    this.e = config.end;
    this.invalid = config.invalid || null;
    this.isLuxonInterval = true;
  }
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidIntervalError(invalid);
    } else {
      return new Interval({ invalid });
    }
  }
  static fromDateTimes(start, end) {
    const builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end);
    const validateError = validateStartEnd(builtStart, builtEnd);
    if (validateError == null) {
      return new Interval({
        start: builtStart,
        end: builtEnd
      });
    } else {
      return validateError;
    }
  }
  static after(start, duration2) {
    const dur = Duration.fromDurationLike(duration2), dt = friendlyDateTime(start);
    return Interval.fromDateTimes(dt, dt.plus(dur));
  }
  static before(end, duration2) {
    const dur = Duration.fromDurationLike(duration2), dt = friendlyDateTime(end);
    return Interval.fromDateTimes(dt.minus(dur), dt);
  }
  static fromISO(text, opts) {
    const [s2, e] = (text || "").split("/", 2);
    if (s2 && e) {
      let start, startIsValid;
      try {
        start = DateTime.fromISO(s2, opts);
        startIsValid = start.isValid;
      } catch (e2) {
        startIsValid = false;
      }
      let end, endIsValid;
      try {
        end = DateTime.fromISO(e, opts);
        endIsValid = end.isValid;
      } catch (e2) {
        endIsValid = false;
      }
      if (startIsValid && endIsValid) {
        return Interval.fromDateTimes(start, end);
      }
      if (startIsValid) {
        const dur = Duration.fromISO(e, opts);
        if (dur.isValid) {
          return Interval.after(start, dur);
        }
      } else if (endIsValid) {
        const dur = Duration.fromISO(s2, opts);
        if (dur.isValid) {
          return Interval.before(end, dur);
        }
      }
    }
    return Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
  }
  static isInterval(o) {
    return o && o.isLuxonInterval || false;
  }
  get start() {
    return this.isValid ? this.s : null;
  }
  get end() {
    return this.isValid ? this.e : null;
  }
  get isValid() {
    return this.invalidReason === null;
  }
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  length(unit = "milliseconds") {
    return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;
  }
  count(unit = "milliseconds") {
    if (!this.isValid)
      return NaN;
    const start = this.start.startOf(unit), end = this.end.startOf(unit);
    return Math.floor(end.diff(start, unit).get(unit)) + 1;
  }
  hasSame(unit) {
    return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
  }
  isEmpty() {
    return this.s.valueOf() === this.e.valueOf();
  }
  isAfter(dateTime) {
    if (!this.isValid)
      return false;
    return this.s > dateTime;
  }
  isBefore(dateTime) {
    if (!this.isValid)
      return false;
    return this.e <= dateTime;
  }
  contains(dateTime) {
    if (!this.isValid)
      return false;
    return this.s <= dateTime && this.e > dateTime;
  }
  set({ start, end } = {}) {
    if (!this.isValid)
      return this;
    return Interval.fromDateTimes(start || this.s, end || this.e);
  }
  splitAt(...dateTimes) {
    if (!this.isValid)
      return [];
    const sorted = dateTimes.map(friendlyDateTime).filter((d) => this.contains(d)).sort(), results = [];
    let { s: s2 } = this, i = 0;
    while (s2 < this.e) {
      const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added;
      results.push(Interval.fromDateTimes(s2, next));
      s2 = next;
      i += 1;
    }
    return results;
  }
  splitBy(duration2) {
    const dur = Duration.fromDurationLike(duration2);
    if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
      return [];
    }
    let { s: s2 } = this, idx = 1, next;
    const results = [];
    while (s2 < this.e) {
      const added = this.start.plus(dur.mapUnits((x) => x * idx));
      next = +added > +this.e ? this.e : added;
      results.push(Interval.fromDateTimes(s2, next));
      s2 = next;
      idx += 1;
    }
    return results;
  }
  divideEqually(numberOfParts) {
    if (!this.isValid)
      return [];
    return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
  }
  overlaps(other) {
    return this.e > other.s && this.s < other.e;
  }
  abutsStart(other) {
    if (!this.isValid)
      return false;
    return +this.e === +other.s;
  }
  abutsEnd(other) {
    if (!this.isValid)
      return false;
    return +other.e === +this.s;
  }
  engulfs(other) {
    if (!this.isValid)
      return false;
    return this.s <= other.s && this.e >= other.e;
  }
  equals(other) {
    if (!this.isValid || !other.isValid) {
      return false;
    }
    return this.s.equals(other.s) && this.e.equals(other.e);
  }
  intersection(other) {
    if (!this.isValid)
      return this;
    const s2 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e;
    if (s2 >= e) {
      return null;
    } else {
      return Interval.fromDateTimes(s2, e);
    }
  }
  union(other) {
    if (!this.isValid)
      return this;
    const s2 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e;
    return Interval.fromDateTimes(s2, e);
  }
  static merge(intervals) {
    const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(([sofar, current], item) => {
      if (!current) {
        return [sofar, item];
      } else if (current.overlaps(item) || current.abutsStart(item)) {
        return [sofar, current.union(item)];
      } else {
        return [sofar.concat([current]), item];
      }
    }, [[], null]);
    if (final) {
      found.push(final);
    }
    return found;
  }
  static xor(intervals) {
    let start = null, currentCount = 0;
    const results = [], ends = intervals.map((i) => [
      { time: i.s, type: "s" },
      { time: i.e, type: "e" }
    ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time);
    for (const i of arr) {
      currentCount += i.type === "s" ? 1 : -1;
      if (currentCount === 1) {
        start = i.time;
      } else {
        if (start && +start !== +i.time) {
          results.push(Interval.fromDateTimes(start, i.time));
        }
        start = null;
      }
    }
    return Interval.merge(results);
  }
  difference(...intervals) {
    return Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty());
  }
  toString() {
    if (!this.isValid)
      return INVALID2;
    return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`;
  }
  toISO(opts) {
    if (!this.isValid)
      return INVALID2;
    return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;
  }
  toISODate() {
    if (!this.isValid)
      return INVALID2;
    return `${this.s.toISODate()}/${this.e.toISODate()}`;
  }
  toISOTime(opts) {
    if (!this.isValid)
      return INVALID2;
    return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;
  }
  toFormat(dateFormat, { separator = " \u2013 " } = {}) {
    if (!this.isValid)
      return INVALID2;
    return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;
  }
  toDuration(unit, opts) {
    if (!this.isValid) {
      return Duration.invalid(this.invalidReason);
    }
    return this.e.diff(this.s, unit, opts);
  }
  mapEndpoints(mapFn) {
    return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
  }
};

// node_modules/luxon/src/info.js
var Info = class {
  static hasDST(zone = Settings.defaultZone) {
    const proto = DateTime.now().setZone(zone).set({ month: 12 });
    return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;
  }
  static isValidIANAZone(zone) {
    return IANAZone.isValidZone(zone);
  }
  static normalizeZone(input) {
    return normalizeZone(input, Settings.defaultZone);
  }
  static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);
  }
  static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);
  }
  static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);
  }
  static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);
  }
  static meridiems({ locale = null } = {}) {
    return Locale.create(locale).meridiems();
  }
  static eras(length = "short", { locale = null } = {}) {
    return Locale.create(locale, null, "gregory").eras(length);
  }
  static features() {
    return { relative: hasRelative() };
  }
};

// node_modules/luxon/src/impl/diff.js
function dayDiff(earlier, later) {
  const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier);
  return Math.floor(Duration.fromMillis(ms).as("days"));
}
function highOrderDiffs(cursor, later, units) {
  const differs = [
    ["years", (a, b) => b.year - a.year],
    ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4],
    ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12],
    [
      "weeks",
      (a, b) => {
        const days = dayDiff(a, b);
        return (days - days % 7) / 7;
      }
    ],
    ["days", dayDiff]
  ];
  const results = {};
  let lowestOrder, highWater;
  for (const [unit, differ] of differs) {
    if (units.indexOf(unit) >= 0) {
      lowestOrder = unit;
      let delta = differ(cursor, later);
      highWater = cursor.plus({ [unit]: delta });
      if (highWater > later) {
        cursor = cursor.plus({ [unit]: delta - 1 });
        delta -= 1;
      } else {
        cursor = highWater;
      }
      results[unit] = delta;
    }
  }
  return [cursor, results, highWater, lowestOrder];
}
function diff_default(earlier, later, units, opts) {
  let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);
  const remainingMillis = later - cursor;
  const lowerOrderUnits = units.filter((u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0);
  if (lowerOrderUnits.length === 0) {
    if (highWater < later) {
      highWater = cursor.plus({ [lowestOrder]: 1 });
    }
    if (highWater !== cursor) {
      results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
    }
  }
  const duration2 = Duration.fromObject(results, opts);
  if (lowerOrderUnits.length > 0) {
    return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration2);
  } else {
    return duration2;
  }
}

// node_modules/luxon/src/impl/digits.js
var numberingSystems = {
  arab: "[\u0660-\u0669]",
  arabext: "[\u06F0-\u06F9]",
  bali: "[\u1B50-\u1B59]",
  beng: "[\u09E6-\u09EF]",
  deva: "[\u0966-\u096F]",
  fullwide: "[\uFF10-\uFF19]",
  gujr: "[\u0AE6-\u0AEF]",
  hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",
  khmr: "[\u17E0-\u17E9]",
  knda: "[\u0CE6-\u0CEF]",
  laoo: "[\u0ED0-\u0ED9]",
  limb: "[\u1946-\u194F]",
  mlym: "[\u0D66-\u0D6F]",
  mong: "[\u1810-\u1819]",
  mymr: "[\u1040-\u1049]",
  orya: "[\u0B66-\u0B6F]",
  tamldec: "[\u0BE6-\u0BEF]",
  telu: "[\u0C66-\u0C6F]",
  thai: "[\u0E50-\u0E59]",
  tibt: "[\u0F20-\u0F29]",
  latn: "\\d"
};
var numberingSystemsUTF16 = {
  arab: [1632, 1641],
  arabext: [1776, 1785],
  bali: [6992, 7001],
  beng: [2534, 2543],
  deva: [2406, 2415],
  fullwide: [65296, 65303],
  gujr: [2790, 2799],
  khmr: [6112, 6121],
  knda: [3302, 3311],
  laoo: [3792, 3801],
  limb: [6470, 6479],
  mlym: [3430, 3439],
  mong: [6160, 6169],
  mymr: [4160, 4169],
  orya: [2918, 2927],
  tamldec: [3046, 3055],
  telu: [3174, 3183],
  thai: [3664, 3673],
  tibt: [3872, 3881]
};
var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split("");
function parseDigits(str) {
  let value = parseInt(str, 10);
  if (isNaN(value)) {
    value = "";
    for (let i = 0; i < str.length; i++) {
      const code = str.charCodeAt(i);
      if (str[i].search(numberingSystems.hanidec) !== -1) {
        value += hanidecChars.indexOf(str[i]);
      } else {
        for (const key in numberingSystemsUTF16) {
          const [min, max] = numberingSystemsUTF16[key];
          if (code >= min && code <= max) {
            value += code - min;
          }
        }
      }
    }
    return parseInt(value, 10);
  } else {
    return value;
  }
}
function digitRegex({ numberingSystem }, append = "") {
  return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`);
}

// node_modules/luxon/src/impl/tokenParser.js
var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support";
function intUnit(regex, post = (i) => i) {
  return { regex, deser: ([s2]) => post(parseDigits(s2)) };
}
var NBSP = String.fromCharCode(160);
var spaceOrNBSP = `[ ${NBSP}]`;
var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g");
function fixListRegex(s2) {
  return s2.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP);
}
function stripInsensitivities(s2) {
  return s2.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase();
}
function oneOf(strings, startIndex) {
  if (strings === null) {
    return null;
  } else {
    return {
      regex: RegExp(strings.map(fixListRegex).join("|")),
      deser: ([s2]) => strings.findIndex((i) => stripInsensitivities(s2) === stripInsensitivities(i)) + startIndex
    };
  }
}
function offset(regex, groups) {
  return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };
}
function simple(regex) {
  return { regex, deser: ([s2]) => s2 };
}
function escapeToken(value) {
  return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
function unitForToken(token, loc) {
  const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s2]) => s2, literal: true }), unitate = (t) => {
    if (token.literal) {
      return literal(t);
    }
    switch (t.val) {
      case "G":
        return oneOf(loc.eras("short", false), 0);
      case "GG":
        return oneOf(loc.eras("long", false), 0);
      case "y":
        return intUnit(oneToSix);
      case "yy":
        return intUnit(twoToFour, untruncateYear);
      case "yyyy":
        return intUnit(four);
      case "yyyyy":
        return intUnit(fourToSix);
      case "yyyyyy":
        return intUnit(six);
      case "M":
        return intUnit(oneOrTwo);
      case "MM":
        return intUnit(two);
      case "MMM":
        return oneOf(loc.months("short", true, false), 1);
      case "MMMM":
        return oneOf(loc.months("long", true, false), 1);
      case "L":
        return intUnit(oneOrTwo);
      case "LL":
        return intUnit(two);
      case "LLL":
        return oneOf(loc.months("short", false, false), 1);
      case "LLLL":
        return oneOf(loc.months("long", false, false), 1);
      case "d":
        return intUnit(oneOrTwo);
      case "dd":
        return intUnit(two);
      case "o":
        return intUnit(oneToThree);
      case "ooo":
        return intUnit(three);
      case "HH":
        return intUnit(two);
      case "H":
        return intUnit(oneOrTwo);
      case "hh":
        return intUnit(two);
      case "h":
        return intUnit(oneOrTwo);
      case "mm":
        return intUnit(two);
      case "m":
        return intUnit(oneOrTwo);
      case "q":
        return intUnit(oneOrTwo);
      case "qq":
        return intUnit(two);
      case "s":
        return intUnit(oneOrTwo);
      case "ss":
        return intUnit(two);
      case "S":
        return intUnit(oneToThree);
      case "SSS":
        return intUnit(three);
      case "u":
        return simple(oneToNine);
      case "uu":
        return simple(oneOrTwo);
      case "uuu":
        return intUnit(one);
      case "a":
        return oneOf(loc.meridiems(), 0);
      case "kkkk":
        return intUnit(four);
      case "kk":
        return intUnit(twoToFour, untruncateYear);
      case "W":
        return intUnit(oneOrTwo);
      case "WW":
        return intUnit(two);
      case "E":
      case "c":
        return intUnit(one);
      case "EEE":
        return oneOf(loc.weekdays("short", false, false), 1);
      case "EEEE":
        return oneOf(loc.weekdays("long", false, false), 1);
      case "ccc":
        return oneOf(loc.weekdays("short", true, false), 1);
      case "cccc":
        return oneOf(loc.weekdays("long", true, false), 1);
      case "Z":
      case "ZZ":
        return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);
      case "ZZZ":
        return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);
      case "z":
        return simple(/[a-z_+-/]{1,256}?/i);
      default:
        return literal(t);
    }
  };
  const unit = unitate(token) || {
    invalidReason: MISSING_FTP
  };
  unit.token = token;
  return unit;
}
var partTypeStyleToTokenVal = {
  year: {
    "2-digit": "yy",
    numeric: "yyyyy"
  },
  month: {
    numeric: "M",
    "2-digit": "MM",
    short: "MMM",
    long: "MMMM"
  },
  day: {
    numeric: "d",
    "2-digit": "dd"
  },
  weekday: {
    short: "EEE",
    long: "EEEE"
  },
  dayperiod: "a",
  dayPeriod: "a",
  hour: {
    numeric: "h",
    "2-digit": "hh"
  },
  minute: {
    numeric: "m",
    "2-digit": "mm"
  },
  second: {
    numeric: "s",
    "2-digit": "ss"
  },
  timeZoneName: {
    long: "ZZZZZ",
    short: "ZZZ"
  }
};
function tokenForPart(part, locale, formatOpts) {
  const { type, value } = part;
  if (type === "literal") {
    return {
      literal: true,
      val: value
    };
  }
  const style = formatOpts[type];
  let val = partTypeStyleToTokenVal[type];
  if (typeof val === "object") {
    val = val[style];
  }
  if (val) {
    return {
      literal: false,
      val
    };
  }
  return void 0;
}
function buildRegex(units) {
  const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, "");
  return [`^${re}$`, units];
}
function match(input, regex, handlers) {
  const matches = input.match(regex);
  if (matches) {
    const all = {};
    let matchIndex = 1;
    for (const i in handlers) {
      if (hasOwnProperty(handlers, i)) {
        const h = handlers[i], groups = h.groups ? h.groups + 1 : 1;
        if (!h.literal && h.token) {
          all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
        }
        matchIndex += groups;
      }
    }
    return [matches, all];
  } else {
    return [matches, {}];
  }
}
function dateTimeFromMatches(matches) {
  const toField = (token) => {
    switch (token) {
      case "S":
        return "millisecond";
      case "s":
        return "second";
      case "m":
        return "minute";
      case "h":
      case "H":
        return "hour";
      case "d":
        return "day";
      case "o":
        return "ordinal";
      case "L":
      case "M":
        return "month";
      case "y":
        return "year";
      case "E":
      case "c":
        return "weekday";
      case "W":
        return "weekNumber";
      case "k":
        return "weekYear";
      case "q":
        return "quarter";
      default:
        return null;
    }
  };
  let zone = null;
  let specificOffset;
  if (!isUndefined(matches.z)) {
    zone = IANAZone.create(matches.z);
  }
  if (!isUndefined(matches.Z)) {
    if (!zone) {
      zone = new FixedOffsetZone(matches.Z);
    }
    specificOffset = matches.Z;
  }
  if (!isUndefined(matches.q)) {
    matches.M = (matches.q - 1) * 3 + 1;
  }
  if (!isUndefined(matches.h)) {
    if (matches.h < 12 && matches.a === 1) {
      matches.h += 12;
    } else if (matches.h === 12 && matches.a === 0) {
      matches.h = 0;
    }
  }
  if (matches.G === 0 && matches.y) {
    matches.y = -matches.y;
  }
  if (!isUndefined(matches.u)) {
    matches.S = parseMillis(matches.u);
  }
  const vals = Object.keys(matches).reduce((r, k) => {
    const f = toField(k);
    if (f) {
      r[f] = matches[k];
    }
    return r;
  }, {});
  return [vals, zone, specificOffset];
}
var dummyDateTimeCache = null;
function getDummyDateTime() {
  if (!dummyDateTimeCache) {
    dummyDateTimeCache = DateTime.fromMillis(1555555555555);
  }
  return dummyDateTimeCache;
}
function maybeExpandMacroToken(token, locale) {
  if (token.literal) {
    return token;
  }
  const formatOpts = Formatter.macroTokenToFormatOpts(token.val);
  const tokens = formatOptsToTokens(formatOpts, locale);
  if (tokens == null || tokens.includes(void 0)) {
    return token;
  }
  return tokens;
}
function expandMacroTokens(tokens, locale) {
  return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale)));
}
function explainFromTokens(locale, input, format) {
  const tokens = expandMacroTokens(Formatter.parseFormat(format), locale), units = tokens.map((t) => unitForToken(t, locale)), disqualifyingUnit = units.find((t) => t.invalidReason);
  if (disqualifyingUnit) {
    return { input, tokens, invalidReason: disqualifyingUnit.invalidReason };
  } else {
    const [regexString, handlers] = buildRegex(units), regex = RegExp(regexString, "i"), [rawMatches, matches] = match(input, regex, handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0];
    if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
      throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");
    }
    return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset };
  }
}
function parseFromTokens(locale, input, format) {
  const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format);
  return [result, zone, specificOffset, invalidReason];
}
function formatOptsToTokens(formatOpts, locale) {
  if (!formatOpts) {
    return null;
  }
  const formatter = Formatter.create(locale, formatOpts);
  const parts = formatter.formatDateTimeParts(getDummyDateTime());
  return parts.map((p) => tokenForPart(p, locale, formatOpts));
}

// node_modules/luxon/src/impl/conversions.js
var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
function unitOutOfRange(unit, value) {
  return new Invalid("unit out of range", `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`);
}
function dayOfWeek(year, month, day) {
  const d = new Date(Date.UTC(year, month - 1, day));
  if (year < 100 && year >= 0) {
    d.setUTCFullYear(d.getUTCFullYear() - 1900);
  }
  const js = d.getUTCDay();
  return js === 0 ? 7 : js;
}
function computeOrdinal(year, month, day) {
  return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];
}
function uncomputeOrdinal(year, ordinal) {
  const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0];
  return { month: month0 + 1, day };
}
function gregorianToWeek(gregObj) {
  const { year, month, day } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = dayOfWeek(year, month, day);
  let weekNumber = Math.floor((ordinal - weekday + 10) / 7), weekYear;
  if (weekNumber < 1) {
    weekYear = year - 1;
    weekNumber = weeksInWeekYear(weekYear);
  } else if (weekNumber > weeksInWeekYear(year)) {
    weekYear = year + 1;
    weekNumber = 1;
  } else {
    weekYear = year;
  }
  return __spreadValues({ weekYear, weekNumber, weekday }, timeObject(gregObj));
}
function weekToGregorian(weekData) {
  const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), yearInDays = daysInYear(weekYear);
  let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, year;
  if (ordinal < 1) {
    year = weekYear - 1;
    ordinal += daysInYear(year);
  } else if (ordinal > yearInDays) {
    year = weekYear + 1;
    ordinal -= daysInYear(weekYear);
  } else {
    year = weekYear;
  }
  const { month, day } = uncomputeOrdinal(year, ordinal);
  return __spreadValues({ year, month, day }, timeObject(weekData));
}
function gregorianToOrdinal(gregData) {
  const { year, month, day } = gregData;
  const ordinal = computeOrdinal(year, month, day);
  return __spreadValues({ year, ordinal }, timeObject(gregData));
}
function ordinalToGregorian(ordinalData) {
  const { year, ordinal } = ordinalData;
  const { month, day } = uncomputeOrdinal(year, ordinal);
  return __spreadValues({ year, month, day }, timeObject(ordinalData));
}
function hasInvalidWeekData(obj) {
  const validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), validWeekday = integerBetween(obj.weekday, 1, 7);
  if (!validYear) {
    return unitOutOfRange("weekYear", obj.weekYear);
  } else if (!validWeek) {
    return unitOutOfRange("week", obj.week);
  } else if (!validWeekday) {
    return unitOutOfRange("weekday", obj.weekday);
  } else
    return false;
}
function hasInvalidOrdinalData(obj) {
  const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));
  if (!validYear) {
    return unitOutOfRange("year", obj.year);
  } else if (!validOrdinal) {
    return unitOutOfRange("ordinal", obj.ordinal);
  } else
    return false;
}
function hasInvalidGregorianData(obj) {
  const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));
  if (!validYear) {
    return unitOutOfRange("year", obj.year);
  } else if (!validMonth) {
    return unitOutOfRange("month", obj.month);
  } else if (!validDay) {
    return unitOutOfRange("day", obj.day);
  } else
    return false;
}
function hasInvalidTimeData(obj) {
  const { hour, minute, second, millisecond } = obj;
  const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999);
  if (!validHour) {
    return unitOutOfRange("hour", hour);
  } else if (!validMinute) {
    return unitOutOfRange("minute", minute);
  } else if (!validSecond) {
    return unitOutOfRange("second", second);
  } else if (!validMillisecond) {
    return unitOutOfRange("millisecond", millisecond);
  } else
    return false;
}

// node_modules/luxon/src/datetime.js
var INVALID3 = "Invalid DateTime";
var MAX_DATE = 864e13;
function unsupportedZone(zone) {
  return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
}
function possiblyCachedWeekData(dt) {
  if (dt.weekData === null) {
    dt.weekData = gregorianToWeek(dt.c);
  }
  return dt.weekData;
}
function clone2(inst, alts) {
  const current = {
    ts: inst.ts,
    zone: inst.zone,
    c: inst.c,
    o: inst.o,
    loc: inst.loc,
    invalid: inst.invalid
  };
  return new DateTime(__spreadProps(__spreadValues(__spreadValues({}, current), alts), { old: current }));
}
function fixOffset(localTS, o, tz) {
  let utcGuess = localTS - o * 60 * 1e3;
  const o2 = tz.offset(utcGuess);
  if (o === o2) {
    return [utcGuess, o];
  }
  utcGuess -= (o2 - o) * 60 * 1e3;
  const o3 = tz.offset(utcGuess);
  if (o2 === o3) {
    return [utcGuess, o2];
  }
  return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)];
}
function tsToObj(ts, offset2) {
  ts += offset2 * 60 * 1e3;
  const d = new Date(ts);
  return {
    year: d.getUTCFullYear(),
    month: d.getUTCMonth() + 1,
    day: d.getUTCDate(),
    hour: d.getUTCHours(),
    minute: d.getUTCMinutes(),
    second: d.getUTCSeconds(),
    millisecond: d.getUTCMilliseconds()
  };
}
function objToTS(obj, offset2, zone) {
  return fixOffset(objToLocalTS(obj), offset2, zone);
}
function adjustTime(inst, dur) {
  const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = __spreadProps(__spreadValues({}, inst.c), {
    year,
    month,
    day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
  }), millisToAdd = Duration.fromObject({
    years: dur.years - Math.trunc(dur.years),
    quarters: dur.quarters - Math.trunc(dur.quarters),
    months: dur.months - Math.trunc(dur.months),
    weeks: dur.weeks - Math.trunc(dur.weeks),
    days: dur.days - Math.trunc(dur.days),
    hours: dur.hours,
    minutes: dur.minutes,
    seconds: dur.seconds,
    milliseconds: dur.milliseconds
  }).as("milliseconds"), localTS = objToLocalTS(c);
  let [ts, o] = fixOffset(localTS, oPre, inst.zone);
  if (millisToAdd !== 0) {
    ts += millisToAdd;
    o = inst.zone.offset(ts);
  }
  return { ts, o };
}
function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {
  const { setZone, zone } = opts;
  if (parsed && Object.keys(parsed).length !== 0) {
    const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, __spreadProps(__spreadValues({}, opts), {
      zone: interpretationZone,
      specificOffset
    }));
    return setZone ? inst : inst.setZone(zone);
  } else {
    return DateTime.invalid(new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`));
  }
}
function toTechFormat(dt, format, allowZ = true) {
  return dt.isValid ? Formatter.create(Locale.create("en-US"), {
    allowZ,
    forceSimple: true
  }).formatDateTimeFromString(dt, format) : null;
}
function toISODate(o, extended) {
  const longFormat = o.c.year > 9999 || o.c.year < 0;
  let c = "";
  if (longFormat && o.c.year >= 0)
    c += "+";
  c += padStart(o.c.year, longFormat ? 6 : 4);
  if (extended) {
    c += "-";
    c += padStart(o.c.month);
    c += "-";
    c += padStart(o.c.day);
  } else {
    c += padStart(o.c.month);
    c += padStart(o.c.day);
  }
  return c;
}
function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) {
  let c = padStart(o.c.hour);
  if (extended) {
    c += ":";
    c += padStart(o.c.minute);
    if (o.c.second !== 0 || !suppressSeconds) {
      c += ":";
    }
  } else {
    c += padStart(o.c.minute);
  }
  if (o.c.second !== 0 || !suppressSeconds) {
    c += padStart(o.c.second);
    if (o.c.millisecond !== 0 || !suppressMilliseconds) {
      c += ".";
      c += padStart(o.c.millisecond, 3);
    }
  }
  if (includeOffset) {
    if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
      c += "Z";
    } else if (o.o < 0) {
      c += "-";
      c += padStart(Math.trunc(-o.o / 60));
      c += ":";
      c += padStart(Math.trunc(-o.o % 60));
    } else {
      c += "+";
      c += padStart(Math.trunc(o.o / 60));
      c += ":";
      c += padStart(Math.trunc(o.o % 60));
    }
  }
  if (extendedZone) {
    c += "[" + o.zone.ianaName + "]";
  }
  return c;
}
var defaultUnitValues = {
  month: 1,
  day: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var defaultWeekUnitValues = {
  weekNumber: 1,
  weekday: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var defaultOrdinalUnitValues = {
  ordinal: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var orderedUnits2 = ["year", "month", "day", "hour", "minute", "second", "millisecond"];
var orderedWeekUnits = [
  "weekYear",
  "weekNumber",
  "weekday",
  "hour",
  "minute",
  "second",
  "millisecond"
];
var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
function normalizeUnit(unit) {
  const normalized = {
    year: "year",
    years: "year",
    month: "month",
    months: "month",
    day: "day",
    days: "day",
    hour: "hour",
    hours: "hour",
    minute: "minute",
    minutes: "minute",
    quarter: "quarter",
    quarters: "quarter",
    second: "second",
    seconds: "second",
    millisecond: "millisecond",
    milliseconds: "millisecond",
    weekday: "weekday",
    weekdays: "weekday",
    weeknumber: "weekNumber",
    weeksnumber: "weekNumber",
    weeknumbers: "weekNumber",
    weekyear: "weekYear",
    weekyears: "weekYear",
    ordinal: "ordinal"
  }[unit.toLowerCase()];
  if (!normalized)
    throw new InvalidUnitError(unit);
  return normalized;
}
function quickDT(obj, opts) {
  const zone = normalizeZone(opts.zone, Settings.defaultZone), loc = Locale.fromObject(opts), tsNow = Settings.now();
  let ts, o;
  if (!isUndefined(obj.year)) {
    for (const u of orderedUnits2) {
      if (isUndefined(obj[u])) {
        obj[u] = defaultUnitValues[u];
      }
    }
    const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
    if (invalid) {
      return DateTime.invalid(invalid);
    }
    const offsetProvis = zone.offset(tsNow);
    [ts, o] = objToTS(obj, offsetProvis, zone);
  } else {
    ts = tsNow;
  }
  return new DateTime({ ts, zone, loc, o });
}
function diffRelative(start, end, opts) {
  const round = isUndefined(opts.round) ? true : opts.round, format = (c, unit) => {
    c = roundTo(c, round || opts.calendary ? 0 : 2, true);
    const formatter = end.loc.clone(opts).relFormatter(opts);
    return formatter.format(c, unit);
  }, differ = (unit) => {
    if (opts.calendary) {
      if (!end.hasSame(start, unit)) {
        return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
      } else
        return 0;
    } else {
      return end.diff(start, unit).get(unit);
    }
  };
  if (opts.unit) {
    return format(differ(opts.unit), opts.unit);
  }
  for (const unit of opts.units) {
    const count = differ(unit);
    if (Math.abs(count) >= 1) {
      return format(count, unit);
    }
  }
  return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
}
function lastOpts(argList) {
  let opts = {}, args;
  if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
    opts = argList[argList.length - 1];
    args = Array.from(argList).slice(0, argList.length - 1);
  } else {
    args = Array.from(argList);
  }
  return [opts, args];
}
var DateTime = class {
  constructor(config) {
    const zone = config.zone || Settings.defaultZone;
    let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null);
    this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
    let c = null, o = null;
    if (!invalid) {
      const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
      if (unchanged) {
        [c, o] = [config.old.c, config.old.o];
      } else {
        const ot = zone.offset(this.ts);
        c = tsToObj(this.ts, ot);
        invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
        c = invalid ? null : c;
        o = invalid ? null : ot;
      }
    }
    this._zone = zone;
    this.loc = config.loc || Locale.create();
    this.invalid = invalid;
    this.weekData = null;
    this.c = c;
    this.o = o;
    this.isLuxonDateTime = true;
  }
  static now() {
    return new DateTime({});
  }
  static local() {
    const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args;
    return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
  }
  static utc() {
    const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args;
    opts.zone = FixedOffsetZone.utcInstance;
    return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
  }
  static fromJSDate(date, options = {}) {
    const ts = isDate(date) ? date.valueOf() : NaN;
    if (Number.isNaN(ts)) {
      return DateTime.invalid("invalid input");
    }
    const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
    if (!zoneToUse.isValid) {
      return DateTime.invalid(unsupportedZone(zoneToUse));
    }
    return new DateTime({
      ts,
      zone: zoneToUse,
      loc: Locale.fromObject(options)
    });
  }
  static fromMillis(milliseconds, options = {}) {
    if (!isNumber(milliseconds)) {
      throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`);
    } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
      return DateTime.invalid("Timestamp out of range");
    } else {
      return new DateTime({
        ts: milliseconds,
        zone: normalizeZone(options.zone, Settings.defaultZone),
        loc: Locale.fromObject(options)
      });
    }
  }
  static fromSeconds(seconds, options = {}) {
    if (!isNumber(seconds)) {
      throw new InvalidArgumentError("fromSeconds requires a numerical input");
    } else {
      return new DateTime({
        ts: seconds * 1e3,
        zone: normalizeZone(options.zone, Settings.defaultZone),
        loc: Locale.fromObject(options)
      });
    }
  }
  static fromObject(obj, opts = {}) {
    obj = obj || {};
    const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
    if (!zoneToUse.isValid) {
      return DateTime.invalid(unsupportedZone(zoneToUse));
    }
    const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), normalized = normalizeObject(obj, normalizeUnit), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale.fromObject(opts);
    if ((containsGregor || containsOrdinal) && definiteWeekDef) {
      throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
    }
    if (containsGregorMD && containsOrdinal) {
      throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
    }
    const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor;
    let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis);
    if (useWeekData) {
      units = orderedWeekUnits;
      defaultValues = defaultWeekUnitValues;
      objNow = gregorianToWeek(objNow);
    } else if (containsOrdinal) {
      units = orderedOrdinalUnits;
      defaultValues = defaultOrdinalUnitValues;
      objNow = gregorianToOrdinal(objNow);
    } else {
      units = orderedUnits2;
      defaultValues = defaultUnitValues;
    }
    let foundFirst = false;
    for (const u of units) {
      const v = normalized[u];
      if (!isUndefined(v)) {
        foundFirst = true;
      } else if (foundFirst) {
        normalized[u] = defaultValues[u];
      } else {
        normalized[u] = objNow[u];
      }
    }
    const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
    if (invalid) {
      return DateTime.invalid(invalid);
    }
    const gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new DateTime({
      ts: tsFinal,
      zone: zoneToUse,
      o: offsetFinal,
      loc
    });
    if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
      return DateTime.invalid("mismatched weekday", `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`);
    }
    return inst;
  }
  static fromISO(text, opts = {}) {
    const [vals, parsedZone] = parseISODate(text);
    return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
  }
  static fromRFC2822(text, opts = {}) {
    const [vals, parsedZone] = parseRFC2822Date(text);
    return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
  }
  static fromHTTP(text, opts = {}) {
    const [vals, parsedZone] = parseHTTPDate(text);
    return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
  }
  static fromFormat(text, fmt, opts = {}) {
    if (isUndefined(text) || isUndefined(fmt)) {
      throw new InvalidArgumentError("fromFormat requires an input string and a format");
    }
    const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({
      locale,
      numberingSystem,
      defaultToEN: true
    }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);
    if (invalid) {
      return DateTime.invalid(invalid);
    } else {
      return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);
    }
  }
  static fromString(text, fmt, opts = {}) {
    return DateTime.fromFormat(text, fmt, opts);
  }
  static fromSQL(text, opts = {}) {
    const [vals, parsedZone] = parseSQL(text);
    return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
  }
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidDateTimeError(invalid);
    } else {
      return new DateTime({ invalid });
    }
  }
  static isDateTime(o) {
    return o && o.isLuxonDateTime || false;
  }
  static parseFormatForOpts(formatOpts, localeOpts = {}) {
    const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));
    return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join("");
  }
  static expandFormat(fmt, localeOpts = {}) {
    const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));
    return expanded.map((t) => t.val).join("");
  }
  get(unit) {
    return this[unit];
  }
  get isValid() {
    return this.invalid === null;
  }
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  get locale() {
    return this.isValid ? this.loc.locale : null;
  }
  get numberingSystem() {
    return this.isValid ? this.loc.numberingSystem : null;
  }
  get outputCalendar() {
    return this.isValid ? this.loc.outputCalendar : null;
  }
  get zone() {
    return this._zone;
  }
  get zoneName() {
    return this.isValid ? this.zone.name : null;
  }
  get year() {
    return this.isValid ? this.c.year : NaN;
  }
  get quarter() {
    return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
  }
  get month() {
    return this.isValid ? this.c.month : NaN;
  }
  get day() {
    return this.isValid ? this.c.day : NaN;
  }
  get hour() {
    return this.isValid ? this.c.hour : NaN;
  }
  get minute() {
    return this.isValid ? this.c.minute : NaN;
  }
  get second() {
    return this.isValid ? this.c.second : NaN;
  }
  get millisecond() {
    return this.isValid ? this.c.millisecond : NaN;
  }
  get weekYear() {
    return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
  }
  get weekNumber() {
    return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
  }
  get weekday() {
    return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
  }
  get ordinal() {
    return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
  }
  get monthShort() {
    return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null;
  }
  get monthLong() {
    return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null;
  }
  get weekdayShort() {
    return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null;
  }
  get weekdayLong() {
    return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null;
  }
  get offset() {
    return this.isValid ? +this.o : NaN;
  }
  get offsetNameShort() {
    if (this.isValid) {
      return this.zone.offsetName(this.ts, {
        format: "short",
        locale: this.locale
      });
    } else {
      return null;
    }
  }
  get offsetNameLong() {
    if (this.isValid) {
      return this.zone.offsetName(this.ts, {
        format: "long",
        locale: this.locale
      });
    } else {
      return null;
    }
  }
  get isOffsetFixed() {
    return this.isValid ? this.zone.isUniversal : null;
  }
  get isInDST() {
    if (this.isOffsetFixed) {
      return false;
    } else {
      return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset;
    }
  }
  get isInLeapYear() {
    return isLeapYear(this.year);
  }
  get daysInMonth() {
    return daysInMonth(this.year, this.month);
  }
  get daysInYear() {
    return this.isValid ? daysInYear(this.year) : NaN;
  }
  get weeksInWeekYear() {
    return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
  }
  resolvedLocaleOptions(opts = {}) {
    const { locale, numberingSystem, calendar } = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this);
    return { locale, numberingSystem, outputCalendar: calendar };
  }
  toUTC(offset2 = 0, opts = {}) {
    return this.setZone(FixedOffsetZone.instance(offset2), opts);
  }
  toLocal() {
    return this.setZone(Settings.defaultZone);
  }
  setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
    zone = normalizeZone(zone, Settings.defaultZone);
    if (zone.equals(this.zone)) {
      return this;
    } else if (!zone.isValid) {
      return DateTime.invalid(unsupportedZone(zone));
    } else {
      let newTS = this.ts;
      if (keepLocalTime || keepCalendarTime) {
        const offsetGuess = zone.offset(this.ts);
        const asObj = this.toObject();
        [newTS] = objToTS(asObj, offsetGuess, zone);
      }
      return clone2(this, { ts: newTS, zone });
    }
  }
  reconfigure({ locale, numberingSystem, outputCalendar } = {}) {
    const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });
    return clone2(this, { loc });
  }
  setLocale(locale) {
    return this.reconfigure({ locale });
  }
  set(values) {
    if (!this.isValid)
      return this;
    const normalized = normalizeObject(values, normalizeUnit), settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber;
    if ((containsGregor || containsOrdinal) && definiteWeekDef) {
      throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
    }
    if (containsGregorMD && containsOrdinal) {
      throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
    }
    let mixed;
    if (settingWeekStuff) {
      mixed = weekToGregorian(__spreadValues(__spreadValues({}, gregorianToWeek(this.c)), normalized));
    } else if (!isUndefined(normalized.ordinal)) {
      mixed = ordinalToGregorian(__spreadValues(__spreadValues({}, gregorianToOrdinal(this.c)), normalized));
    } else {
      mixed = __spreadValues(__spreadValues({}, this.toObject()), normalized);
      if (isUndefined(normalized.day)) {
        mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
      }
    }
    const [ts, o] = objToTS(mixed, this.o, this.zone);
    return clone2(this, { ts, o });
  }
  plus(duration2) {
    if (!this.isValid)
      return this;
    const dur = Duration.fromDurationLike(duration2);
    return clone2(this, adjustTime(this, dur));
  }
  minus(duration2) {
    if (!this.isValid)
      return this;
    const dur = Duration.fromDurationLike(duration2).negate();
    return clone2(this, adjustTime(this, dur));
  }
  startOf(unit) {
    if (!this.isValid)
      return this;
    const o = {}, normalizedUnit = Duration.normalizeUnit(unit);
    switch (normalizedUnit) {
      case "years":
        o.month = 1;
      case "quarters":
      case "months":
        o.day = 1;
      case "weeks":
      case "days":
        o.hour = 0;
      case "hours":
        o.minute = 0;
      case "minutes":
        o.second = 0;
      case "seconds":
        o.millisecond = 0;
        break;
      case "milliseconds":
        break;
    }
    if (normalizedUnit === "weeks") {
      o.weekday = 1;
    }
    if (normalizedUnit === "quarters") {
      const q = Math.ceil(this.month / 3);
      o.month = (q - 1) * 3 + 1;
    }
    return this.set(o);
  }
  endOf(unit) {
    return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit).minus(1) : this;
  }
  toFormat(fmt, opts = {}) {
    return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID3;
  }
  toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
    return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID3;
  }
  toLocaleParts(opts = {}) {
    return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
  }
  toISO({
    format = "extended",
    suppressSeconds = false,
    suppressMilliseconds = false,
    includeOffset = true,
    extendedZone = false
  } = {}) {
    if (!this.isValid) {
      return null;
    }
    const ext = format === "extended";
    let c = toISODate(this, ext);
    c += "T";
    c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
    return c;
  }
  toISODate({ format = "extended" } = {}) {
    if (!this.isValid) {
      return null;
    }
    return toISODate(this, format === "extended");
  }
  toISOWeekDate() {
    return toTechFormat(this, "kkkk-'W'WW-c");
  }
  toISOTime({
    suppressMilliseconds = false,
    suppressSeconds = false,
    includeOffset = true,
    includePrefix = false,
    extendedZone = false,
    format = "extended"
  } = {}) {
    if (!this.isValid) {
      return null;
    }
    let c = includePrefix ? "T" : "";
    return c + toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
  }
  toRFC2822() {
    return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
  }
  toHTTP() {
    return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
  }
  toSQLDate() {
    if (!this.isValid) {
      return null;
    }
    return toISODate(this, true);
  }
  toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {
    let fmt = "HH:mm:ss.SSS";
    if (includeZone || includeOffset) {
      if (includeOffsetSpace) {
        fmt += " ";
      }
      if (includeZone) {
        fmt += "z";
      } else if (includeOffset) {
        fmt += "ZZ";
      }
    }
    return toTechFormat(this, fmt, true);
  }
  toSQL(opts = {}) {
    if (!this.isValid) {
      return null;
    }
    return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
  }
  toString() {
    return this.isValid ? this.toISO() : INVALID3;
  }
  valueOf() {
    return this.toMillis();
  }
  toMillis() {
    return this.isValid ? this.ts : NaN;
  }
  toSeconds() {
    return this.isValid ? this.ts / 1e3 : NaN;
  }
  toUnixInteger() {
    return this.isValid ? Math.floor(this.ts / 1e3) : NaN;
  }
  toJSON() {
    return this.toISO();
  }
  toBSON() {
    return this.toJSDate();
  }
  toObject(opts = {}) {
    if (!this.isValid)
      return {};
    const base = __spreadValues({}, this.c);
    if (opts.includeConfig) {
      base.outputCalendar = this.outputCalendar;
      base.numberingSystem = this.loc.numberingSystem;
      base.locale = this.loc.locale;
    }
    return base;
  }
  toJSDate() {
    return new Date(this.isValid ? this.ts : NaN);
  }
  diff(otherDateTime, unit = "milliseconds", opts = {}) {
    if (!this.isValid || !otherDateTime.isValid) {
      return Duration.invalid("created by diffing an invalid DateTime");
    }
    const durOpts = __spreadValues({ locale: this.locale, numberingSystem: this.numberingSystem }, opts);
    const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff_default(earlier, later, units, durOpts);
    return otherIsLater ? diffed.negate() : diffed;
  }
  diffNow(unit = "milliseconds", opts = {}) {
    return this.diff(DateTime.now(), unit, opts);
  }
  until(otherDateTime) {
    return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
  }
  hasSame(otherDateTime, unit) {
    if (!this.isValid)
      return false;
    const inputMs = otherDateTime.valueOf();
    const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });
    return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);
  }
  equals(other) {
    return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
  }
  toRelative(options = {}) {
    if (!this.isValid)
      return null;
    const base = options.base || DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0;
    let units = ["years", "months", "days", "hours", "minutes", "seconds"];
    let unit = options.unit;
    if (Array.isArray(options.unit)) {
      units = options.unit;
      unit = void 0;
    }
    return diffRelative(base, this.plus(padding), __spreadProps(__spreadValues({}, options), {
      numeric: "always",
      units,
      unit
    }));
  }
  toRelativeCalendar(options = {}) {
    if (!this.isValid)
      return null;
    return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, __spreadProps(__spreadValues({}, options), {
      numeric: "auto",
      units: ["years", "months", "days"],
      calendary: true
    }));
  }
  static min(...dateTimes) {
    if (!dateTimes.every(DateTime.isDateTime)) {
      throw new InvalidArgumentError("min requires all arguments be DateTimes");
    }
    return bestBy(dateTimes, (i) => i.valueOf(), Math.min);
  }
  static max(...dateTimes) {
    if (!dateTimes.every(DateTime.isDateTime)) {
      throw new InvalidArgumentError("max requires all arguments be DateTimes");
    }
    return bestBy(dateTimes, (i) => i.valueOf(), Math.max);
  }
  static fromFormatExplain(text, fmt, options = {}) {
    const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({
      locale,
      numberingSystem,
      defaultToEN: true
    });
    return explainFromTokens(localeToUse, text, fmt);
  }
  static fromStringExplain(text, fmt, options = {}) {
    return DateTime.fromFormatExplain(text, fmt, options);
  }
  static get DATE_SHORT() {
    return DATE_SHORT;
  }
  static get DATE_MED() {
    return DATE_MED;
  }
  static get DATE_MED_WITH_WEEKDAY() {
    return DATE_MED_WITH_WEEKDAY;
  }
  static get DATE_FULL() {
    return DATE_FULL;
  }
  static get DATE_HUGE() {
    return DATE_HUGE;
  }
  static get TIME_SIMPLE() {
    return TIME_SIMPLE;
  }
  static get TIME_WITH_SECONDS() {
    return TIME_WITH_SECONDS;
  }
  static get TIME_WITH_SHORT_OFFSET() {
    return TIME_WITH_SHORT_OFFSET;
  }
  static get TIME_WITH_LONG_OFFSET() {
    return TIME_WITH_LONG_OFFSET;
  }
  static get TIME_24_SIMPLE() {
    return TIME_24_SIMPLE;
  }
  static get TIME_24_WITH_SECONDS() {
    return TIME_24_WITH_SECONDS;
  }
  static get TIME_24_WITH_SHORT_OFFSET() {
    return TIME_24_WITH_SHORT_OFFSET;
  }
  static get TIME_24_WITH_LONG_OFFSET() {
    return TIME_24_WITH_LONG_OFFSET;
  }
  static get DATETIME_SHORT() {
    return DATETIME_SHORT;
  }
  static get DATETIME_SHORT_WITH_SECONDS() {
    return DATETIME_SHORT_WITH_SECONDS;
  }
  static get DATETIME_MED() {
    return DATETIME_MED;
  }
  static get DATETIME_MED_WITH_SECONDS() {
    return DATETIME_MED_WITH_SECONDS;
  }
  static get DATETIME_MED_WITH_WEEKDAY() {
    return DATETIME_MED_WITH_WEEKDAY;
  }
  static get DATETIME_FULL() {
    return DATETIME_FULL;
  }
  static get DATETIME_FULL_WITH_SECONDS() {
    return DATETIME_FULL_WITH_SECONDS;
  }
  static get DATETIME_HUGE() {
    return DATETIME_HUGE;
  }
  static get DATETIME_HUGE_WITH_SECONDS() {
    return DATETIME_HUGE_WITH_SECONDS;
  }
};
function friendlyDateTime(dateTimeish) {
  if (DateTime.isDateTime(dateTimeish)) {
    return dateTimeish;
  } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
    return DateTime.fromJSDate(dateTimeish);
  } else if (dateTimeish && typeof dateTimeish === "object") {
    return DateTime.fromObject(dateTimeish);
  } else {
    throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`);
  }
}

// src/services/dateService/DateService.ts
var DateService = class extends AbstractService {
  getDate(metadataDate, fantasyCalendarCategory, component) {
    if ((metadataDate == void 0 || metadataDate === "") && fantasyCalendarCategory === void 0)
      return void 0;
    const isFantasyCalendar = component.campaign.calendar === 1 /* FantasyCalendar */ && fantasyCalendarCategory !== void 0;
    let responseDate;
    if (isFantasyCalendar) {
      const calendar = component.campaign.fantasyCalendar;
      if (calendar === void 0)
        return void 0;
      let events = [];
      if (fantasyCalendarCategory === "current" /* CurrentDate */) {
        responseDate = calendar.current;
        if (responseDate === void 0 || responseDate.year === void 0)
          return void 0;
      } else {
        const categories = calendar.categories.filter((category) => category.name === fantasyCalendarCategory);
        if (categories.length === 0)
          return void 0;
        events = calendar.events.filter((event) => event.note === component.file.path.slice(0, -3) && event.category === categories[0].id);
        if (events.length !== 1)
          return void 0;
        responseDate = events[0].date;
      }
    } else {
      if (metadataDate == void 0 || metadataDate === "")
        return void 0;
      responseDate = DateTime.fromISO(metadataDate.toString()).toJSDate();
    }
    return { date: responseDate, isFantasyCalendar, category: fantasyCalendarCategory };
  }
  getReadableDate(date, component) {
    if (date === void 0)
      return "";
    if (date.isFantasyCalendar) {
      const fantasyDate = date.date;
      const fantasyCalendar = component.campaign.fantasyCalendar;
      if (fantasyDate === void 0 || fantasyCalendar === void 0)
        return "";
      const day = window.FantasyCalendarAPI.getDay(fantasyDate, fantasyCalendar);
      return day.displayDate;
    } else {
      return date.date.toDateString();
    }
  }
  getAge(dob, death, currentDate, component) {
    if (dob === void 0)
      return void 0;
    const deathOrNow = death !== void 0 ? death : currentDate;
    if (deathOrNow === void 0)
      return void 0;
    if (dob.isFantasyCalendar) {
      const end = deathOrNow.date;
      const start = dob.date;
      let response = end.year - start.year;
      if (end.month < start.month) {
        response--;
      } else if (end.month === start.month) {
        if (end.day < start.day) {
          response--;
        }
      }
      return response;
    } else {
      const end = DateTime.fromISO(deathOrNow.date.toISOString());
      const start = DateTime.fromISO(dob.date.toISOString());
      return Math.floor(end.diff(start, "years").years);
    }
  }
  formatMinutesSeconds(durationInSeconds) {
    if (durationInSeconds === void 0)
      return "00:00:00";
    const hours = Math.floor(durationInSeconds / 3600);
    const minutes = Math.floor((durationInSeconds - hours * 3600) / 60);
    const seconds = Math.floor(durationInSeconds - hours * 3600 - minutes * 60);
    return this._padHMS(hours) + ":" + this._padHMS(minutes) + ":" + this._padHMS(seconds);
  }
  _padHMS(duration2) {
    if (duration2 === 0)
      return "00";
    if (duration2 < 10)
      return "0" + duration2.toString();
    return duration2.toString();
  }
};

// src/components/campaign/abstracts/AbstractCampaignData.ts
var AbstractCampaignData = class extends PlotsAbtOnly {
  get date() {
    var _a;
    if (this.calendar === 0 /* Gregorian */)
      return this.api.service(DateService).getDate((_a = this.metadata.data) == null ? void 0 : _a.date, "current" /* CurrentDate */, this);
    const fantasyCalendar = this.fantasyCalendar;
    if (fantasyCalendar === void 0)
      return void 0;
    return { date: fantasyCalendar.current, isFantasyCalendar: true };
  }
  get currentAdventureId() {
    if (this.metadata.data.currentAdventureId == void 0 || this.metadata.data.currentAdventureId === "")
      return void 0;
    let response = void 0;
    try {
      response = this.api.database.readById(this.metadata.data.currentAdventureId).index;
    } catch (e) {
    }
    return response;
  }
  get currentActId() {
    if (this.metadata.data.currentActId == void 0 || this.metadata.data.currentActId === "")
      return void 0;
    let response = void 0;
    try {
      response = this.api.database.readById(this.metadata.data.currentActId).index;
    } catch (e) {
    }
    return response;
  }
  get currentSessionId() {
    if (this.metadata.data.currentSessionId == void 0 || this.metadata.data.currentSessionId === "")
      return void 0;
    let response = void 0;
    try {
      response = this.api.database.readById(this.metadata.data.currentSessionId).index;
    } catch (e) {
    }
    return response;
  }
  get calendar() {
    if (this.frontmatter["fc-calendar"] === void 0)
      return 0 /* Gregorian */;
    return 1 /* FantasyCalendar */;
  }
  get fantasyCalendar() {
    if (this.calendar === 0 /* Gregorian */)
      return void 0;
    const calendars = this.api.service(FantasyCalendarService).calendars;
    if (calendars.length === 1)
      return calendars[0];
    const searchedCalendar = calendars.filter((calendar) => calendar.name === this.frontmatter["fc-calendar"]);
    if (searchedCalendar.length === 1)
      return searchedCalendar[0];
    return void 0;
  }
};

// src/components/campaign/models/CampaignModel.ts
var CampaignModel = class extends AbstractCampaignData {
  constructor() {
    super(...arguments);
    this.stage = 0 /* Plot */;
  }
  get folder() {
    const lastSlashPosition = this.file.path.lastIndexOf("/");
    return lastSlashPosition !== -1 ? this.file.path.substring(0, lastSlashPosition + 1) : "/";
  }
  getRelationships(database) {
    const response = super.getRelationships(database);
    this.api.database.read((model) => model.index.campaignId === this.index.campaignId).forEach((model) => {
      response.add(this.api.service(RelationshipService).createRelationship(32 /* Hierarchy */, model.file.path, void 0, model));
    });
    return response;
  }
};

// src/components/session/abstracts/AbstractSessionData.ts
var AbstractSessionData = class extends Plots {
  get irl() {
    var _a;
    return this.api.service(DateService).getDate((_a = this.metadata.data) == null ? void 0 : _a.irl, void 0, this);
  }
  get abtStage() {
    var _a;
    if (((_a = this.metadata.data) == null ? void 0 : _a.abtStage) == void 0)
      return void 0;
    return this.api.service(PlotService).getAbtStage(this.metadata.data.abtStage);
  }
  get targetDuration() {
    var _a;
    return (_a = this.metadata.data) == null ? void 0 : _a.targetDuration;
  }
};

// src/components/session/models/SessionModel.ts
var SessionModel = class extends AbstractSessionData {
  constructor() {
    super(...arguments);
    this.stage = 2 /* Run */;
    this._sceneNoteListPattern = void 0;
  }
  initialiseData() {
    return __async(this, null, function* () {
      const pattern = ["### Storyteller Diary", "-", "", "###"];
      this._fileManipulator = yield this.api.service(FileManipulatorService).read(this.file);
      if (this._fileManipulator !== void 0)
        this._sceneNoteListPattern = yield yield this.api.service(FileManipulatorService).patternPosition(this._fileManipulator, pattern);
    });
  }
  get isSceneNoteListAvailable() {
    return this._sceneNoteListPattern !== void 0;
  }
  replaceSceneNoteList(content) {
    return __async(this, null, function* () {
      if (this._fileManipulator !== void 0 && this._sceneNoteListPattern !== void 0)
        this.api.service(FileManipulatorService).replacePattern(this._fileManipulator, this._sceneNoteListPattern, content);
    });
  }
  get nextSession() {
    return this._adjacentSession(true);
  }
  get previousSession() {
    return this._adjacentSession(false);
  }
  _adjacentSession(next) {
    try {
      return this.api.database.readNeighbour(16 /* Session */, this.index, !next);
    } catch (e) {
      return null;
    }
  }
  getRelationships(database) {
    const response = new RelationshipList();
    super.getRelationships(database).forEach((relationship) => {
      response.add(relationship);
    });
    this.api.database.read((model) => model.index.campaignId === this.index.campaignId && model.session !== void 0 && model.session.index === this.index).forEach((model) => {
      model.getRelationships().forEach((sceneRelationship) => {
        if (sceneRelationship.component !== void 0)
          response.add(this.api.service(RelationshipService).createRelationship(32 /* Hierarchy */, sceneRelationship.path, void 0, sceneRelationship.component));
      });
      response.add(this.api.service(RelationshipService).createRelationship(32 /* Hierarchy */, model.file.path, void 0, model));
    });
    return response;
  }
  compactScenePositions(skipScene, scenes) {
    return __async(this, null, function* () {
      if (scenes === void 0) {
        scenes = this.api.database.read((scene) => {
          var _a;
          return scene.index.type === 8 /* Scene */ && ((_a = scene.session) == null ? void 0 : _a.index.id) === this.index.id && (skipScene !== void 0 ? scene.index.id !== skipScene : true);
        }).sort(this.api.service(SorterService).create([
          new SorterComparisonElement((scene) => scene.positionInSession)
        ]));
      }
      if (scenes !== void 0) {
        for (let index = 0; index < scenes.length; index++) {
          if (scenes[index].positionInSession !== index + 1) {
            this.api.service(CodeblockService).addOrUpdate("data.positionInSession", index + 1, scenes[index].file);
          }
        }
      }
    });
  }
};

// src/components/session/modals/SceneSelectionModal.ts
var SceneSelectionModal = class extends AbstractModal {
  constructor(api, _session) {
    super(api);
    this._session = _session;
    this._scenesEls = /* @__PURE__ */ new Map();
    this._loadAvailableScenes();
  }
  onOpen() {
    super.onOpen();
    const { contentEl } = this;
    contentEl.empty();
    contentEl.addClass("rpg-manager-modal");
    contentEl.createEl("h2", { text: "SceneModel Selector" });
    contentEl.createEl("p", { text: 'Select the scenes to add to the session "' + this._session.file.basename + '"' });
    const actSelectorContainerEl = contentEl.createDiv();
    actSelectorContainerEl.createDiv({ text: "Limit scenes to a specific act" });
    this._actSelectorEl = actSelectorContainerEl.createEl("select");
    this._actSelectorEl.createEl("option", {
      text: "",
      value: ""
    });
    const acts = this.api.database.read((act) => act.index.type === 4 /* Act */ && act.index.campaignId === this._session.index.campaignId).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((act) => act.file.stat.mtime, 1 /* Descending */)
    ]));
    acts.forEach((act) => {
      this._actSelectorEl.createEl("option", { text: act.file.basename, value: act.file.path });
    });
    this._actSelectorEl.addEventListener("change", () => {
      if (this._actSelectorEl.value !== "") {
        this._selectedAct = this.api.database.readByPath(this._actSelectorEl.value);
      } else {
        this._selectedAct = void 0;
      }
      this._loadAvailableScenes();
      this._populateAvailableScenes();
    });
    this._sessionContainerEl = contentEl.createDiv({ cls: "rpg-manager-modal-scene-container" });
    this._populateAvailableScenes();
    const scenesSelectionButtonEl = contentEl.createEl("button", { text: 'Add selected scenes to session "' + this._session.file.basename + '"' });
    scenesSelectionButtonEl.addEventListener("click", () => {
      this._addScenes().then(() => {
        this._session.touch(true);
        this.app.workspace.trigger("rpgmanager:force-refresh-views");
        this.close();
      });
    });
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
    super.onClose();
  }
  _loadAvailableScenes() {
    this._availableScenes = this.api.database.read((scene) => {
      var _a;
      return scene.index.type === 8 /* Scene */ && scene.index.campaignId === this._session.index.campaignId && (this._selectedAct !== void 0 ? scene.index.parentId === this._selectedAct.index.parentId : true) && (scene.session === void 0 || ((_a = scene.session) == null ? void 0 : _a.index.id) === this._session.index.id);
    }).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((scene) => scene.index.parentPosition),
      new SorterComparisonElement((scene) => scene.index.positionInParent)
    ]));
  }
  _populateAvailableScenes() {
    let populateInitialScenes = false;
    if (this._initialScenesEls === void 0) {
      this._initialScenesEls = /* @__PURE__ */ new Map();
      populateInitialScenes = true;
    }
    if (this._sessionContainerEl.childNodes.length > 0) {
      const keysToRemove = [];
      this._sessionContainerEl.childNodes.forEach((value, key, parent) => {
        const option = value.childNodes[0];
        if (!option.checked)
          keysToRemove.push(key);
      });
      keysToRemove.sort((n1, n2) => n2 - n1).forEach((key) => {
        this._sessionContainerEl.childNodes[key].remove();
      });
    }
    this._availableScenes.forEach((scene) => {
      var _a;
      if (!this._scenesEls.has(scene.file)) {
        const checkboxDiv = this._sessionContainerEl.createDiv();
        const checkbox = checkboxDiv.createEl("input");
        checkbox.type = "checkbox";
        checkbox.value = scene.file.path;
        checkbox.id = scene.file.basename;
        if (((_a = scene.session) == null ? void 0 : _a.index.id) === this._session.index.id) {
          checkbox.checked = true;
          this._scenesEls.set(scene.file, checkbox);
          if (populateInitialScenes)
            this._initialScenesEls.set(scene.file.path, checkbox.checked);
        }
        checkbox.addEventListener("change", () => {
          if (checkbox.checked) {
            this._scenesEls.set(scene.file, checkbox);
          }
        });
        const checkboxLabel = checkboxDiv.createEl("label", { text: scene.file.basename });
        checkboxLabel.htmlFor = scene.file.basename;
      }
    });
  }
  _addScenes() {
    return __async(this, null, function* () {
      let positionInSession = 0;
      const scenes = this.api.database.read((scene) => {
        var _a;
        return scene.index.type === 8 /* Scene */ && ((_a = scene.session) == null ? void 0 : _a.index.id) === this._session.index.id;
      });
      for (let index = 0; index < scenes.length; index++) {
        const scenePosition = scenes[index].positionInSession;
        if (scenePosition !== void 0 && scenePosition >= positionInSession)
          positionInSession = scenePosition + 1;
      }
      if (positionInSession > 0)
        positionInSession--;
      const finalScenes = [];
      for (const [file, sceneEl] of this._scenesEls) {
        const initialSceneCheked = yield this._initialScenesEls.get(file.path);
        if (sceneEl.checked === true) {
          const scene = this.api.database.readByPath(file.path);
          if (scene !== void 0)
            finalScenes.push(scene);
        }
        if (initialSceneCheked === void 0 || sceneEl.checked !== initialSceneCheked) {
          if (sceneEl.checked === true)
            positionInSession++;
          const keyValues = /* @__PURE__ */ new Map();
          keyValues.set("data.sessionId", sceneEl.checked === true ? this._session.index.id : void 0);
          keyValues.set("data.positionInSession", sceneEl.checked === true ? positionInSession : void 0);
          yield this.api.service(CodeblockService).addOrUpdateMultiple(keyValues, file);
        }
      }
      this._session.compactScenePositions(void 0, finalScenes);
    });
  }
};

// src/services/analyserService/enums/SceneType.ts
var SceneType = /* @__PURE__ */ ((SceneType2) => {
  SceneType2[SceneType2["Action"] = 0] = "Action";
  SceneType2[SceneType2["Combat"] = 1] = "Combat";
  SceneType2[SceneType2["Encounter"] = 2] = "Encounter";
  SceneType2[SceneType2["Exposition"] = 3] = "Exposition";
  SceneType2[SceneType2["Investigation"] = 4] = "Investigation";
  SceneType2[SceneType2["Planning"] = 5] = "Planning";
  SceneType2[SceneType2["Preparation"] = 6] = "Preparation";
  SceneType2[SceneType2["Recap"] = 7] = "Recap";
  SceneType2[SceneType2["SocialCombat"] = 8] = "SocialCombat";
  return SceneType2;
})(SceneType || {});
var sceneTypeDescription = /* @__PURE__ */ new Map([
  [0 /* Action */, "Action: the pcs have to do something (active)"],
  [1 /* Combat */, "Combat: fight scene (active)"],
  [2 /* Encounter */, "Encounter: An NPC in involved"],
  [3 /* Exposition */, "Exposition: Storyteller showtime"],
  [4 /* Investigation */, "Investigation: Pcs analyse a scene (active)"],
  [5 /* Planning */, "Planning: Pcs plans something (not exciteable)"],
  [6 /* Preparation */, "Preparation: Pcs do something (active,not exciteable)"],
  [7 /* Recap */, "Recap: Pcs talks amongst themselves (not exciteable)"],
  [8 /* SocialCombat */, "Social Combat: PCs need to get something from NPCs (active)"]
]);
var activeSceneTypes = /* @__PURE__ */ new Map([
  [0 /* Action */, true],
  [1 /* Combat */, true],
  [2 /* Encounter */, false],
  [3 /* Exposition */, false],
  [4 /* Investigation */, true],
  [5 /* Planning */, false],
  [6 /* Preparation */, true],
  [7 /* Recap */, false],
  [8 /* SocialCombat */, true]
]);

// src/services/analyserService/analysers/AnalyserData.ts
var AnalyserData = class {
  constructor() {
    this.abtStage = void 0;
    this.dataLength = 0;
    this.totalRunningTime = 0;
    this.totalActiveScenes = 0;
    this.totalRepetitiveScenes = 0;
    this.totalExpectedRunningTime = 0;
    this.totalExpectedExcitmentDuration = 0;
    this.totalTargetDuration = 0;
    this.dataTypeUsed = /* @__PURE__ */ new Map();
    this._previousType = void 0;
  }
  get isValid() {
    return this.dataLength !== 0;
  }
  set dataCount(count) {
    this.dataLength = count;
  }
  addExpectedRunningTime(duration2) {
    this.totalExpectedRunningTime += duration2;
  }
  addExpectedExcitmentDuration(duration2) {
    this.totalExpectedExcitmentDuration += duration2;
  }
  addActiveScene() {
    this.totalActiveScenes++;
  }
  addSceneType(type) {
    var _a;
    if (type !== void 0) {
      this.dataTypeUsed.set(type, ((_a = this.dataTypeUsed.get(type)) != null ? _a : 0) + 1);
      if (this._previousType === type) {
        this.totalRepetitiveScenes++;
      } else {
        this._previousType = type;
      }
    }
  }
};

// src/services/analyserService/views/abstract/AbstractAnalyserView.ts
var AbstractAnalyserView = class {
  constructor(api, type) {
    this.api = api;
    this.type = type;
    this.descriptions = /* @__PURE__ */ new Map([
      [0 /* Activity */, /* @__PURE__ */ new Map([
        [1 /* CriticallyHigh */, "Really, %score% scenes out of %maximumScore% are active, you should aim for %ideal%"],
        [2 /* High */, "%score% scenes out of %maximumScore% are active, you should aim for %ideal%"],
        [3 /* Correct */, "%score% scenes out of %maximumScore% are active, you should aim for %ideal%"],
        [4 /* Low */, "Only  %score% scenes out of %maximumScore% are active, you should aim for %ideal%"],
        [5 /* CriticallyLow */, "Just %score% scenes out of %maximumScore% are active, you should aim for %ideal%"]
      ])],
      [1 /* Duration */, /* @__PURE__ */ new Map([
        [1 /* CriticallyHigh */, "Really, %percentage%% longer than your target"],
        [2 /* High */, "%percentage%% longer than your target"],
        [3 /* Correct */, "%percentage%% longer or shorter than your target"],
        [4 /* Low */, "%percentage%% shorter than your target"],
        [5 /* CriticallyLow */, "%percentage%% shorter than your target"]
      ])],
      [2 /* Excitement */, /* @__PURE__ */ new Map([
        [1 /* CriticallyHigh */, "%score% are exciting, you should aim for %ideal%"],
        [2 /* High */, "%score% are exciting, you should aim for %ideal%"],
        [3 /* Correct */, "%score% are exciting, you should aim for %ideal%"],
        [4 /* Low */, "Only %score% are exciting, you should aim for %ideal%"],
        [5 /* CriticallyLow */, "Just %score% are exciting, you should aim for %ideal%"]
      ])],
      [3 /* Interest */, /* @__PURE__ */ new Map([
        [5 /* CriticallyLow */, "Really, %score% scenes type repeated in %maximumScore% scenes. Keep it below %ideal%."],
        [4 /* Low */, "%score% scenes type repeated in %maximumScore% scenes. Try to keep it below %ideal%"],
        [3 /* Correct */, "%score% scenes type repeated in %maximumScore% scenes. Try to keep it below %ideal%"]
      ])],
      [5 /* Variety */, /* @__PURE__ */ new Map([
        [3 /* Correct */, "%score% different type of scenes are used, you should aim for %ideal%"],
        [4 /* Low */, "Only %score% different type of scenes are used, you should aim for %ideal%"],
        [5 /* CriticallyLow */, "Just %score% different type of scenes are used, you should aim for %ideal%"]
      ])]
    ]);
    this.subtitles = /* @__PURE__ */ new Map([
      [0 /* Activity */, /* @__PURE__ */ new Map([
        [1 /* CriticallyHigh */, "Too many active scenes"],
        [2 /* High */, "Maybe too many active scenes"],
        [3 /* Correct */, "The amount of active scenes is balanced"],
        [4 /* Low */, "Maybe not enough active scenes"],
        [5 /* CriticallyLow */, "Not enough active scenes"]
      ])],
      [1 /* Duration */, /* @__PURE__ */ new Map([
        [1 /* CriticallyHigh */, "The session is going to be too long"],
        [2 /* High */, "The session might be too long"],
        [3 /* Correct */, "The expected duration is in line with your target session duration"],
        [4 /* Low */, "The session might be short"],
        [5 /* CriticallyLow */, "The session is too short"]
      ])],
      [2 /* Excitement */, /* @__PURE__ */ new Map([
        [1 /* CriticallyHigh */, "Too much excitement"],
        [2 /* High */, "Maybe too much excitement"],
        [3 /* Correct */, "The amount of exciting time is balanced"],
        [4 /* Low */, "Maybe not enough excitement"],
        [5 /* CriticallyLow */, "Not enough excitement"]
      ])],
      [3 /* Interest */, /* @__PURE__ */ new Map([
        [5 /* CriticallyLow */, "Repetitive"],
        [4 /* Low */, "Maybe a bit repetitive"],
        [3 /* Correct */, "The scenes are not repetitive"]
      ])],
      [5 /* Variety */, /* @__PURE__ */ new Map([
        [3 /* Correct */, "There is a good variety of scenes"],
        [4 /* Low */, "Maybe not enough variety"],
        [5 /* CriticallyLow */, "Not enough variety"]
      ])]
    ]);
  }
  transformTime(duration2) {
    if (duration2 === void 0)
      return "00:00";
    const hours = Math.floor(duration2 / (60 * 60));
    const minutes = Math.floor((duration2 - hours * (60 * 60)) / 60);
    return (hours < 10 ? "0" + hours.toString() : hours.toString()) + ":" + (minutes < 10 ? "0" + minutes.toString() : minutes.toString());
  }
  prepareDescription(percentage, score, maximumScore, descriptionTemplate, ideal, type = void 0) {
    if (descriptionTemplate === void 0 || descriptionTemplate === "")
      return "";
    let response = descriptionTemplate;
    if (percentage !== void 0)
      response = response.replace("%percentage%", percentage.toString());
    if (score !== void 0)
      response = response.replace("%score%", score.toString());
    if (maximumScore !== void 0)
      response = response.replace("%maximumScore%", maximumScore.toString());
    if (type !== void 0)
      response = response.replace("%type%", ComponentType[type]);
    if (ideal !== void 0)
      response = response.replace("%ideal%", ideal.toString());
    return response;
  }
  addThresholdClass(threshold, containerEl) {
    switch (threshold) {
      case 1 /* CriticallyHigh */:
        containerEl.addClass("perfect");
        break;
      case 2 /* High */:
        containerEl.addClass("balanced");
        break;
      case 4 /* Low */:
        containerEl.addClass("warning");
        break;
      case 5 /* CriticallyLow */:
        containerEl.addClass("error");
        break;
      case 3 /* Correct */:
        containerEl.addClass("normal");
        break;
    }
  }
  addThresholdErrorClass(threshold, containerEl) {
    switch (threshold) {
      case 3 /* Correct */:
        containerEl.addClass("perfect");
        break;
      case 1 /* CriticallyHigh */:
        containerEl.addClass("error");
        break;
      case 2 /* High */:
        containerEl.addClass("warning");
        break;
      case 4 /* Low */:
        containerEl.addClass("warning");
        break;
      case 5 /* CriticallyLow */:
        containerEl.addClass("error");
        break;
    }
  }
};

// src/services/analyserService/views/AnalyserVisualView.ts
var import_obsidian21 = require("obsidian");
var AnalyserVisualView = class extends AbstractAnalyserView {
  constructor() {
    super(...arguments);
    this._description = /* @__PURE__ */ new Map([
      [void 0, "Score"],
      [0 /* Activity */, "Activity"],
      [1 /* Duration */, "Duration"],
      [2 /* Excitement */, "Excitement"],
      [3 /* Interest */, "Interest"],
      [5 /* Variety */, "Variety"],
      [4 /* Timing */, "Timing"]
    ]);
  }
  render(report, containerEl) {
    var _a;
    if (!report.isValid)
      return;
    const analyserEl = containerEl.createDiv({ cls: "rpgm-new-analyser centred" });
    const analyserContainerEl = analyserEl.createDiv({ cls: "analyser-container clearfix" });
    this.addCircle(analyserContainerEl, report.percentage, report.thresholdType, true, "Score");
    if (report.durationPercentage === 0 && isNaN(report.durationPercentage))
      this.addCircle(analyserContainerEl, report.durationPercentage, report.durationThreshold, true, (_a = this._description.get(void 0)) != null ? _a : "");
    report.details.forEach((reportDetail) => {
      var _a2;
      if (reportDetail.isRelevant === false)
        return;
      this.addCircle(analyserContainerEl, reportDetail.percentage, reportDetail.thresholdType, reportDetail.isHighBetter, (_a2 = this._description.get(reportDetail.detailType)) != null ? _a2 : "");
    });
  }
  addCircle(containerEl, percentage, threshold, isHigerBetter, description) {
    const response = containerEl.createDiv({ cls: "circle-container" });
    const circleEl = response.createDiv({ cls: " c100 p" + percentage.toString() + " small" });
    circleEl.createSpan({ text: percentage.toString() + "%" });
    const sliceEl = circleEl.createDiv({ cls: "slice" });
    sliceEl.createDiv({ cls: "bar" });
    sliceEl.createDiv({ cls: "fill" });
    const circleDescriptionEl = response.createDiv({ cls: "description" });
    import_obsidian21.MarkdownRenderer.renderMarkdown(description, circleDescriptionEl, "", null);
    if (isHigerBetter) {
      this.addThresholdClass(threshold, circleEl);
      this.addThresholdClass(threshold, circleDescriptionEl);
    } else {
      this.addThresholdErrorClass(threshold, circleEl);
      this.addThresholdErrorClass(threshold, circleDescriptionEl);
    }
    return response;
  }
};

// src/services/analyserService/views/AnalyserExtendedView.ts
var AnalyserExtendedView = class extends AbstractAnalyserView {
  constructor() {
    super(...arguments);
    this.titles = /* @__PURE__ */ new Map([
      [void 0, "Analysis score %percentage%%"],
      [0 /* Activity */, "Activity accuracy: %percentage%%"],
      [1 /* Duration */, "Plotted duration accuracy: %percentage%%"],
      [2 /* Excitement */, "Excitement accuracy: %percentage%%"],
      [3 /* Interest */, "Interest accuracy: %percentage%%"],
      [5 /* Variety */, "Variety accuracy: %percentage%%"],
      [4 /* Timing */, "Timing accuracy: %percentage%%"]
    ]);
  }
  render(report, containerEl) {
    if (!report.isValid)
      return;
    const analyserEl = containerEl.createDiv({ cls: "rpgm-new-analyser" });
    this._addHeaderElement(report, analyserEl);
    const analyserListEl = analyserEl.createEl("ul");
    this._addTimingElements(report, analyserListEl);
    report.details.forEach((reportDetail) => {
      this._addDetailElement(reportDetail, analyserListEl);
    });
  }
  _addDetailElement(reportDetail, containerEl) {
    var _a, _b, _c;
    if (reportDetail.isRelevant === false)
      return;
    const analyserListElementEl = containerEl.createEl("li");
    const title = this.prepareDescription(reportDetail.percentage, reportDetail.score, reportDetail.maximumScore, this.titles.get(reportDetail.detailType), reportDetail.ideal);
    if (title !== void 0) {
      const subtitleEl = analyserListElementEl.createSpan({ cls: "subtitle", text: title });
      if (reportDetail.isHighBetter) {
        this.addThresholdClass(reportDetail.thresholdType, subtitleEl);
      } else {
        this.addThresholdErrorClass(reportDetail.thresholdType, subtitleEl);
      }
    }
    const subtitle = this.prepareDescription(reportDetail.percentage, reportDetail.score, reportDetail.maximumScore, (_a = this.subtitles.get(reportDetail.detailType)) == null ? void 0 : _a.get(reportDetail.thresholdType), reportDetail.ideal);
    const analyserListEl = analyserListElementEl.createEl("ul");
    if (subtitle !== void 0 && subtitle !== "")
      analyserListEl.createEl("li", { text: subtitle });
    if (reportDetail.percentage !== 100) {
      let detail = void 0;
      if (reportDetail.scoreType === 1 /* Percentage */)
        detail = this.prepareDescription(reportDetail.percentage, reportDetail.score, reportDetail.maximumScore, (_b = this.descriptions.get(reportDetail.detailType)) == null ? void 0 : _b.get(reportDetail.thresholdType), reportDetail.ideal);
      else if (reportDetail.scoreType === 2 /* Time */)
        detail = this.prepareDescription(reportDetail.percentage, this.transformTime(reportDetail.score), this.transformTime(reportDetail.maximumScore), (_c = this.descriptions.get(reportDetail.detailType)) == null ? void 0 : _c.get(reportDetail.thresholdType), this.transformTime(reportDetail.ideal));
      if (detail !== void 0 && detail !== "")
        analyserListEl.createEl("li", { text: detail });
    }
  }
  _addTimingElements(report, containerEl) {
    const analyserListTimingElementEl = containerEl.createEl("li");
    if (report.durationPercentage !== 0 && !isNaN(report.durationPercentage)) {
      const detail = this.prepareDescription(report.durationPercentage, 0, 0, this.titles.get(4 /* Timing */), 0);
      const timingTitleEl = analyserListTimingElementEl.createSpan({ cls: "subtitle", text: detail });
      this.addThresholdClass(report.durationThreshold, timingTitleEl);
    } else {
      analyserListTimingElementEl.createSpan({ cls: "subtitle", text: "Time Analysis" });
    }
    const timingEl = analyserListTimingElementEl.createDiv();
    const timingListEl = timingEl.createEl("ul");
    if (report.actualDuration !== void 0 && report.actualDuration !== 0) {
      const actualDurationEl = timingListEl.createEl("li");
      const actualDuration = this.transformTime(report.actualDuration);
      const actualDurationDescription = "Actual " + ComponentType[this.type] + " duration: " + actualDuration;
      actualDurationEl.createSpan({ cls: "description", text: actualDurationDescription });
    }
    if (report.expectedDuration !== void 0 && report.expectedDuration !== 0) {
      const expectedDurationEl = timingListEl.createEl("li");
      const expectedDuration = this.transformTime(report.expectedDuration);
      const expectedDurationDescription = "Expected " + ComponentType[this.type] + " duration: " + expectedDuration;
      expectedDurationEl.createSpan({ cls: "description", text: expectedDurationDescription });
      if (report.targetDuration !== void 0 && report.targetDuration !== 0) {
        const targetDurationEl = timingListEl.createEl("li");
        const targetDuration = this.transformTime(report.targetDuration);
        const targetDurationDescription = "Target duration: " + targetDuration;
        targetDurationEl.createSpan({ cls: "description", text: targetDurationDescription });
      }
    }
  }
  _addHeaderElement(report, containerEl) {
    const analyserHeadlineEl = containerEl.createSpan({ cls: "header" });
    analyserHeadlineEl.textContent = this.prepareDescription(report.percentage, report.score, report.maximumScore, this.titles.get(void 0), report.ideal, this.type);
    this.addThresholdClass(report.thresholdType, analyserHeadlineEl);
  }
};

// src/services/analyserService/abstracts/AbstractAnalyserReportDetail.ts
var AbstractAnalyserReportDetail = class {
  constructor(data) {
    this.data = data;
    this._isRelevant = true;
  }
  get ideal() {
    return this._idealScore;
  }
  get detailType() {
    return this._detailType;
  }
  get scoreType() {
    return this._type;
  }
  get isRelevant() {
    return this._isRelevant;
  }
  get maximumScore() {
    return this._maximumScore;
  }
  get score() {
    return this._score;
  }
  get isHighBetter() {
    return false;
  }
  get percentage() {
    if (this.maximumScore === 0)
      return 0;
    return Math.floor(this.score * 100 / this.maximumScore);
  }
  get thresholdType() {
    if (this.percentage < 30)
      return 5 /* CriticallyLow */;
    if (this.percentage < 60)
      return 4 /* Low */;
    if (this.percentage < 75)
      return 3 /* Correct */;
    if (this.percentage < 90)
      return 2 /* High */;
    return 1 /* CriticallyHigh */;
  }
  get percentageThresholdScore() {
    if (this._idealScore === void 0)
      return 0 /* NotAnalysable */;
    if (this._score > this._idealScore) {
      if (this.percentage < 60)
        return 1 /* CriticallyHigh */;
      if (this.percentage < 80)
        return 2 /* High */;
    } else {
      if (this.percentage < 60)
        return 5 /* CriticallyLow */;
      if (this.percentage < 80)
        return 4 /* Low */;
    }
    return 3 /* Correct */;
  }
};

// src/services/analyserService/reports/details/AnalyserReportActivityDetail.ts
var AnalyserReportActivityDetail = class extends AbstractAnalyserReportDetail {
  constructor(data) {
    var _a;
    super(data);
    this._type = 1 /* Percentage */;
    this._detailType = 0 /* Activity */;
    this._abtStageActivityThreshold = /* @__PURE__ */ new Map([
      [0 /* Need */, 35],
      [1 /* And */, 75],
      [2 /* But */, 50],
      [3 /* Therefore */, 75]
    ]);
    this._maximumScore = this.data.dataLength;
    this._score = this.data.totalActiveScenes;
    if (this.data.abtStage === void 0) {
      this._idealScore = Math.floor(this.maximumScore * 50 / 100);
    } else {
      this._idealScore = Math.floor(this.maximumScore * ((_a = this._abtStageActivityThreshold.get(this.data.abtStage)) != null ? _a : 50) / 100);
    }
  }
  get percentage() {
    if (this._idealScore === void 0)
      return 0;
    if (this._score === this._idealScore)
      return 100;
    if (this._score > this._idealScore * 2)
      return 0;
    if (this._score > this._idealScore)
      return Math.floor((this._idealScore - (this._score - this._idealScore)) * 100 / this._idealScore);
    return Math.floor(this._score * 100 / this._idealScore);
  }
  get thresholdType() {
    return this.percentageThresholdScore;
  }
};

// src/services/analyserService/reports/details/AnalyserReportDurationDetail.ts
var AnalyserReportDurationDetail = class extends AbstractAnalyserReportDetail {
  constructor(data) {
    super(data);
    this._type = 2 /* Time */;
    this._detailType = 1 /* Duration */;
    if (this.data.totalTargetDuration === 0 || this.data.totalExpectedRunningTime === 0) {
      this._isRelevant = false;
      return;
    }
    this._maximumScore = this.data.totalTargetDuration;
    this._idealScore = this._maximumScore;
    this._score = Math.floor(this.data.totalExpectedRunningTime / 60);
  }
  get percentage() {
    if (this.data.totalTargetDuration === 0 || this.data.totalExpectedRunningTime === 0)
      return 0;
    if (this._score > this._maximumScore * 2)
      return 0;
    if (this._score > this._maximumScore)
      return Math.floor((this._maximumScore - (this._score - this._maximumScore)) * 100 / this._maximumScore);
    return Math.floor(this._score * 100 / this._maximumScore);
  }
  get thresholdType() {
    return this.percentageThresholdScore;
  }
};

// src/services/analyserService/reports/details/AnalyserReportExcitementDetail.ts
var AnalyserReportExcitementDetail = class extends AbstractAnalyserReportDetail {
  constructor(data) {
    var _a;
    super(data);
    this._type = 2 /* Time */;
    this._detailType = 2 /* Excitement */;
    this._abtStageExcitementThreshold = /* @__PURE__ */ new Map([
      [0 /* Need */, 35],
      [1 /* And */, 35],
      [2 /* But */, 75],
      [3 /* Therefore */, 50]
    ]);
    if (this.data.totalExpectedRunningTime === 0)
      return;
    this._maximumScore = this.data.totalExpectedRunningTime;
    this._score = this.data.totalExpectedExcitmentDuration;
    if (this.data.abtStage === void 0) {
      this._idealScore = Math.floor(this.maximumScore * 50 / 100);
    } else {
      this._idealScore = Math.floor(this.maximumScore * ((_a = this._abtStageExcitementThreshold.get(this.data.abtStage)) != null ? _a : 50) / 100);
    }
  }
  get percentage() {
    if (this._idealScore === void 0)
      return 0;
    if (this._score === this._idealScore)
      return 100;
    if (this._score > this._idealScore * 2)
      return 0;
    if (this._score > this._idealScore)
      return Math.floor((this._idealScore - (this._score - this._idealScore)) * 100 / this._idealScore);
    return Math.floor(this._score * 100 / this._idealScore);
  }
  get thresholdType() {
    return this.percentageThresholdScore;
  }
};

// src/services/analyserService/reports/details/AnalyserReportInterestDetail.ts
var AnalyserReportInterestDetail = class extends AbstractAnalyserReportDetail {
  constructor(data) {
    super(data);
    this._type = 1 /* Percentage */;
    this._detailType = 3 /* Interest */;
    this._score = this.data.dataLength - this.data.totalRepetitiveScenes;
    this._maximumScore = this.data.dataLength;
    this._idealScore = this.data.dataLength;
  }
  get isHighBetter() {
    return true;
  }
};

// src/services/analyserService/reports/details/AnalyserReportVarietyDetail.ts
var AnalyserReportVarietyDetail = class extends AbstractAnalyserReportDetail {
  constructor(data) {
    super(data);
    this._type = 1 /* Percentage */;
    this._detailType = 5 /* Variety */;
    this._score = this.data.dataTypeUsed.size;
    this._maximumScore = this.data.dataLength;
    this._idealScore = 6;
  }
  get percentage() {
    if (this._idealScore === void 0)
      return 0;
    if (this._score >= this._idealScore)
      return 100;
    return Math.floor(this._score * 100 / this._idealScore);
  }
  get isHighBetter() {
    return true;
  }
};

// src/services/analyserService/reports/AnalyserReport.ts
var AnalyserReport = class {
  constructor(api, _data) {
    this.api = api;
    this._data = _data;
    this.activity = new AnalyserReportActivityDetail(_data);
    this.duration = new AnalyserReportDurationDetail(_data);
    this.excitement = new AnalyserReportExcitementDetail(_data);
    this.interest = new AnalyserReportInterestDetail(_data);
    this.variety = new AnalyserReportVarietyDetail(_data);
    this._reportDetails = /* @__PURE__ */ new Map([
      [0 /* Activity */, this.activity],
      [1 /* Duration */, this.duration],
      [2 /* Excitement */, this.excitement],
      [3 /* Interest */, this.interest],
      [5 /* Variety */, this.variety]
    ]);
  }
  get ideal() {
    return void 0;
  }
  get scoreType() {
    return 1 /* Percentage */;
  }
  get isValid() {
    return this._data.isValid;
  }
  get details() {
    const response = [];
    this._reportDetails.forEach((detail) => {
      if (detail.isRelevant)
        response.push(detail);
    });
    return response;
  }
  get actualDuration() {
    return this._data.totalRunningTime;
  }
  get expectedDuration() {
    return this._data.totalExpectedRunningTime;
  }
  get targetDuration() {
    if (this._data.totalTargetDuration === void 0)
      return void 0;
    return this._data.totalTargetDuration * 60;
  }
  get durationThreshold() {
    if (this.targetDuration === void 0 || this.actualDuration === void 0)
      return 3 /* Correct */;
    if (this.durationPercentage < 30)
      return 5 /* CriticallyLow */;
    if (this.durationPercentage < 60)
      return 4 /* Low */;
    if (this.durationPercentage < 75)
      return 3 /* Correct */;
    if (this.durationPercentage < 90)
      return 2 /* High */;
    return 1 /* CriticallyHigh */;
  }
  get score() {
    return 0;
  }
  get maximumScore() {
    return 0;
  }
  get percentage() {
    let maximumPercentage = 0;
    let percentage = 0;
    this._reportDetails.forEach((analyser) => {
      if (analyser.isRelevant) {
        maximumPercentage += 100;
        percentage += analyser.percentage;
      }
    });
    return Math.floor(percentage * 100 / maximumPercentage);
  }
  get durationPercentage() {
    if (this.targetDuration === void 0 || this.actualDuration === void 0)
      return 0;
    if (this.actualDuration > this.targetDuration * 2)
      return 0;
    if (this.actualDuration > this.targetDuration) {
      const actualDuration = this.targetDuration - (this.actualDuration - this.targetDuration);
      return Math.floor(actualDuration * 100 / this.targetDuration);
    }
    return Math.floor(this.actualDuration * 100 / this.targetDuration);
  }
  get thresholdType() {
    if (this.percentage < 30)
      return 5 /* CriticallyLow */;
    if (this.percentage < 60)
      return 4 /* Low */;
    if (this.percentage < 75)
      return 3 /* Correct */;
    if (this.percentage < 90)
      return 2 /* High */;
    return 1 /* CriticallyHigh */;
  }
};

// src/services/analyserService/views/AnalyserSceneView.ts
var AnalyserSceneView = class extends AbstractAnalyserView {
  render(report, containerEl) {
    if (!report.isValid)
      return;
    const analyserEl = containerEl.createDiv({ cls: "rpgm-new-analyser" });
    const analyserListEl = analyserEl.createEl("ul");
    const analyserListTimingElementEl = analyserListEl.createEl("li");
    analyserListTimingElementEl.createSpan({ cls: "subtitle", text: "Expected session duration: " + this.transformTime(report.expectedDuration) });
  }
};

// src/services/analyserService/views/AnalyserSceneBuilderView.ts
var AnalyserSceneBuilderView = class extends AnalyserVisualView {
  constructor() {
    super(...arguments);
    this._extendedDescription = /* @__PURE__ */ new Map([
      [
        0 /* Activity */,
        /* @__PURE__ */ new Map([
          [1 /* CriticallyHigh */, "Activity\nToo high"],
          [2 /* High */, "Activity\nHigh"],
          [3 /* Correct */, "Activity"],
          [4 /* Low */, "Activity\nLow"],
          [5 /* CriticallyLow */, "Activity\nToo low"]
        ])
      ],
      [
        2 /* Excitement */,
        /* @__PURE__ */ new Map([
          [1 /* CriticallyHigh */, "Excitement\nToo high"],
          [2 /* High */, "Excitement\nHigh"],
          [3 /* Correct */, "Excitement"],
          [4 /* Low */, "Excitement\nLow"],
          [5 /* CriticallyLow */, "Excitement\nToo low"]
        ])
      ],
      [
        3 /* Interest */,
        /* @__PURE__ */ new Map([
          [1 /* CriticallyHigh */, "Interest"],
          [2 /* High */, "Interest"],
          [3 /* Correct */, "Interest"],
          [4 /* Low */, "Interest\nLow"],
          [5 /* CriticallyLow */, "Interest\nToo low"]
        ])
      ],
      [
        5 /* Variety */,
        /* @__PURE__ */ new Map([
          [1 /* CriticallyHigh */, "Variety"],
          [2 /* High */, "Variety"],
          [3 /* Correct */, "Variety"],
          [4 /* Low */, "Variety\nLow"],
          [5 /* CriticallyLow */, "Variety\nToo low"]
        ])
      ]
    ]);
  }
  render(report, containerEl) {
    if (!report.isValid)
      return;
    const analyserEl = containerEl.createDiv({ cls: "rpgm-new-analyser centred" });
    const analyserContainerEl = analyserEl.createDiv({ cls: "analyser-container clearfix" });
    this.addCircle(analyserContainerEl, report.percentage, report.thresholdType, true, "Score");
    report.details.forEach((reportDetail) => {
      var _a, _b;
      if (reportDetail.isRelevant === false)
        return;
      const circleEl = this.addCircle(analyserContainerEl, reportDetail.percentage, reportDetail.thresholdType, reportDetail.isHighBetter, (_b = (_a = this._extendedDescription.get(reportDetail.detailType)) == null ? void 0 : _a.get(reportDetail.thresholdType)) != null ? _b : "");
      circleEl.addEventListener("mouseover", () => {
        this._showFix(reportDetail);
      });
      circleEl.addEventListener("mouseout", () => {
        this._showExpectedDuration(report);
      });
    });
    this._fixEl = analyserEl.createDiv({ cls: "analyser-container-fix" });
    this._showExpectedDuration(report);
  }
  _showExpectedDuration(report) {
    return __async(this, null, function* () {
      this._fixEl.removeClasses(["error", "warning", "balanced", "perfect", "normal"]);
      if (report.expectedDuration !== void 0 && report.expectedDuration !== 0) {
        const expectedDuration = this.transformTime(report.expectedDuration);
        this._fixEl.textContent = "Expected duration: " + expectedDuration;
      } else {
        this._fixEl.textContent = "";
      }
      this.addThresholdClass(3 /* Correct */, this._fixEl);
    });
  }
  _showFix(reportDetail) {
    return __async(this, null, function* () {
      var _a, _b;
      this._fixEl.removeClasses(["error", "warning", "balanced", "perfect", "normal"]);
      let description = "";
      if (reportDetail.scoreType === 1 /* Percentage */)
        description = this.prepareDescription(reportDetail.percentage, reportDetail.score, reportDetail.maximumScore, (_a = this.descriptions.get(reportDetail.detailType)) == null ? void 0 : _a.get(reportDetail.thresholdType), reportDetail.ideal);
      else if (reportDetail.scoreType === 2 /* Time */)
        description = this.prepareDescription(reportDetail.percentage, this.transformTime(reportDetail.score), this.transformTime(reportDetail.maximumScore), (_b = this.descriptions.get(reportDetail.detailType)) == null ? void 0 : _b.get(reportDetail.thresholdType), this.transformTime(reportDetail.ideal));
      if (description !== "") {
        if (reportDetail.isHighBetter) {
          this.addThresholdClass(reportDetail.thresholdType, this._fixEl);
        } else {
          this.addThresholdErrorClass(reportDetail.thresholdType, this._fixEl);
        }
        this._fixEl.textContent = description;
      }
    });
  }
};

// src/services/analyserService/abstracts/AbstractAnalyser.ts
var AbstractAnalyser = class {
  constructor(api, abtStage) {
    this.api = api;
    this.isSingleScene = false;
    this.rawData = [];
    this._analyserData = new AnalyserData();
    this._analyserData.abtStage = abtStage;
  }
  get scenesCount() {
    return this.rawData.length;
  }
  set targetDuration(duration2) {
    this._analyserData.totalTargetDuration = duration2;
  }
  render(type, containerEl) {
    const report = new AnalyserReport(this.api, this._analyserData);
    let view = void 0;
    switch (type) {
      case 2 /* Scene */:
        view = new AnalyserSceneView(this.api, this.type);
        break;
      case 1 /* Visual */:
        view = new AnalyserVisualView(this.api, this.type);
        break;
      case 0 /* Extended */:
        view = new AnalyserExtendedView(this.api, this.type);
        break;
      case 3 /* SceneBuilder */:
        view = new AnalyserSceneBuilderView(this.api, this.type);
        break;
      default:
        return;
    }
    view.render(report, containerEl);
  }
  ingestData() {
    if (this.rawData.length > 0) {
      this._analyserData.dataLength = this.rawData.length;
      this.rawData.forEach((data) => {
        var _a;
        this._analyserData.totalRunningTime += (_a = data.currentDuration) != null ? _a : 0;
        this._analyserData.addExpectedRunningTime(data.expectedDuration);
        if (data.isExciting)
          this._analyserData.addExpectedExcitmentDuration(data.expectedDuration);
        if (data.isActive)
          this._analyserData.addActiveScene();
        this._analyserData.addSceneType(data.type);
      });
    }
  }
  convertScene(scene) {
    const response = {
      isExciting: false,
      isActive: false,
      expectedDuration: 0
    };
    response.currentDuration = scene.currentDuration;
    response.isExciting = scene.isExciting;
    response.expectedDuration = scene.expectedDuration;
    response.isActive = scene.isActive;
    response.type = scene.sceneType;
    return response;
  }
  addScene(scene) {
    this.rawData.push(this.convertScene(scene));
  }
  addScenesList(scenes) {
    scenes.forEach((scene) => {
      this.addScene(scene);
    });
  }
};

// src/services/analyserService/analysers/BuilderAnalyser.ts
var BuilderAnalyser = class extends AbstractAnalyser {
  constructor(api, dataList, abtStage) {
    super(api, abtStage);
    this.type = 4 /* Act */;
    this.rawData = dataList;
    super.ingestData();
  }
};

// src/services/analyserService/analysers/SceneAnalyser.ts
var SceneAnalyser = class extends AbstractAnalyser {
  constructor(api, scene, abtStage) {
    super(api, abtStage);
    this.isSingleScene = true;
    this.addScene(this.api.database.readById(scene.index.id));
    super.ingestData();
  }
};

// src/services/analyserService/analysers/ActAnalyser.ts
var ActAnalyser = class extends AbstractAnalyser {
  constructor(api, act, abtStage) {
    super(api, abtStage);
    this.type = 4 /* Act */;
    const sceneList = this.api.database.readChildren(8 /* Scene */, act.index.id).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((scene) => scene.index.positionInParent)
    ]));
    super.addScenesList(sceneList);
    super.ingestData();
  }
};

// src/services/analyserService/analysers/SessionAnalyser.ts
var SessionAnalyser = class extends AbstractAnalyser {
  constructor(api, session, abtStage) {
    super(api, abtStage);
    this.type = 16 /* Session */;
    const singleSession = this.api.database.readById(session.index.id);
    if (singleSession.targetDuration != void 0)
      this.targetDuration = singleSession.targetDuration;
    const sceneList = this.api.database.read((scene) => {
      var _a;
      return scene.index.type === 8 /* Scene */ && scene.index.campaignId === session.index.campaignId && ((_a = scene.session) == null ? void 0 : _a.index.id) === session.index.id;
    }).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((scene) => scene.index.campaignId),
      new SorterComparisonElement((scene) => scene.index.parentPosition),
      new SorterComparisonElement((scene) => scene.index.positionInParent)
    ]));
    super.addScenesList(sceneList);
    super.ingestData();
  }
};

// src/services/analyserService/AnalyserService.ts
var AnalyserService = class extends AbstractService {
  createAct(act, abtStage) {
    return new ActAnalyser(this.api, act, abtStage);
  }
  createBuilder(data, abtStage) {
    return new BuilderAnalyser(this.api, data, abtStage);
  }
  createScene(scene, abtStage) {
    return new SceneAnalyser(this.api, scene, abtStage);
  }
  createSession(session, abtStage) {
    return new SessionAnalyser(this.api, session, abtStage);
  }
  getReadableSceneType(type) {
    return SceneType[type].toString().toLowerCase();
  }
  getSceneType(readableContentType) {
    readableContentType = readableContentType[0].toUpperCase() + readableContentType.substring(1).toLowerCase();
    readableContentType = readableContentType.replaceAll("combat", "Combat");
    return SceneType[readableContentType];
  }
};

// src/services/runningTimeService/RunningTimeService.ts
var import_obsidian22 = require("obsidian");
var RunningTimeService = class extends AbstractService {
  constructor() {
    super(...arguments);
    this._currentlyRunningScene = void 0;
    this._medianDefaultTimes = /* @__PURE__ */ new Map([
      [0 /* Action */, [15 * 60]],
      [1 /* Combat */, [15 * 60]],
      [2 /* Encounter */, [15 * 60]],
      [3 /* Exposition */, [5 * 60]],
      [4 /* Investigation */, [15 * 60]],
      [5 /* Planning */, [10 * 60]],
      [6 /* Preparation */, [10 * 60]],
      [7 /* Recap */, [5 * 60]],
      [8 /* SocialCombat */, [15 * 60]]
    ]);
    this.medianTimes = /* @__PURE__ */ new Map([
      [
        "",
        this._medianDefaultTimes
      ]
    ]);
  }
  get isTimerRunning() {
    return this._currentlyRunningScene !== void 0;
  }
  isCurrentlyRunningScene(scene) {
    if (this._currentlyRunningScene === void 0)
      return false;
    return this._currentlyRunningScene.index === scene.index;
  }
  startScene(scene) {
    return __async(this, null, function* () {
      if (this._currentlyRunningScene !== void 0)
        yield this.stopScene(this._currentlyRunningScene);
      this._currentlyRunningScene = scene;
      this.api.service(CodeblockService).startRunningTime();
    });
  }
  stopScene(scene) {
    return __async(this, null, function* () {
      if (scene.isCurrentlyRunning) {
        this.api.service(CodeblockService).stopRunningTime(scene.file);
        if (this._currentlyRunningScene !== void 0 && this._currentlyRunningScene.index.id === scene.index.id)
          this._currentlyRunningScene = void 0;
      }
    });
  }
  updateMedianTimes(isStartup = false) {
    return __async(this, null, function* () {
      const campaigns = this.api.database.read((campaign) => campaign.index.type === 1 /* Campaign */);
      for (let index = 0; index < campaigns.length; index++) {
        this.medianTimes.set(campaigns[index].index.campaignId, structuredClone(this._medianDefaultTimes));
      }
      const scenes = this.api.database.read((scene) => scene.index.type === 8 /* Scene */);
      yield scenes.forEach((scene) => {
        if (isStartup && scene.isCurrentlyRunning)
          this.stopScene(scene);
        if (scene.sceneType !== void 0 && scene.currentDuration !== void 0 && scene.currentDuration !== 0) {
          const campaignMedians = this.medianTimes.get(scene.index.campaignId);
          if (campaignMedians !== void 0) {
            const sessionTypeTimes = campaignMedians.get(scene.sceneType);
            if (sessionTypeTimes !== void 0)
              sessionTypeTimes.push(scene.currentDuration);
          }
        }
      });
      this.api.app.workspace.on("active-leaf-change", this._stopClosedLeaf.bind(this));
    });
  }
  getTypeExpectedDuration(campaignId, type) {
    var _a, _b;
    const previousDurations = (_b = (_a = this.medianTimes.get(campaignId)) == null ? void 0 : _a.get(type)) != null ? _b : [];
    if (previousDurations.length === 0)
      return 0;
    if (previousDurations.length === 1)
      return previousDurations[0];
    previousDurations.sort((left, right) => {
      if (left > right)
        return 1;
      if (left < right)
        return -1;
      return 0;
    });
    if (previousDurations.length % 2 === 0) {
      const previous = previousDurations[previousDurations.length / 2];
      const next = previousDurations[previousDurations.length / 2 - 1];
      return Math.floor((previous + next) / 2);
    } else {
      return previousDurations[(previousDurations.length - 1) / 2];
    }
  }
  _stopClosedLeaf() {
    return __async(this, null, function* () {
      if (!this.isTimerRunning)
        return;
      let isCurrentlyRunningSceneOpen = false;
      this.api.app.workspace.iterateAllLeaves((leaf) => {
        var _a;
        if (leaf.view instanceof import_obsidian22.MarkdownView) {
          const file = (_a = leaf.view) == null ? void 0 : _a.file;
          if (file !== void 0) {
            const component = this.api.database.readByPath(file.path);
            if (component !== void 0 && component.index.type === 8 /* Scene */ && this.isCurrentlyRunningScene(component))
              isCurrentlyRunningSceneOpen = true;
          }
        }
      });
      if (!isCurrentlyRunningSceneOpen && this._currentlyRunningScene !== void 0)
        this.stopScene(this._currentlyRunningScene);
    });
  }
};

// src/services/sceneBuilderService/modals/SceneBuilderModal.ts
var import_obsidian23 = require("obsidian");
var SceneBuilderModal = class extends AbstractModal {
  constructor(api, _act) {
    super(api);
    this._act = _act;
    this._hasEmptyLine = false;
    this.maxWidth = true;
    this.title = "Scene Builder";
    this._emptyLines = /* @__PURE__ */ new Map();
    this._idCounter = 0;
  }
  onClose() {
    super.onClose();
    this.app.workspace.trigger("rpgmanager:force-refresh-views");
  }
  onOpen() {
    super.onOpen();
    this.modalEl.style.width = "var(--modal-max-width)";
    this.modalEl.style.minHeight = "var(--modal-max-height)";
    const editorDeletedContainerEl = this.rpgmContainerEl.createDiv({ cls: "rpg-manager-scene-builder-confirmation" });
    editorDeletedContainerEl.createDiv({ text: "The scenes for " + this._act.file.basename + " have been created" });
    const sceneBuilderContainerEl = this.rpgmContainerEl.createDiv({ cls: "rpg-manager-scene-builder" });
    if (this.api.settings.usePlotStructures)
      this._addPlot(sceneBuilderContainerEl);
    this._analyserContainerEl = sceneBuilderContainerEl.createDiv({ cls: "rpg-manager-scene-builder-analyser" });
    const scenesContainerEl = sceneBuilderContainerEl.createDiv({ cls: "scenes-container" });
    const buttonContainerEl = sceneBuilderContainerEl.createDiv({ cls: "rpg-manager-scene-builder-confirmation-button" });
    this._createScenesButtonEl = buttonContainerEl.createEl("button", { text: "Create Scenes for act " + this._act.file.basename });
    this._createScenesButtonEl.disabled = true;
    this._createScenesButtonEl.addEventListener("click", () => {
      this._createScenes().then(() => {
        editorDeletedContainerEl.style.display = "block";
      });
    });
    this._addScenesTable(scenesContainerEl);
  }
  _createScenes() {
    return __async(this, null, function* () {
      let positionInParent = 1;
      const scenes = this.api.database.readChildren(8 /* Scene */, this._act.index.id);
      yield scenes.forEach((scene) => {
        if (scene.index.positionInParent >= positionInParent)
          positionInParent = scene.index.positionInParent + 1;
      });
      let indexOfSelect = 2;
      if (this.api.settings.usePlotStructures)
        indexOfSelect = 3;
      for (let index = 0; index < this._scenesContainerEl.rows.length; index++) {
        const line = this._scenesContainerEl.rows[index];
        if (line.dataset.id === void 0)
          continue;
        if (this._emptyLines.has(+line.dataset.id) && this._emptyLines.get(+line.dataset.id) === true)
          continue;
        if (line.cells[0].childNodes[0].disabled === true)
          continue;
        let sceneType;
        const type = line.cells[indexOfSelect].childNodes[0].value;
        if (type !== "")
          sceneType = this.api.service(AnalyserService).getSceneType(type);
        const title = line.cells[0].childNodes[0].value;
        const data = {
          synopsis: line.cells[indexOfSelect - 1].childNodes[0].value,
          sceneType: sceneType !== void 0 ? this.api.service(AnalyserService).getReadableSceneType(sceneType) : "",
          isActedUpon: line.cells[indexOfSelect + 1].childNodes[0].checked
        };
        if (this.api.settings.usePlotStructures) {
          data.storyCircleStage = line.cells[1].childNodes[0].value;
        }
        this.api.service(FileCreationService).silentCreate(8 /* Scene */, title, this._act.index.campaignId, this._act.index.id, positionInParent, {
          data
        });
        positionInParent++;
      }
      this.close();
    });
  }
  _refreshAnalyser() {
    return __async(this, null, function* () {
      var _a;
      this._analyserContainerEl.empty();
      const data = [];
      for (let index = 0; index < this._scenesContainerEl.rows.length; index++) {
        let indexOfSelect = 2;
        if (this.api.settings.usePlotStructures)
          indexOfSelect = 3;
        const cells = this._scenesContainerEl.rows[index].cells;
        const type = cells[indexOfSelect].childNodes[0].value;
        if (type !== "") {
          const sceneType = this.api.service(AnalyserService).getSceneType(type);
          data.push({
            isExciting: cells[indexOfSelect + 1].childNodes[0].checked,
            isActive: sceneType !== void 0 ? (_a = activeSceneTypes.get(sceneType)) != null ? _a : false : false,
            expectedDuration: sceneType !== void 0 ? this.api.service(RunningTimeService).getTypeExpectedDuration(this._act.index.campaignId, sceneType) : 0,
            type: sceneType
          });
        }
      }
      if (data.length > 0) {
        const analyser = this.api.service(AnalyserService).createBuilder(data, this._act.abtStage);
        analyser.render(3 /* SceneBuilder */, this._analyserContainerEl);
      }
    });
  }
  _addSceneLine(scene) {
    var _a;
    const id = this._idCounter++;
    const rowEl = this._scenesContainerEl.insertRow();
    rowEl.dataset.id = id.toString();
    this._updateEmptyLines(id, scene === void 0, false, scene === void 0);
    const titleCellEl = rowEl.insertCell();
    titleCellEl.addClass("scenes-container-table-title");
    let plotStageSelectionEl = void 0;
    if (this.api.settings.usePlotStructures) {
      const plotStageCellEl = rowEl.insertCell();
      plotStageCellEl.addClass("scenes-container-table-stage");
      plotStageSelectionEl = plotStageCellEl.createEl("select");
      plotStageSelectionEl.createEl("option", {
        text: "",
        value: ""
      });
      Object.keys(StoryCircleStage).filter((v) => isNaN(Number(v))).forEach((type, index) => {
        if (plotStageSelectionEl !== void 0) {
          const plotStageOption = plotStageSelectionEl.createEl("option", {
            text: type,
            value: type
          });
          if (scene !== void 0 && scene.storyCircleStage !== void 0 && scene.storyCircleStage === this.api.service(PlotService).getStoryCircleStage(type)) {
            plotStageOption.selected = true;
          }
        }
      });
      if (scene === void 0) {
        plotStageSelectionEl.addEventListener("change", () => {
          this._updateEmptyLines(id, titleInputEl.value === "" && goalInputEl.value === "" && typeSelectionEl.value === "" && excitementCheckboxEl.checked === false && (plotStageSelectionEl === void 0 ? true : plotStageSelectionEl.value === ""), true);
          this._refreshAnalyser();
        });
      }
    }
    const goalCellEl = rowEl.insertCell();
    goalCellEl.addClass("scenes-container-table-goal");
    const typeCellEl = rowEl.insertCell();
    typeCellEl.addClass("scenes-container-table-type");
    const excitingCellEl = rowEl.insertCell();
    excitingCellEl.addClass("scenes-container-table-exciting");
    const titleInputEl = titleCellEl.createEl("input");
    titleInputEl.type = "text";
    const goalInputEl = goalCellEl.createEl("input");
    goalInputEl.type = "text";
    const typeSelectionEl = typeCellEl.createEl("select");
    const excitementCheckboxEl = excitingCellEl.createEl("input");
    this.api.service(LinkSuggesterService).createHandler(goalInputEl, this._act);
    typeSelectionEl.createEl("option", { text: "", value: "" }).selected = true;
    Object.keys(SceneType).filter((v) => isNaN(Number(v))).forEach((type, index) => {
      var _a2;
      const typeOption = typeSelectionEl.createEl("option", {
        text: (_a2 = sceneTypeDescription.get(SceneType[type])) != null ? _a2 : type,
        value: type
      });
      if (scene !== void 0 && scene.sceneType !== void 0 && scene.sceneType === SceneType[type]) {
        typeOption.selected = true;
      }
    });
    excitementCheckboxEl.type = "checkbox";
    if (scene !== void 0) {
      titleInputEl.value = scene.file.basename;
      titleInputEl.disabled = true;
      goalInputEl.value = (_a = scene.synopsis) != null ? _a : "";
      goalInputEl.disabled = true;
      typeSelectionEl.disabled = true;
      if (scene.isExciting)
        excitementCheckboxEl.checked = true;
      excitementCheckboxEl.disabled = true;
      if (this.api.settings.usePlotStructures && plotStageSelectionEl !== void 0)
        plotStageSelectionEl.disabled = true;
    } else {
      titleInputEl.addEventListener("keyup", () => {
        this._updateEmptyLines(id, titleInputEl.value === "" && goalInputEl.value === "" && typeSelectionEl.value === "" && excitementCheckboxEl.checked === false && (plotStageSelectionEl === void 0 ? true : plotStageSelectionEl.value === ""));
      });
      titleInputEl.addEventListener("focusout", () => {
        this._updateEmptyLines(id, titleInputEl.value === "" && goalInputEl.value === "" && typeSelectionEl.value === "" && excitementCheckboxEl.checked === false && (plotStageSelectionEl === void 0 ? true : plotStageSelectionEl.value === ""), true);
      });
      goalInputEl.addEventListener("keyup", () => {
        this._updateEmptyLines(id, titleInputEl.value === "" && goalInputEl.value === "" && typeSelectionEl.value === "" && excitementCheckboxEl.checked === false && (plotStageSelectionEl === void 0 ? true : plotStageSelectionEl.value === ""));
      });
      goalInputEl.addEventListener("focusout", () => {
        this._updateEmptyLines(id, titleInputEl.value === "" && goalInputEl.value === "" && typeSelectionEl.value === "" && excitementCheckboxEl.checked === false && (plotStageSelectionEl === void 0 ? true : plotStageSelectionEl.value === ""), true);
      });
      typeSelectionEl.addEventListener("change", () => {
        this._updateEmptyLines(id, titleInputEl.value === "" && goalInputEl.value === "" && typeSelectionEl.value === "" && excitementCheckboxEl.checked === false && (plotStageSelectionEl === void 0 ? true : plotStageSelectionEl.value === ""), true);
        this._refreshAnalyser();
      });
      excitementCheckboxEl.addEventListener("change", () => {
        this._updateEmptyLines(id, titleInputEl.value === "" && goalInputEl.value === "" && typeSelectionEl.value === "" && excitementCheckboxEl.checked === false && (plotStageSelectionEl === void 0 ? true : plotStageSelectionEl.value === ""), true);
        this._refreshAnalyser();
      });
    }
  }
  _updateEmptyLines(lineId, isEmpty, deleteLine = false, addLineIfEmpty = true) {
    this._emptyLines.set(lineId, isEmpty);
    let emptyLines = 0;
    this._emptyLines.forEach((empty, id) => {
      if (empty === true)
        emptyLines++;
    });
    if (emptyLines > 1 && deleteLine) {
      this._emptyLines.delete(lineId);
      for (let index = 0; index < this._scenesContainerEl.rows.length; index++) {
        if (this._scenesContainerEl.rows[index].dataset.id === lineId.toString()) {
          this._scenesContainerEl.deleteRow(index);
          emptyLines--;
          break;
        }
      }
    }
    this._hasEmptyLine = emptyLines > 0;
    if (!this._hasEmptyLine) {
      this._hasEmptyLine = true;
      if (addLineIfEmpty)
        this._addSceneLine();
    }
    this._createScenesButtonEl.disabled = this._scenesContainerEl.rows.length < 2;
  }
  _addScenesTable(containerEl) {
    const scenesTableEl = containerEl.createEl("table");
    const titleTHeadEl = scenesTableEl.createTHead();
    const titleRowEl = titleTHeadEl.insertRow();
    const titleCellEl = titleRowEl.insertCell();
    titleCellEl.textContent = "Title";
    titleCellEl.addClass("scenes-container-table-title");
    if (this.api.settings.usePlotStructures) {
      const plotStageCellEl = titleRowEl.insertCell();
      plotStageCellEl.textContent = "Stage";
      plotStageCellEl.addClass("scenes-container-table-stage");
    }
    const goalCellEl = titleRowEl.insertCell();
    goalCellEl.textContent = "Goal";
    goalCellEl.addClass("scenes-container-table-goal");
    const typeCellEl = titleRowEl.insertCell();
    typeCellEl.textContent = "Type";
    typeCellEl.addClass("scenes-container-table-type");
    const excitingCellEl = titleRowEl.insertCell();
    excitingCellEl.textContent = "Exciting?";
    excitingCellEl.addClass("scenes-container-table-exciting");
    this._scenesContainerEl = scenesTableEl.createTBody();
    const scenes = this.api.database.readChildren(8 /* Scene */, this._act.index.id).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((scene) => scene.index.id)
    ]));
    if (scenes.length > 0) {
      for (let index = 0; index < scenes.length; index++) {
        this._addSceneLine(scenes[index]);
      }
      this._refreshAnalyser();
    }
    this._addSceneLine();
  }
  _addPlot(containerEl) {
    const plotContainerEl = containerEl.createDiv({ cls: "rpg-manager-scene-builder-plot" });
    this._addPlotElement("You", this._act.storyCircle.you, plotContainerEl);
    this._addPlotElement("Need", this._act.storyCircle.need, plotContainerEl);
    this._addPlotElement("Go", this._act.storyCircle.go, plotContainerEl);
    this._addPlotElement("Search", this._act.storyCircle.search, plotContainerEl);
    this._addPlotElement("Find", this._act.storyCircle.find, plotContainerEl);
    this._addPlotElement("Take", this._act.storyCircle.take, plotContainerEl);
    this._addPlotElement("Return", this._act.storyCircle.return, plotContainerEl);
    this._addPlotElement("Change", this._act.storyCircle.change, plotContainerEl);
  }
  _addPlotElement(title, content, containerEl) {
    const plotContainerEl = containerEl.createDiv({ cls: "rpg-manager-scene-builder-plot-line clearfix" });
    plotContainerEl.createDiv({ cls: "rpg-manager-scene-builder-plot-line-title", text: title });
    const plotContentEl = plotContainerEl.createDiv({ cls: "rpg-manager-scene-builder-plot-line-description" });
    import_obsidian23.MarkdownRenderer.renderMarkdown(content, plotContentEl, "", null);
  }
};

// src/services/sceneBuilderService/SceneBuilderService.ts
var SceneBuilderService = class extends AbstractService {
  open(act) {
    return __async(this, null, function* () {
      new SceneBuilderModal(this.api, act).open();
    });
  }
};

// src/managers/modalsManager/abstracts/AbstractWizardModal.ts
var import_obsidian24 = require("obsidian");

// src/managers/modalsManager/parts/NavigationPart.ts
var NavigationPart = class {
  constructor(_steps, _containerEl, _moveFn) {
    this._steps = _steps;
    this._containerEl = _containerEl;
    this._moveFn = _moveFn;
    this._circles = [];
    const navigationEl = this._containerEl.createDiv({ cls: "rpg-manager-wizard-navigation-elements" });
    for (let index = 0; index < this._steps + 1; index++) {
      const dotEl = navigationEl.createDiv({ cls: "rpg-manager-wizard-navigation-elements-dot", text: (index + 1).toString() });
      dotEl.addEventListener("click", () => {
        this._moveFn(index);
      });
      this._circles.push(dotEl);
    }
  }
  render(step) {
    return __async(this, null, function* () {
      for (let index = 0; index < this._steps + 1; index++) {
        if (index <= step)
          this._circles[index].addClass("rpg-manager-wizard-navigation-elements-dot-active");
        else
          this._circles[index].removeClass("rpg-manager-wizard-navigation-elements-dot-active");
      }
    });
  }
};

// src/managers/modalsManager/abstracts/AbstractWizardModal.ts
var AbstractWizardModal = class extends import_obsidian24.Modal {
  constructor(api) {
    super(api.app);
    this.api = api;
    this.scope = new import_obsidian24.Scope();
    this.scope.register([], "Escape", (evt) => {
      evt.preventDefault();
    });
    this._currentStep = 0;
    this.isInitialised = false;
  }
  open() {
    super.open();
    const { contentEl } = this;
    contentEl.empty();
    contentEl.addClass("rpg-manager-modal");
    this.modalEl.style.width = "var(--modal-max-width)";
    const wizardEl = contentEl.createDiv({ cls: "rpg-manager-modal-wizard" });
    this._wizardHeaderEl = wizardEl.createDiv({ cls: "rpg-manager-wizard-header" });
    this._wizardHeaderEl.createEl("h2", { text: "Plot Creation Wizard" });
    this._wizardNavigationEl = wizardEl.createDiv({ cls: "rpg-manager-wizard-navigation" });
    const mainContentEl = wizardEl.createDiv({ cls: "rpg-manager-wizard-main clearfix" });
    this._wizardRecapEl = mainContentEl.createDiv({ cls: "rpg-manager-wizard-main-recap" });
    this._wizardContentEl = mainContentEl.createDiv({ cls: "rpg-manager-wizard-main-content clearfix" });
    this._wizardButtonEl = wizardEl.createDiv({ cls: "rpg-manager-wizard-buttons" });
    this.move(0);
  }
  close() {
    super.close();
  }
  move(newStep) {
    return __async(this, null, function* () {
      if (this._currentPartInterface !== void 0)
        this._currentPartInterface.save();
      this._updateNavigation(newStep);
      this._updateRecap(this._wizardRecapEl);
      this._updateButtons(newStep);
      this._render(newStep);
      if (!this.isInitialised)
        this.isInitialised = true;
    });
  }
  _updateNavigation(newStep) {
    return __async(this, null, function* () {
      if (!this.isInitialised)
        this._navigationPart = new NavigationPart(this.steps, this._wizardNavigationEl, this.move.bind(this));
      this._navigationPart.render(newStep);
    });
  }
  _updateButtons(step) {
    return __async(this, null, function* () {
      if (!this.isInitialised) {
        this._nextButtonEl = this._wizardButtonEl.createEl("button");
        this._backButtonEl = this._wizardButtonEl.createEl("button", { text: "Back" });
        this._backButtonEl.addEventListener("click", () => {
          if (this._currentStep !== 0)
            this.move(this._currentStep - 1);
        });
        this._nextButtonEl.addEventListener("click", () => {
          if (this._currentStep === this.steps) {
            if (this._currentPartInterface !== void 0)
              this._currentPartInterface.save();
            this.create();
          } else {
            this.move(this._currentStep + 1);
          }
        });
      }
      this._currentStep = step;
      if (this._currentStep === 0)
        this._backButtonEl.disabled = true;
      else
        this._backButtonEl.disabled = false;
      if (this._currentStep === this.steps)
        this._nextButtonEl.textContent = "Create Plot";
      else
        this._nextButtonEl.textContent = "Next >";
    });
  }
  getClueHint(clue) {
    if (clue === void 0 || clue.name === void 0 || clue.name === "")
      return "";
    let response = " (*information [[" + clue.name + "]]";
    if (clue.leads !== void 0 && clue.leads.length > 0) {
      let leads = "";
      for (let index = 0; index < clue.leads.length; index++) {
        leads += " [[" + clue.leads[index] + "]],";
      }
      if (leads !== "") {
        leads = leads.substring(0, leads.length - 1);
        response += " available from" + leads;
      }
    }
    response += "*)";
    return response;
  }
  _render(newStep) {
    return __async(this, null, function* () {
      this._currentPartInterface = this.getStepInterface(newStep);
      this._wizardContentEl.empty();
      this._currentPartInterface.render(this._wizardContentEl);
    });
  }
};

// src/services/plotWizardService/abstracts/AbstractStepModal.ts
var AbstractStepModal = class {
  constructor(api, adventureId, title, description, existingDescription) {
    this.api = api;
    this.adventureId = adventureId;
    this.title = title;
    this.description = description;
    this.existingDescription = existingDescription;
  }
  get adventure() {
    return this.api.database.readById(this.adventureId.id);
  }
  get data() {
    return this.information;
  }
  getContainer(containerEl, containsClues) {
    var _a, _b, _c;
    containerEl.createEl("h2", { cls: "rpg-manager-wizard-main-content-header", text: this.title });
    containerEl.createDiv({ cls: "rpg-manager-wizard-main-content-title", text: this.description });
    const dataContainerEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-content-container clearfix" });
    const descriptionContainerEl = dataContainerEl.createDiv({ cls: "rpg-manager-wizard-main-content-container-" + (containsClues ? "clues-" : "") + "text" });
    this.descriptionEl = descriptionContainerEl.createEl("textarea", {
      cls: "rpg-manager-wizard-main-content-container-textarea",
      text: (_c = (_b = (_a = this.information) == null ? void 0 : _a.description) != null ? _b : this.existingDescription) != null ? _c : ""
    });
    this.api.service(LinkSuggesterService).createHandler(this.descriptionEl, this.adventure);
    return dataContainerEl;
  }
};

// src/services/plotWizardService/modals/steps/StepIntroductionModal.ts
var import_obsidian25 = require("obsidian");
var StepIntroductionModal = class extends AbstractStepModal {
  render(containerEl) {
    return __async(this, null, function* () {
      containerEl.createEl("h2", { cls: "rpg-manager-wizard-main-content-header", text: this.title });
      const introductionEl = containerEl.createDiv();
      import_obsidian25.MarkdownRenderer.renderMarkdown(this.description, introductionEl, "", null);
    });
  }
  save() {
    return __async(this, null, function* () {
    });
  }
};

// src/services/plotWizardService/modals/steps/StepDescriptionModal.ts
var StepDescriptionModal = class extends AbstractStepModal {
  render(containerEl) {
    return __async(this, null, function* () {
      __superGet(StepDescriptionModal.prototype, this, "getContainer").call(this, containerEl, false);
    });
  }
  save() {
    return __async(this, null, function* () {
      this.information = {
        description: this.descriptionEl.value
      };
    });
  }
};

// src/services/plotWizardService/modals/steps/StepDescriptionAndCluesModal.ts
var StepDescriptionAndCluesModal = class extends AbstractStepModal {
  render(containerEl) {
    return __async(this, null, function* () {
      var _a, _b, _c, _d, _e, _f, _g, _h;
      const dataContainerEl = __superGet(StepDescriptionAndCluesModal.prototype, this, "getContainer").call(this, containerEl, true);
      const cluesContainerEl = dataContainerEl.createDiv({ cls: "rpg-manager-wizard-main-content-container-clues" });
      cluesContainerEl.createDiv({ cls: "rpg-manager-wizard-main-content-container-clues-title-container rpg-manager-wizard-main-content-container-clues-title", text: "Clue" });
      this._clueTitleEl = cluesContainerEl.createEl("input", { cls: "rpg-manager-wizard-main-content-container-clues-title-input", type: "text", placeholder: "Title of the clue", value: (_c = (_b = (_a = this.information) == null ? void 0 : _a.clue) == null ? void 0 : _b.name) != null ? _c : "" });
      this.api.service(LinkSuggesterService).createSimplifiedHandler(this._clueTitleEl, this.adventure);
      this._clueTitleEl.addEventListener("change", () => {
        var _a2;
        const clue = this.api.database.readByBaseName(this._clueTitleEl.value);
        if (clue === void 0) {
          this._clueDescriptionEl.value = "";
          this._clueDescriptionEl.disabled = false;
          this._clueDescriptionEl.focus();
        } else {
          this._clueDescriptionEl.value = (_a2 = clue.synopsis) != null ? _a2 : "";
          this._clueDescriptionEl.disabled = true;
        }
      });
      this._clueDescriptionEl = cluesContainerEl.createEl("textarea", {
        cls: "rpg-manager-wizard-main-content-container-clues-title-description",
        text: (_f = (_e = (_d = this.information) == null ? void 0 : _d.clue) == null ? void 0 : _e.description) != null ? _f : ""
      });
      this._clueDescriptionEl.disabled = true;
      this._clueDescriptionEl.placeholder = "Synopsis of the clue";
      this.api.service(LinkSuggesterService).createHandler(this._clueDescriptionEl, this.adventure);
      cluesContainerEl.createDiv({ cls: "rpg-manager-wizard-main-content-container-clues-lead-container-title rpg-manager-wizard-main-content-container-clues-title", text: "Where can the clue be found?" });
      this._leadItems = [];
      this._leadContainerEl = cluesContainerEl.createDiv({ cls: "rpg-manager-wizard-main-content-container-clues-lead-container" });
      if (((_h = (_g = this.information) == null ? void 0 : _g.clue) == null ? void 0 : _h.leads) !== void 0 && this.information.clue.leads.length > 0) {
        for (let index = 0; index < this.information.clue.leads.length; index++)
          if (this.information.clue.leads[index] !== "")
            this._addLeadEl(this.information.clue.leads[index]);
      }
      this._addLeadEl();
    });
  }
  save() {
    return __async(this, null, function* () {
      var _a, _b;
      this.information = {
        description: this.descriptionEl.value,
        clue: {
          name: this._clueTitleEl.value,
          description: this._clueDescriptionEl.value,
          leads: []
        }
      };
      for (let index = 0; index < this._leadItems.length; index++)
        if (this._leadItems[index].value !== "")
          (_b = (_a = this.information.clue) == null ? void 0 : _a.leads) == null ? void 0 : _b.push(this._leadItems[index].value);
    });
  }
  _addLeadEl(selectedElement) {
    const leadItemEl = this._leadContainerEl.createEl("input", { cls: "rpg-manager-wizard-main-content-container-clues-lead-item", type: "text", placeholder: "Add an npc or a location", value: selectedElement != null ? selectedElement : "" });
    this.api.service(LinkSuggesterService).createSimplifiedHandler(leadItemEl, this.adventure);
    leadItemEl.addEventListener("input", () => {
      if (leadItemEl.value !== "" && !this._isThereAnEmptyLeadEl)
        this._addLeadEl();
    });
    this._leadItems.push(leadItemEl);
  }
  get _isThereAnEmptyLeadEl() {
    for (let index = 0; index < this._leadItems.length; index++) {
      if (this._leadItems[index].value === "")
        return true;
    }
    return false;
  }
};

// src/services/plotWizardService/modals/AdventurePlotWizard.ts
var import_obsidian26 = require("obsidian");
var AdventurePlotWizard = class extends AbstractWizardModal {
  constructor(api, _adventureId) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    super(api);
    this._adventureId = _adventureId;
    this.steps = 8;
    this._steps = /* @__PURE__ */ new Map();
    this._adventure = this.api.database.readById(this._adventureId.id);
    this._steps.set(0, new StepIntroductionModal(this.api, this._adventureId, "Plot Creation Wizard - Adventure", `The **Plot Creation Wizard** is a tool that helps you create a more consistent plot without worrying about knowing anything about ABT or Storycircle mechanics. Follow the prompts in the next few pages and the plot will be organized for you.
			The plot is structured to provide an interesting storyline for your player characters, identifying two main goals for the **Adventure**.
			
			The first goal is what the player characters believe they want or need as the goal. The second one is the true goal of the adventure, the player characters discovers by playing. This storytelling structure creates minor narrative tension in the game, and through narrative tension you achieve variety. Take into consideration Luke Skywalker. When he left Tatooine with Obi-Wan Kenobi, he was under the impression that he was going to rescue Princess Leia and then continue to work on becoming a Jedi. However, once she was rescued from the station, he became aware that she would not be truly rescued until the station itself was destroyed. The logic is the same, and in storytelling, it works!
			
			Two areas in the plot creation wizard offer the ability to also create a Clue alongside those plot elements, which allow you to expand upon who or what your player characters will also interact with in that plot point. The suggestion is to make these types of clues as relevant and interesting as possible, and identify three other elements (*mainly Non-Player Characters and Locations*) where player characters can learn about the clue. These types of clues are meant to mark a moment of passage for the player characters in the storyline, and should be unavoidable to find`));
    this._steps.set(1, new StepDescriptionModal(this.api, this._adventureId, "What's the initial status of the player characters?", "What is the current status of the player characters? Where they are in the story and what they have decided to do at the end of the previous session?", (_a = this._adventure.storyCircle.you) != null ? _a : ""));
    this._steps.set(2, new StepDescriptionModal(this.api, this._adventureId, "What do they feel as their goal for the adventure?", "What do the player characters think they should achive in the adventure? This is the perceived goal.", (_b = this._adventure.storyCircle.go) != null ? _b : ""));
    this._steps.set(3, new StepDescriptionModal(this.api, this._adventureId, "What happens when they reach their goal?", "What do the player characters realise when they achieve their perceived goal?", (_c = this._adventure.storyCircle.find) != null ? _c : ""));
    this._steps.set(4, new StepDescriptionModal(this.api, this._adventureId, "What is the true goal of the adventure?", "What is the real goal of the adventure?", (_d = this._adventure.storyCircle.return) != null ? _d : ""));
    this._steps.set(5, new StepDescriptionModal(this.api, this._adventureId, "What convinces player characters to achieve their perceived goal?", "What happens to convince the player characters to try and achieve the perceived goal?", (_e = this._adventure.storyCircle.need) != null ? _e : ""));
    this._steps.set(6, new StepDescriptionAndCluesModal(this.api, this._adventureId, "How can they reach their perceived goal?", "What clue will lead the player characters to reach their perceived goal?", (_f = this._adventure.storyCircle.search) != null ? _f : ""));
    this._steps.set(7, new StepDescriptionAndCluesModal(this.api, this._adventureId, "When they realise the true goal of the adventure, how can they reach it?", "When they pay the price, what is the clue that will lead them to the real goal?", (_g = this._adventure.storyCircle.take) != null ? _g : ""));
    this._steps.set(8, new StepDescriptionModal(this.api, this._adventureId, "How are they going to triumph and reach the true goal of the adventure?", "How are they going to triumph?", (_h = this._adventure.storyCircle.change) != null ? _h : ""));
  }
  getStepInterface(newStep) {
    const response = this._steps.get(newStep);
    if (response === void 0)
      throw new Error("");
    return response;
  }
  _updateRecap(containerEl) {
    return __async(this, null, function* () {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
      if (!this.isInitialised) {
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "You" });
        this._youEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._youEl.addEventListener("click", () => {
          this.move(1);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Need" });
        this._needEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._needEl.addEventListener("click", () => {
          this.move(5);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Go" });
        this._goEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._goEl.addEventListener("click", () => {
          this.move(2);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Search" });
        this._searchEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._searchEl.addEventListener("click", () => {
          this.move(6);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Find" });
        this._findEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._findEl.addEventListener("click", () => {
          this.move(3);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Take" });
        this._takeEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._takeEl.addEventListener("click", () => {
          this.move(7);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Return" });
        this._returnEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._returnEl.addEventListener("click", () => {
          this.move(4);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Change" });
        this._changeEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._changeEl.addEventListener("click", () => {
          this.move(8);
        });
      }
      this._addRecapElement(this._youEl, (_b = (_a = this._steps.get(1)) == null ? void 0 : _a.data) == null ? void 0 : _b.description, this._adventure.storyCircle.you);
      this._addRecapElement(this._needEl, (_d = (_c = this._steps.get(5)) == null ? void 0 : _c.data) == null ? void 0 : _d.description, this._adventure.storyCircle.need);
      this._addRecapElement(this._goEl, (_f = (_e = this._steps.get(2)) == null ? void 0 : _e.data) == null ? void 0 : _f.description, this._adventure.storyCircle.go);
      this._addRecapElement(this._searchEl, (_h = (_g = this._steps.get(6)) == null ? void 0 : _g.data) == null ? void 0 : _h.description, this._adventure.storyCircle.search);
      this._addRecapElement(this._findEl, (_j = (_i = this._steps.get(3)) == null ? void 0 : _i.data) == null ? void 0 : _j.description, this._adventure.storyCircle.find);
      this._addRecapElement(this._takeEl, (_l = (_k = this._steps.get(7)) == null ? void 0 : _k.data) == null ? void 0 : _l.description, this._adventure.storyCircle.take);
      this._addRecapElement(this._returnEl, (_n = (_m = this._steps.get(4)) == null ? void 0 : _m.data) == null ? void 0 : _n.description, this._adventure.storyCircle.return);
      this._addRecapElement(this._changeEl, (_p = (_o = this._steps.get(8)) == null ? void 0 : _o.data) == null ? void 0 : _p.description, this._adventure.storyCircle.change);
    });
  }
  _addRecapElement(containerEl, newContent, oldContent) {
    var _a;
    containerEl.empty();
    let content = (_a = newContent != null ? newContent : oldContent) != null ? _a : "";
    if (content.length > 60)
      content = content.substring(0, 57) + "...";
    import_obsidian26.MarkdownRenderer.renderMarkdown(content, containerEl, "", null);
  }
  create() {
    return __async(this, null, function* () {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N;
      const codeblockDomain = yield this.api.service(CodeblockService).read(this._adventure.file);
      if (codeblockDomain === void 0)
        return;
      const codeblock = codeblockDomain.codeblock;
      this._createClue((_b = (_a = this._steps.get(6)) == null ? void 0 : _a.data) == null ? void 0 : _b.clue);
      this._createClue((_d = (_c = this._steps.get(7)) == null ? void 0 : _c.data) == null ? void 0 : _d.clue);
      if (codeblock.plot === void 0)
        codeblock.plot = {
          abt: {
            need: "",
            and: "",
            but: "",
            therefore: ""
          },
          storycircle: {
            you: "",
            need: "",
            go: "",
            search: "",
            find: "",
            take: "",
            return: "",
            change: ""
          }
        };
      codeblock.plot.storycircle = {
        you: (_h = (_g = (_f = (_e = this._steps.get(1)) == null ? void 0 : _e.data) == null ? void 0 : _f.description) != null ? _g : this._adventure.storyCircle.you) != null ? _h : "",
        need: (_l = (_k = (_j = (_i = this._steps.get(5)) == null ? void 0 : _i.data) == null ? void 0 : _j.description) != null ? _k : this._adventure.storyCircle.need) != null ? _l : "",
        go: (_p = (_o = (_n = (_m = this._steps.get(2)) == null ? void 0 : _m.data) == null ? void 0 : _n.description) != null ? _o : this._adventure.storyCircle.go) != null ? _p : "",
        search: ((_t = (_s = (_r = (_q = this._steps.get(6)) == null ? void 0 : _q.data) == null ? void 0 : _r.description) != null ? _s : this._adventure.storyCircle.search) != null ? _t : "") + this.getClueHint((_v = (_u = this._steps.get(6)) == null ? void 0 : _u.data) == null ? void 0 : _v.clue),
        find: (_z = (_y = (_x = (_w = this._steps.get(3)) == null ? void 0 : _w.data) == null ? void 0 : _x.description) != null ? _y : this._adventure.storyCircle.find) != null ? _z : "",
        take: ((_D = (_C = (_B = (_A = this._steps.get(7)) == null ? void 0 : _A.data) == null ? void 0 : _B.description) != null ? _C : this._adventure.storyCircle.take) != null ? _D : "") + this.getClueHint((_F = (_E = this._steps.get(7)) == null ? void 0 : _E.data) == null ? void 0 : _F.clue),
        return: (_J = (_I = (_H = (_G = this._steps.get(4)) == null ? void 0 : _G.data) == null ? void 0 : _H.description) != null ? _I : this._adventure.storyCircle.return) != null ? _J : "",
        change: (_N = (_M = (_L = (_K = this._steps.get(8)) == null ? void 0 : _K.data) == null ? void 0 : _L.description) != null ? _M : this._adventure.storyCircle.change) != null ? _N : ""
      };
      this.api.service(CodeblockService).updateDomain(codeblockDomain);
      this.close();
    });
  }
  _createClue(data) {
    return __async(this, null, function* () {
      var _a;
      if (data === void 0 || data.name === void 0 || data.name === "")
        return void 0;
      const additionalInformation = {
        data: {
          synopsis: (_a = data.description) != null ? _a : ""
        }
      };
      if (data.leads !== void 0 && data.leads.length > 0) {
        const relationships = [];
        for (let index = 0; index < data.leads.length; index++) {
          const model = this.api.database.readByBaseName(data.leads[index]);
          if (model !== void 0) {
            const relationship = {
              type: "bidirectional",
              path: model.file.path
            };
            relationships.push(relationship);
          }
        }
        additionalInformation.relationships = relationships;
      }
      this.api.service(FileCreationService).silentCreate(512 /* Clue */, data.name, this._adventureId.campaignId, this._adventureId.campaignId, void 0, additionalInformation);
    });
  }
};

// src/services/plotWizardService/modals/ActPlotWizard.ts
var import_obsidian27 = require("obsidian");
var ActPlotWizard = class extends AbstractWizardModal {
  constructor(api, _actId) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    super(api);
    this._actId = _actId;
    this.steps = 8;
    this._act = this.api.database.readById(this._actId.id);
    this._steps = /* @__PURE__ */ new Map();
    this._steps.set(0, new StepIntroductionModal(this.api, this._actId, "Plot Creation Wizard - Act", `The **Plot Creation Wizard** is a tool that helps you create a more consistent plot without worrying about knowing anything about ABT or Storycircle mechanics. Follow the prompts in the next few pages and the plot will be organized for you.
			The plot is structured to provide an interesting storyline for your player characters, identifying two main goals for the **Act**.
			
			The first goal is what the player characters believe they want or need as the goal. The second one is the true goal of the adventure, the player characters discovers by playing. This storytelling structure creates minor narrative tension in the game, and through narrative tension you achieve variety. Take into consideration Luke Skywalker. When he left Tatooine with Obi-Wan Kenobi, he was under the impression that he was going to rescue Princess Leia and then continue to work on becoming a Jedi. However, once she was rescued from the station, he became aware that she would not be truly rescued until the station itself was destroyed. The logic is the same, and in storytelling, it works!
			
			Two areas in the plot creation wizard offer the ability to also create a Clue alongside those plot elements, which allow you to expand upon who or what your player characters will also interact with in that plot point. The suggestion is to make these types of clues as relevant and interesting as possible, and identify three other elements (*mainly Non-Player Characters and Locations*) where player characters can learn about the clue. These types of clues are meant to mark a moment of passage for the player characters in the storyline, and should be unavoidable to find`));
    this._steps.set(1, new StepDescriptionModal(this.api, this._actId, "What's the initial status of the player characters?", "What is the current status of the player characters? Where they are in the story and what they have decided to do at the end of the previous session?", (_a = this._act.storyCircle.you) != null ? _a : ""));
    this._steps.set(2, new StepDescriptionModal(this.api, this._actId, "What do they feel as their goal for the act?", "What do the player characters think they should achive in the act? This is the perceived goal.", (_b = this._act.storyCircle.go) != null ? _b : ""));
    this._steps.set(3, new StepDescriptionModal(this.api, this._actId, "What happens when they reach their goal?", "What do the player characters realise when they achieve their perceived goal?", (_c = this._act.storyCircle.find) != null ? _c : ""));
    this._steps.set(4, new StepDescriptionModal(this.api, this._actId, "What is the true goal of the act?", "What is the real goal of the act?", (_d = this._act.storyCircle.return) != null ? _d : ""));
    this._steps.set(5, new StepDescriptionModal(this.api, this._actId, "What convinces player characters to achieve their perceived goal?", "What happens to convince the player characters to try and achieve the perceived goal?", (_e = this._act.storyCircle.need) != null ? _e : ""));
    this._steps.set(6, new StepDescriptionAndCluesModal(this.api, this._actId, "How can they reach their perceived goal?", "What clue will lead the player characters to reach their perceived goal?", (_f = this._act.storyCircle.search) != null ? _f : ""));
    this._steps.set(7, new StepDescriptionAndCluesModal(this.api, this._actId, "When they realise the true goal of the act, how can they reach it?", "When they pay the price, what is the clue that will lead them to the real goal?", (_g = this._act.storyCircle.take) != null ? _g : ""));
    this._steps.set(8, new StepDescriptionModal(this.api, this._actId, "How are they going to triumph and reach the true goal of the act?", "How are they going to triumph?", (_h = this._act.storyCircle.change) != null ? _h : ""));
  }
  getStepInterface(newStep) {
    const response = this._steps.get(newStep);
    if (response === void 0)
      throw new Error("");
    return response;
  }
  _updateRecap(containerEl) {
    return __async(this, null, function* () {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
      if (!this.isInitialised) {
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "You" });
        this._youEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._youEl.addEventListener("click", () => {
          this.move(1);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Need" });
        this._needEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._needEl.addEventListener("click", () => {
          this.move(5);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Go" });
        this._goEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._goEl.addEventListener("click", () => {
          this.move(2);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Search" });
        this._searchEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._searchEl.addEventListener("click", () => {
          this.move(6);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Find" });
        this._findEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._findEl.addEventListener("click", () => {
          this.move(3);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Take" });
        this._takeEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._takeEl.addEventListener("click", () => {
          this.move(7);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Return" });
        this._returnEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._returnEl.addEventListener("click", () => {
          this.move(4);
        });
        containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-title", text: "Change" });
        this._changeEl = containerEl.createDiv({ cls: "rpg-manager-wizard-main-recap-description" });
        this._changeEl.addEventListener("click", () => {
          this.move(8);
        });
      }
      this._addRecapElement(this._youEl, (_b = (_a = this._steps.get(1)) == null ? void 0 : _a.data) == null ? void 0 : _b.description, this._act.storyCircle.you);
      this._addRecapElement(this._needEl, (_d = (_c = this._steps.get(5)) == null ? void 0 : _c.data) == null ? void 0 : _d.description, this._act.storyCircle.need);
      this._addRecapElement(this._goEl, (_f = (_e = this._steps.get(2)) == null ? void 0 : _e.data) == null ? void 0 : _f.description, this._act.storyCircle.go);
      this._addRecapElement(this._searchEl, (_h = (_g = this._steps.get(6)) == null ? void 0 : _g.data) == null ? void 0 : _h.description, this._act.storyCircle.search);
      this._addRecapElement(this._findEl, (_j = (_i = this._steps.get(3)) == null ? void 0 : _i.data) == null ? void 0 : _j.description, this._act.storyCircle.find);
      this._addRecapElement(this._takeEl, (_l = (_k = this._steps.get(7)) == null ? void 0 : _k.data) == null ? void 0 : _l.description, this._act.storyCircle.take);
      this._addRecapElement(this._returnEl, (_n = (_m = this._steps.get(4)) == null ? void 0 : _m.data) == null ? void 0 : _n.description, this._act.storyCircle.return);
      this._addRecapElement(this._changeEl, (_p = (_o = this._steps.get(8)) == null ? void 0 : _o.data) == null ? void 0 : _p.description, this._act.storyCircle.change);
    });
  }
  _addRecapElement(containerEl, newContent, oldContent) {
    var _a;
    containerEl.empty();
    let content = (_a = newContent != null ? newContent : oldContent) != null ? _a : "";
    if (content.length > 60)
      content = content.substring(0, 57) + "...";
    import_obsidian27.MarkdownRenderer.renderMarkdown(content, containerEl, "", null);
  }
  create() {
    return __async(this, null, function* () {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N;
      const codeblockDomain = yield this.api.service(CodeblockService).read(this._act.file);
      if (codeblockDomain === void 0)
        return;
      const codeblock = codeblockDomain.codeblock;
      this._createClue((_b = (_a = this._steps.get(6)) == null ? void 0 : _a.data) == null ? void 0 : _b.clue);
      this._createClue((_d = (_c = this._steps.get(7)) == null ? void 0 : _c.data) == null ? void 0 : _d.clue);
      if (codeblock.plot === void 0)
        codeblock.plot = {
          abt: {
            need: "",
            and: "",
            but: "",
            therefore: ""
          },
          storycircle: {
            you: "",
            need: "",
            go: "",
            search: "",
            find: "",
            take: "",
            return: "",
            change: ""
          }
        };
      codeblock.plot.storycircle = {
        you: (_h = (_g = (_f = (_e = this._steps.get(1)) == null ? void 0 : _e.data) == null ? void 0 : _f.description) != null ? _g : this._act.storyCircle.you) != null ? _h : "",
        need: (_l = (_k = (_j = (_i = this._steps.get(5)) == null ? void 0 : _i.data) == null ? void 0 : _j.description) != null ? _k : this._act.storyCircle.need) != null ? _l : "",
        go: (_p = (_o = (_n = (_m = this._steps.get(2)) == null ? void 0 : _m.data) == null ? void 0 : _n.description) != null ? _o : this._act.storyCircle.go) != null ? _p : "",
        search: ((_t = (_s = (_r = (_q = this._steps.get(6)) == null ? void 0 : _q.data) == null ? void 0 : _r.description) != null ? _s : this._act.storyCircle.search) != null ? _t : "") + this.getClueHint((_v = (_u = this._steps.get(6)) == null ? void 0 : _u.data) == null ? void 0 : _v.clue),
        find: (_z = (_y = (_x = (_w = this._steps.get(3)) == null ? void 0 : _w.data) == null ? void 0 : _x.description) != null ? _y : this._act.storyCircle.find) != null ? _z : "",
        take: ((_D = (_C = (_B = (_A = this._steps.get(7)) == null ? void 0 : _A.data) == null ? void 0 : _B.description) != null ? _C : this._act.storyCircle.take) != null ? _D : "") + this.getClueHint((_F = (_E = this._steps.get(7)) == null ? void 0 : _E.data) == null ? void 0 : _F.clue),
        return: (_J = (_I = (_H = (_G = this._steps.get(4)) == null ? void 0 : _G.data) == null ? void 0 : _H.description) != null ? _I : this._act.storyCircle.return) != null ? _J : "",
        change: (_N = (_M = (_L = (_K = this._steps.get(8)) == null ? void 0 : _K.data) == null ? void 0 : _L.description) != null ? _M : this._act.storyCircle.change) != null ? _N : ""
      };
      this.api.service(CodeblockService).updateDomain(codeblockDomain);
      this.close();
    });
  }
  _createClue(data) {
    return __async(this, null, function* () {
      var _a;
      if (data === void 0 || data.name === void 0 || data.name === "")
        return void 0;
      const additionalInformation = {
        data: {
          synopsis: (_a = data.description) != null ? _a : ""
        }
      };
      if (data.leads !== void 0 && data.leads.length > 0) {
        const relationships = [];
        for (let index = 0; index < data.leads.length; index++) {
          const model = this.api.database.readByBaseName(data.leads[index]);
          if (model !== void 0) {
            const relationship = {
              type: "bidirectional",
              path: model.file.path
            };
            relationships.push(relationship);
          }
        }
        additionalInformation.relationships = relationships;
      }
      this.api.service(FileCreationService).silentCreate(512 /* Clue */, data.name, this._actId.campaignId, this._actId.parentId, void 0, additionalInformation);
    });
  }
};

// src/services/plotWizardService/PlotWizardService.ts
var PlotWizardService = class extends AbstractService {
  openActWizard(actId) {
    return __async(this, null, function* () {
      new ActPlotWizard(this.api, actId).open();
    });
  }
  openAdventureWizard(adventureId) {
    return __async(this, null, function* () {
      new AdventurePlotWizard(this.api, adventureId).open();
    });
  }
};

// src/components/adventure/abstracts/AbstractAdventureData.ts
var AbstractAdventureData = class extends Plots {
};

// src/components/adventure/models/AdventureModel.ts
var AdventureModel = class extends AbstractAdventureData {
  constructor() {
    super(...arguments);
    this.stage = 0 /* Plot */;
  }
  getRelationships(database) {
    const response = super.getRelationships(database);
    this.api.database.read((model) => model.index.campaignId === this.index.campaignId && model.index.parentId === this.index.id).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((model) => model.index.positionInParent),
      new SorterComparisonElement((model) => model.file.basename)
    ])).forEach((model) => {
      response.add(this.api.service(RelationshipService).createRelationship(32 /* Hierarchy */, model.file.path, void 0, model));
    });
    return response;
  }
};

// src/services/componentOptionsService/ComponentOptionsService.ts
var ComponentOptionsService = class extends AbstractService {
  render(model, containerEl) {
    if (model instanceof CampaignModel) {
      this._addFunctionality(containerEl, "Timeline").addEventListener("click", () => {
        this.api.staticViews.create("rpgm-timeline-view" /* Timeline */, [model.index]);
      });
      this._addSeparator(containerEl);
    } else {
      if (model instanceof AdventureModel) {
        this._addFunctionality(containerEl, "Wizard").addEventListener("click", () => {
          this.api.service(PlotWizardService).openAdventureWizard(model.index);
        });
        this._addSeparator(containerEl);
      }
      if (model instanceof ActModel) {
        this._addFunctionality(containerEl, "Wizard").addEventListener("click", () => {
          this.api.service(PlotWizardService).openActWizard(model.index);
        });
        this._addSeparator(containerEl);
        this._addFunctionality(containerEl, "Scene Builder").addEventListener("click", () => {
          this.api.service(SceneBuilderService).open(model);
        });
        this._addSeparator(containerEl);
      }
      if (model instanceof SessionModel) {
        this._addFunctionality(containerEl, "Manage Scenes").addEventListener("click", () => {
          new SceneSelectionModal(this.api, model).open();
        });
        this._addSeparator(containerEl);
      }
      if (model instanceof AdventureModel === false) {
        this._addFunctionality(containerEl, "Relationship").addEventListener("click", () => {
          new RelationshipsSelectionModal(this.api, model).open();
        });
        this._addSeparator(containerEl);
      }
    }
    this._addFunctionality(containerEl, "Gallery").addEventListener("click", () => {
      new GalleryManagementModal(this.api, model, this.api.service(GalleryService)).open();
    });
    if (!model.isComplete) {
      this._addSeparator(containerEl);
      this._addFunctionality(containerEl, "Complete").addEventListener("click", () => {
        this.api.service(CodeblockService).addOrUpdate("data.complete", true);
      });
    }
  }
  _addFunctionality(containerEl, description) {
    return containerEl.createDiv({ cls: "option", text: description });
  }
  _addSeparator(containerEl) {
    containerEl.createDiv({ cls: "separator", text: "|" });
  }
};

// src/services/galleryService/views/GalleryCarouselView.ts
var import_obsidian28 = require("obsidian");
var GalleryCarouselView = class {
  constructor(_api, _images) {
    this._api = _api;
    this._images = _images;
    this._currentImage = 0;
    this._imagesCount = this._images.length;
    this._imageGroups = [];
  }
  render(containerEl) {
    const carouselContainerEl = containerEl.createDiv({ cls: "rpg-manager-image-carousel" });
    this._addImageNavigator(carouselContainerEl);
    const imagesContainerEl = carouselContainerEl.createDiv({ cls: "rpg-manager-image-carousel-images" });
    this._images.forEach((image, index) => {
      this._addImageGroup(image, imagesContainerEl);
    });
    this._imageGroups[0].removeClass("rpg-manager-image-carousel-images-group-invisible");
  }
  _addImageGroup(image, containerEl) {
    const imageGroupEl = containerEl.createDiv({ cls: "rpg-manager-image-carousel-images-group rpg-manager-image-carousel-images-group-invisible" });
    const imageContainerEl = imageGroupEl.createDiv({ cls: "rpg-manager-image-carousel-images-group-container" });
    const imageEl = new Image();
    imageEl.onload = (evt) => {
      if (image.src.startsWith("http")) {
        const crsImageLink = imageContainerEl.createEl("a", { href: image.src });
        crsImageLink.append(imageEl);
      } else {
        imageContainerEl.append(imageEl);
      }
    };
    imageEl.src = image.src;
    const imageCaptionEl = imageGroupEl.createDiv({ cls: "rpg-manager-image-carousel-images-group-container" });
    if (image.caption !== "") {
      import_obsidian28.MarkdownRenderer.renderMarkdown(image.caption, imageCaptionEl, "", null);
    }
    this._imageGroups.push(imageGroupEl);
  }
  _addImageNavigator(containerEl) {
    if (this._imagesCount > 1) {
      const imageNavigatorContainerEl = containerEl.createDiv({ cls: "rpg-manager-image-carousel-images-navigator clearfix" });
      if (this._images.length > 0) {
        const previousImageNavigatorEl = imageNavigatorContainerEl.createDiv({
          cls: "rpg-manager-image-carousel-images-navigator-previous",
          text: "<<"
        });
        previousImageNavigatorEl.addEventListener("click", this._movePrevious.bind(this));
        const nextImageNavigatorEl = imageNavigatorContainerEl.createDiv({
          cls: "rpg-manager-image-carousel-images-navigator-next",
          text: ">>"
        });
        nextImageNavigatorEl.addEventListener("click", this._moveNext.bind(this));
        this._imageCounterEl = imageNavigatorContainerEl.createDiv({ cls: "rpg-manager-image-carousel-images-navigator-counter" });
      }
      this._imageCounterEl.textContent = "1/" + this._imagesCount.toString();
    }
  }
  _movePrevious() {
    this._imageGroups[this._currentImage].addClass("rpg-manager-image-carousel-images-group-invisible");
    if (this._currentImage === 0) {
      this._currentImage = this._imagesCount - 1;
    } else {
      this._currentImage--;
    }
    this._imageGroups[this._currentImage].removeClass("rpg-manager-image-carousel-images-group-invisible");
    this._imageCounterEl.textContent = (this._currentImage + 1).toString() + "/" + this._imagesCount.toString();
  }
  _moveNext() {
    this._imageGroups[this._currentImage].addClass("rpg-manager-image-carousel-images-group-invisible");
    if (this._currentImage === this._imagesCount - 1) {
      this._currentImage = 0;
    } else {
      this._currentImage++;
    }
    this._imageGroups[this._currentImage].removeClass("rpg-manager-image-carousel-images-group-invisible");
    this._imageCounterEl.textContent = (this._currentImage + 1).toString() + "/" + this._imagesCount.toString();
  }
};

// src/managers/viewsManager/abstracts/AbstractHeaderView.ts
var AbstractHeaderView = class {
  constructor(api, model, containerEl, sourcePath) {
    this.api = api;
    this.model = model;
    this.containerEl = containerEl;
    this.sourcePath = sourcePath;
    containerEl.addClass("rpg-manager-header");
    this._breadcumbContainerEl = containerEl.createDiv({ cls: "rpgm-breadcrumb" });
    this._headerContainerEl = containerEl.createDiv({ cls: "rpg-manager-header-container" });
    this.titleContainerEl = this._headerContainerEl.createDiv({ cls: "rpg-manager-header-container-title" });
    this._componentOptionsContainerEl = this._headerContainerEl.createDiv();
    this._headerInfoAndGalleryEl = this._headerContainerEl.createDiv({ cls: "rpg-manager-header-container-info rpg-manager-header-container-info-no-gallery clearfix" });
    this._infoContainerEl = this._headerInfoAndGalleryEl.createDiv({ cls: "rpg-manager-header-container-info-data" });
    this._galleryContainerEl = this._headerInfoAndGalleryEl.createDiv({ cls: "rpg-manager-header-container-info-gallery" });
    this._plotContainerEl = this._headerContainerEl.createDiv({ cls: "" });
    this._analyserContainerEl = this._headerContainerEl.createDiv({ cls: "" });
  }
  addBreadcrumb() {
    this.api.service(BreadcrumbService).render(this.model, this._breadcumbContainerEl);
  }
  addComponentOptions() {
    this._componentOptionsContainerEl.addClass("rpg-manager-component-option");
    this.api.service(ComponentOptionsService).render(this.model, this._componentOptionsContainerEl);
  }
  addTitle() {
    const titleEl = this.titleContainerEl.createDiv({ cls: "rpg-manager-header-container-title-name" });
    titleEl.textContent = this.model.file.basename;
  }
  addGallery() {
    if (this.model.images.length > 0) {
      this._headerInfoAndGalleryEl.removeClass("rpg-manager-header-container-info-no-gallery");
      new GalleryCarouselView(this.api, this.model.images).render(this._galleryContainerEl);
    }
  }
  addPlot() {
    this._plotContainerEl.addClass("rpg-manager-header-container-info-plot");
    const plotView = this.api.service(PlotService).getView();
    plotView.render(this.model, this.model.abt, this._plotContainerEl);
    plotView.render(this.model, this.model.storyCircle, this._plotContainerEl);
  }
  addAnalyser(analyser, type) {
    if (!this._analyserContainerEl.hasClass("rpg-manager-header-container-info-analyser"))
      this._analyserContainerEl.addClass("rpg-manager-header-container-info-analyser");
    analyser.render(type, this._analyserContainerEl);
  }
  addInfoElement(elementClass, data) {
    const element = this.api.views.getElement(elementClass);
    element.render(data, this._infoContainerEl);
  }
};

// src/managers/viewsManager/abstracts/AbstractElement.ts
var import_obsidian29 = require("obsidian");
var AbstractElement = class {
  constructor(api) {
    this.api = api;
  }
  createTitle(model, title, containerEl, editableField) {
    let titleClass = "rpg-manager-header-container-info-data-container-title";
    if (editableField !== void 0) {
      containerEl.addClass("rpg-manager-header-container-info-data-container-editable");
      const editEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-edit" });
      (0, import_obsidian29.setIcon)(editEl, "edit");
      editEl.addEventListener("click", () => {
        this.api.service(ContentEditorService).open(model, editableField);
      });
      titleClass = "rpg-manager-header-container-info-data-container-title-editable";
    }
    containerEl.createDiv({ cls: titleClass + " clearfix", text: title });
  }
};

// src/managers/viewsManager/elements/abstracts/AbstractTextElement.ts
var import_obsidian30 = require("obsidian");
var AbstractTextElement = class extends AbstractElement {
  renderText(data, containerEl, isLong) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-" + (isLong ? "long" : "short") + " clearfix" });
    this.createTitle(data.model, data.title, infoEl, data.editableKey);
    let contentClass = "rpg-manager-header-container-info-data-container-content";
    if (data.editableKey !== void 0)
      contentClass = "rpg-manager-header-container-info-data-container-content-editable";
    const contentEl = infoEl.createDiv({ cls: contentClass + " clearfix" });
    import_obsidian30.MarkdownRenderer.renderMarkdown(data.values, contentEl, "", null);
  }
};

// src/managers/viewsManager/elements/LongTextElement.ts
var LongTextElement = class extends AbstractTextElement {
  render(data, containerEl) {
    this.renderText(data, containerEl, true);
  }
};

// src/services/plotsService/views/elements/AbtStageElement.ts
var AbtStageElement = class extends AbstractElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const abtSelectorEl = contentEl.createEl("select");
    abtSelectorEl.createEl("option", {
      text: "",
      value: ""
    }).selected = true;
    Object.keys(AbtStage).filter((v) => isNaN(Number(v))).forEach((type, index) => {
      const abtOptionEl = abtSelectorEl.createEl("option", {
        text: type,
        value: type
      });
      if (data.values !== void 0 && data.values === this.api.service(PlotService).getAbtStage(type))
        abtOptionEl.selected = true;
    });
    abtSelectorEl.addEventListener("change", (e) => {
      if (data.editableKey !== void 0)
        this.api.service(CodeblockService).addOrUpdate(data.editableKey, abtSelectorEl.value.toLowerCase());
    });
  }
};

// src/managers/viewsManager/elements/ParentSwitcherSelectorElement.ts
var import_obsidian31 = require("obsidian");
var ParentSwitcherSelectorElement = class extends AbstractElement {
  constructor(api) {
    super(api);
    this.api = api;
    this._id = v4_default();
  }
  render(data, containerEl) {
    let selectedModel = void 0;
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const modelSelectorEl = contentEl.createEl("select");
    data.values.list.forEach((model) => {
      const sessionOptionEl = modelSelectorEl.createEl("option", {
        text: model.file.basename,
        value: model.file.path
      });
      if (data.values.index !== void 0 && data.values.index.parentId === model.index.id) {
        selectedModel = model;
        sessionOptionEl.selected = true;
      }
    });
    modelSelectorEl.addEventListener("change", (e) => {
      const selectedModel2 = this.api.database.readByPath(modelSelectorEl.value);
      if (selectedModel2 === void 0)
        return;
      const existingChildrenInParent = this.api.database.readChildren(data.model.index.type, selectedModel2.index.id).sort(this.api.service(SorterService).create([
        new SorterComparisonElement((act) => act.index.positionInParent, 1 /* Descending */)
      ]));
      let positionInParent = 1;
      if (existingChildrenInParent.length > 0)
        positionInParent = existingChildrenInParent[0].index.positionInParent + 1;
      const keyValues = /* @__PURE__ */ new Map();
      keyValues.set("parentId", selectedModel2.index.id);
      keyValues.set("positionInParent", positionInParent);
      this.api.service(CodeblockService).addOrUpdateMultipleInIndex(keyValues);
      this._addModelLink(contentEl, selectedModel2);
    });
    if (selectedModel !== void 0)
      this._addModelLink(contentEl, selectedModel);
  }
  _addModelLink(containerEl, model) {
    const previousContainer = document.getElementById(this._id);
    if (previousContainer != void 0)
      previousContainer.remove();
    if (model !== void 0) {
      const linkContainerEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content-link" });
      linkContainerEl.id = this._id;
      import_obsidian31.MarkdownRenderer.renderMarkdown(model.link, linkContainerEl, "", null);
    }
  }
};

// src/components/act/views/ActHeaderView.ts
var ActHeaderView = class extends AbstractHeaderView {
  render() {
    var _a;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    const adventures = this.api.database.readChildren(2 /* Adventure */, this.model.index.campaignId);
    this.addInfoElement(ParentSwitcherSelectorElement, { model: this.model, title: "Part of Adventure", values: { index: this.model.index, list: adventures } });
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    if (this.api.settings.usePlotStructures) {
      this.addInfoElement(AbtStageElement, {
        model: this.model,
        title: "ABT Stage",
        values: this.model.abtStage,
        editableKey: "data.abtStage"
      });
      this.addPlot();
    }
    if (this.api.settings.useSceneAnalyser) {
      const analyser = this.api.service(AnalyserService).createAct(this.model, this.model.abtStage);
      if (analyser.scenesCount > 0) {
        this.addAnalyser(analyser, 1 /* Visual */);
        this.addAnalyser(analyser, 0 /* Extended */);
      }
    }
  }
};

// src/managers/templatesManager/abstracts/AbstractComponentNoteTemplate.ts
var AbstractComponentNoteTemplate = class {
  constructor(api, campaignId) {
    this.api = api;
    this.campaignId = campaignId;
  }
};

// src/components/campaign/templates/CampaignNotesTemplate.ts
var CampaignNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Campaign Notes\n - \n\n---\n";
  }
};

// src/components/adventure/templates/AdventureNotesTemplate.ts
var AdventureNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Adventure Notes\n - \n\n---\n";
  }
};

// src/components/character/templates/CharacterNotesTemplate.ts
var CharacterNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Player Character Notes\n - \n\n---\n";
  }
};

// src/components/character/templates/NonPlayerCharacterNotesTemplate.ts
var NonPlayerCharacterNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Non Player Character Notes\n - \n\n### Non Player Character Story\n - \n\n---\n";
  }
};

// src/components/clue/templates/ClueNotesTemplate.ts
var ClueNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Clue Details\n - \n\n---\n";
  }
};

// src/components/location/templates/LocationNotesTemplate.ts
var LocationNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Location Details\n - \n\n---\n";
  }
};

// src/components/faction/templates/FactionNotesTemplate.ts
var FactionNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Faction Details\n - \n\n---\n";
  }
};

// src/components/event/templates/EventNotesTemplate.ts
var EventNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Event Details\n - \n\n---\n";
  }
};

// src/components/act/templates/ActNotesTemplate.ts
var ActNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Act Notes\n - \n\n---\n";
  }
};

// src/components/scene/templates/SceneNotesTemplate.ts
var SceneNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Scene Notes\n - \n\n---\n";
  }
};

// src/components/session/templates/SessionNotesTemplate.ts
var SessionNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    const characters = this.api.database.read((character) => character.index.type === 32 /* Character */ && character.index.campaignId === this.campaignId);
    let possibleRecappers = "";
    (characters || []).forEach((character) => {
      possibleRecappers += character.link + "/";
    });
    possibleRecappers = possibleRecappers.substring(0, possibleRecappers.length - 1);
    let response = "---\n### SessionModel Notes\n\nPrevious SessionModel Recap: " + possibleRecappers + "\n\n### Storyteller Diary\n-\n\n### End of SessionModel Feedbacks\n";
    response += this._generateFeedback("Storyteller");
    (characters || []).forEach((character) => {
      response += this._generateFeedback(character.link);
    });
    response += "---\n";
    return response;
  }
  _generateFeedback(characterName) {
    return characterName + "\n- **Notes**: \n- **Wish**: \n- **Rose**: \n\n";
  }
};

// src/components/subplot/templates/SubplotNotesTemplate.ts
var SubplotNotesTemplate = class extends AbstractComponentNoteTemplate {
  getContent() {
    return "---\n### Subplot Notes\n - \n\n---\n";
  }
};

// src/managers/templatesManager/workers/FileContentManager.ts
var import_obsidian32 = require("obsidian");
var FileContentManager = class {
  constructor(_api, _templateFileName) {
    this._api = _api;
    this._templateFileName = _templateFileName;
  }
  parse() {
    return __async(this, null, function* () {
      const templateFile = this._api.app.vault.getAbstractFileByPath(this._templateFileName);
      const content = yield this._api.app.vault.read(templateFile);
      const templateContentLines = content.split("\n").map(String);
      let frontmatterContent = "";
      let frontMatterStarted = false;
      let frontMatterCompleted = false;
      if (templateContentLines[0] !== "---") {
        frontMatterStarted = true;
        frontMatterCompleted = true;
      }
      templateContentLines.forEach((content2) => {
        if (!frontMatterCompleted) {
          if (content2 === "---") {
            if (frontMatterStarted) {
              frontMatterCompleted = true;
            } else {
              frontMatterStarted = true;
            }
          } else {
            if (frontMatterStarted && !frontMatterCompleted) {
              frontmatterContent += content2 + "\n";
            }
          }
        } else if (!frontMatterStarted) {
          frontMatterStarted = true;
          frontMatterCompleted = true;
          if (this.templateContent === void 0)
            this.templateContent = "";
          this.templateContent += content2 + "\n";
        } else {
          if (this.templateContent === void 0)
            this.templateContent = "";
          this.templateContent += content2 + "\n";
        }
      });
      if (frontmatterContent !== "")
        this.templateFrontMatter = (0, import_obsidian32.parseYaml)(frontmatterContent);
    });
  }
};

// src/managers/templatesManager/abstracts/AbstractComponentTemplate.ts
var import_obsidian33 = require("obsidian");
var AbstractComponentTemplate = class {
  constructor(api, templateName, name, id, campaignId, parentId, positionInParent, additionalInformation) {
    this.api = api;
    this.templateName = templateName;
    this.name = name;
    this.id = id;
    this.campaignId = campaignId;
    this.parentId = parentId;
    this.positionInParent = positionInParent;
    this.additionalInformation = additionalInformation;
    if ((additionalInformation == null ? void 0 : additionalInformation.data) !== void 0)
      this.data = additionalInformation.data;
  }
  generateData(existingFile) {
    return __async(this, null, function* () {
      let templateFrontmatter;
      let templateContent;
      if (this.templateName != null && this.templateName != "") {
        if (this.templateName.startsWith("internal")) {
          switch (ComponentType[this.templateName.substring(8)]) {
            case 1 /* Campaign */:
              this.internalTemplate = new CampaignNotesTemplate(this.api, this.campaignId);
              break;
            case 2 /* Adventure */:
              this.internalTemplate = new AdventureNotesTemplate(this.api, this.campaignId);
              break;
            case 4 /* Act */:
              this.internalTemplate = new ActNotesTemplate(this.api, this.campaignId);
              break;
            case 8 /* Scene */:
              this.internalTemplate = new SceneNotesTemplate(this.api, this.campaignId);
              break;
            case 16 /* Session */:
              this.internalTemplate = new SessionNotesTemplate(this.api, this.campaignId);
              break;
            case 32 /* Character */:
              this.internalTemplate = new CharacterNotesTemplate(this.api, this.campaignId);
              break;
            case 64 /* NonPlayerCharacter */:
              this.internalTemplate = new NonPlayerCharacterNotesTemplate(this.api, this.campaignId);
              break;
            case 512 /* Clue */:
              this.internalTemplate = new ClueNotesTemplate(this.api, this.campaignId);
              break;
            case 128 /* Location */:
              this.internalTemplate = new LocationNotesTemplate(this.api, this.campaignId);
              break;
            case 1024 /* Faction */:
              this.internalTemplate = new FactionNotesTemplate(this.api, this.campaignId);
              break;
            case 256 /* Event */:
              this.internalTemplate = new EventNotesTemplate(this.api, this.campaignId);
              break;
            case 4096 /* Subplot */:
              this.internalTemplate = new SubplotNotesTemplate(this.api, this.campaignId);
              break;
          }
        } else {
          const templateContentManager = new FileContentManager(this.api, this.templateName);
          yield templateContentManager.parse();
          templateFrontmatter = templateContentManager.templateFrontMatter;
          templateContent = templateContentManager.templateContent;
        }
      }
      const frontmatter = {
        alias: [],
        tags: []
      };
      this.addFrontmatterData(frontmatter);
      this._mergeFrontmatters(frontmatter, templateFrontmatter);
      if (existingFile !== void 0) {
        const activeView = app.workspace.getActiveViewOfType(import_obsidian33.MarkdownView);
        if (activeView != void 0) {
          const metadata = this.api.app.metadataCache.getFileCache(existingFile);
          if (metadata != void 0 && metadata.sections != void 0 && metadata.sections.length > 0) {
            if (metadata.sections[0].type === "yaml") {
              const editor = activeView.editor;
              const codeblockStart = { line: metadata.sections[0].position.start.line + 1, ch: 0 };
              const codeblockEnd = { line: metadata.sections[0].position.end.line, ch: 0 };
              const codeblockContent = yield editor.getRange(codeblockStart, codeblockEnd);
              const frontmatterFromFile = yield (0, import_obsidian33.parseYaml)(codeblockContent);
              this._mergeFrontmatters(frontmatter, frontmatterFromFile);
            }
          }
        }
      }
      const dataCodeblock = this.generateDataCodeBlock();
      const initialCodeblock = this.generateInitialCodeBlock();
      const lastCodeblock = this.generateLastCodeBlock();
      if (this.internalTemplate !== void 0) {
        templateContent = this.internalTemplate.getContent();
      }
      const idCodeBlock = this.generateRpgManagerIDCodeBlock(this.generateID());
      return this._generateResponse(frontmatter, dataCodeblock, initialCodeblock, templateContent, lastCodeblock, idCodeBlock);
    });
  }
  _generateResponse(frontmatter, dataCodebBlock, initialCodeBlock, mainContent, lastCodeBlock, idCodeBlock) {
    let response;
    const frontmatterString = this.api.service(YamlService).stringify(frontmatter);
    const frontmatterParsedString = frontmatterString.replaceAll("{}", "");
    response = "---\n" + frontmatterParsedString + "---\n";
    response += dataCodebBlock;
    response += initialCodeBlock;
    response += mainContent != null ? mainContent : "\n";
    if (lastCodeBlock !== void 0)
      response += lastCodeBlock;
    response += idCodeBlock;
    return response;
  }
  _mergeFrontmatters(frontmatter, additionalFrontMatter) {
    if (additionalFrontMatter != null) {
      Object.entries(frontmatter).forEach(([frontmatterElementName, frontmatterElementValue]) => {
        if (typeof frontmatterElementValue !== "object") {
          if (additionalFrontMatter[frontmatterElementName] != null)
            frontmatter[frontmatterElementName] = additionalFrontMatter[frontmatterElementName];
        } else {
          if (this._isArray(frontmatterElementValue)) {
            if (additionalFrontMatter[frontmatterElementName] != null) {
              if (this._isArray(additionalFrontMatter[frontmatterElementName])) {
                Object.entries(additionalFrontMatter[frontmatterElementName]).forEach(([additionalFrontmatterElementName, additionalFrontmatterElementValue]) => {
                  let index;
                  Object.entries(frontmatterElementValue).forEach(([frontmatterSubElementName, frontmatterSubElementValue]) => {
                    if (additionalFrontmatterElementValue === frontmatterSubElementValue)
                      index = +frontmatterSubElementName;
                  });
                  if (index === void 0) {
                    if (!additionalFrontmatterElementValue.startsWith("rpgm/template/") && this.api.service(TagService).getTemplateDataType([additionalFrontmatterElementValue]) === void 0) {
                      frontmatterElementValue[frontmatterElementValue.length] = additionalFrontmatterElementValue;
                    }
                  }
                });
              } else {
                this._mergeFrontmatters(frontmatterElementValue, additionalFrontMatter[frontmatterElementName]);
              }
            }
          } else {
            this._mergeFrontmatters(frontmatterElementValue, additionalFrontMatter[frontmatterElementName]);
          }
        }
        if (typeof frontmatter[frontmatterElementValue] === "object" && additionalFrontMatter[frontmatterElementName] != null) {
          frontmatter[frontmatterElementName] = additionalFrontMatter[frontmatterElementName];
        }
      });
      Object.entries(additionalFrontMatter).forEach(([name, childFrontmatter]) => {
        if (frontmatter[name] == null) {
          if (typeof childFrontmatter === "string") {
            if (!childFrontmatter.startsWith("rpgm/template"))
              frontmatter[name] = childFrontmatter;
          } else {
            frontmatter[name] = childFrontmatter;
          }
        }
      });
    }
  }
  _isArray(list) {
    let response = false;
    Object.entries(list).forEach(([index, value]) => {
      if (!isNaN(+index)) {
        response = true;
      }
    });
    return response;
  }
  addFrontmatterData(frontmatter) {
  }
  generateDataCodeBlock() {
    return "";
  }
  generateInitialCodeBlock() {
    return "";
  }
  generateLastCodeBlock() {
    return void 0;
  }
  generateRpgManagerDataCodeBlock(metadata) {
    var _a, _b, _c;
    if (((_a = this.data) == null ? void 0 : _a.synopsis) !== void 0)
      metadata.data.synopsis = this.data.synopsis;
    if (((_b = this.data) == null ? void 0 : _b.images) !== void 0)
      metadata.data.images = this.data.images;
    if (((_c = this.additionalInformation) == null ? void 0 : _c.relationships) !== void 0)
      metadata.relationships = this.additionalInformation.relationships;
    let response = "```RpgManagerData\n";
    response += this.api.service(YamlService).stringify(metadata);
    response += "```\n";
    return response.replaceAll("''", "").replaceAll('""', "").replaceAll("{}", "");
  }
  generateRpgManagerCodeBlock(metadata) {
    let response = "```RpgManager\n";
    response += this.api.service(YamlService).stringify(metadata);
    response += "```\n";
    return response.replaceAll("''", "").replaceAll('""', "").replaceAll("{}", "");
  }
  generateRpgManagerIDCodeBlock(index) {
    let response = "```RpgManagerID\n";
    response += "### DO NOT EDIT MANUALLY IF NOT INSTRUCTED TO DO SO ###\n";
    response += this.api.service(YamlService).stringify(index);
    response += "```\n";
    return response;
  }
};

// src/components/act/templates/ActTemplate.ts
var ActTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      plot: {
        abt: {
          need: "",
          and: "",
          but: "",
          therefore: ""
        },
        storycircle: {
          you: "",
          need: "",
          go: "",
          search: "",
          find: "",
          take: "",
          return: "",
          change: ""
        }
      },
      data: {
        synopsis: "",
        complete: false,
        abtStage: ""
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateLastCodeBlock() {
    const metadata = {
      models: {
        lists: {
          scenes: {
            relationship: "hierarchy"
          },
          pcs: {
            relationship: "unidirectional"
          },
          npcs: {
            relationship: "unidirectional"
          },
          clues: {
            relationship: "unidirectional"
          },
          locations: {
            relationship: "unidirectional"
          },
          factions: {
            relationship: "unidirectional"
          }
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    const previousActs = this.api.database.read((act) => act.index.type === 4 /* Act */ && act.index.campaignId === this.campaignId && act.index.parentId === this.parentId).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((act) => act.index.positionInParent, 1 /* Descending */)
    ]));
    const positionInParent = previousActs.length === 0 ? 1 : previousActs[0].index.positionInParent + 1;
    if (this.id === void 0)
      this.id = this.api.service(IndexService).createUUID();
    return {
      type: 4 /* Act */,
      campaignSettings: 0 /* Agnostic */,
      campaignId: this.campaignId,
      parentId: this.parentId,
      id: this.id,
      positionInParent
    };
  }
};

// src/managers/viewsManager/abstracts/AbstractRelationshipView.ts
var import_obsidian34 = require("obsidian");

// src/services/fantasyCalendarService/sorters/FantasyCalendarSorterComparisonElement.ts
var FantasyCalendarSorterComparisonElement = class {
  constructor(comparisonElement, sortType = 0 /* Ascending */) {
    this.comparisonElement = comparisonElement;
    this.sortType = sortType;
  }
  sortFunction(leftData, rightData) {
    const left = this.comparisonElement(leftData);
    const right = this.comparisonElement(rightData);
    if (left === void 0 && right === void 0)
      return 0;
    if (left === void 0 && right !== void 0)
      return this.sortType === 0 /* Ascending */ ? -1 : 1;
    if (left !== void 0 && right === void 0)
      return this.sortType === 0 /* Ascending */ ? 1 : -1;
    if (left !== void 0 && right !== void 0) {
      if (left.year > right.year)
        return this.sortType === 0 /* Ascending */ ? 1 : -1;
      if (left.year < right.year)
        return this.sortType === 0 /* Ascending */ ? -1 : 1;
      if (left.month > right.month)
        return this.sortType === 0 /* Ascending */ ? 1 : -1;
      if (left.month < right.month)
        return this.sortType === 0 /* Ascending */ ? -1 : 1;
      if (left.day > right.day)
        return this.sortType === 0 /* Ascending */ ? 1 : -1;
      if (left.day < right.day)
        return this.sortType === 0 /* Ascending */ ? -1 : 1;
    }
    return 0;
  }
};

// src/components/scene/abstracts/AbstractSceneData.ts
var AbstractSceneData = class extends AbstractModel {
  get action() {
    var _a;
    const response = (_a = this.metadata.data) == null ? void 0 : _a.action;
    if (response === void 0 || response === "")
      return void 0;
    return response;
  }
  get trigger() {
    var _a;
    const response = (_a = this.metadata.data) == null ? void 0 : _a.trigger;
    if (response === void 0 || response === "")
      return void 0;
    return response;
  }
  get date() {
    var _a;
    return this.api.service(DateService).getDate((_a = this.metadata.data) == null ? void 0 : _a.date, "RPG Manager Scene" /* Scene */, this);
  }
  get isExciting() {
    var _a;
    return ((_a = this.metadata.data) == null ? void 0 : _a.isActedUpon) !== void 0 && this.metadata.data.isActedUpon === true;
  }
  get sceneType() {
    var _a;
    if (((_a = this.metadata.data) == null ? void 0 : _a.sceneType) == void 0 || this.metadata.data.sceneType === "")
      return void 0;
    return this.api.service(AnalyserService).getSceneType(this.metadata.data.sceneType);
  }
  get storyCircleStage() {
    var _a;
    if (((_a = this.metadata.data) == null ? void 0 : _a.storyCircleStage) == void 0 || this.metadata.data.storyCircleStage === "")
      return void 0;
    return this.api.service(PlotService).getStoryCircleStage(this.metadata.data.storyCircleStage);
  }
};

// src/components/scene/models/SceneModel.ts
var SceneModel = class extends AbstractSceneData {
  constructor() {
    super(...arguments);
    this.stage = 0 /* Plot */;
  }
  validateHierarchy() {
    super.validateHierarchy();
    try {
      this.act.validateHierarchy();
    } catch (e) {
      throw new ComponentNotFoundError(this.api, this.index);
    }
  }
  get act() {
    return this.api.database.readById(this.index.parentId);
  }
  get adventure() {
    return this.api.database.readById(this.act.index.parentId);
  }
  get currentDuration() {
    var _a, _b;
    if (((_a = this.metadata.data) == null ? void 0 : _a.durations) === void 0 || ((_b = this.metadata.data) == null ? void 0 : _b.durations.length) === 0)
      return 0;
    let response = 0;
    for (let index = 0; index < this.metadata.data.durations.length; index++) {
      const duration2 = this.metadata.data.durations[index];
      if (duration2.indexOf("-") === -1)
        continue;
      const [start, end] = duration2.split("-");
      response += +end - +start;
    }
    return response;
  }
  get duration() {
    if (this.currentDuration === 0)
      return "00:00";
    const hours = Math.floor(this.currentDuration / (60 * 60));
    const minutes = Math.floor((this.currentDuration - hours * 60 * 60) / 60);
    return (hours < 10 ? "0" + hours.toString() : hours.toString()) + ":" + (minutes < 10 ? "0" + minutes.toString() : minutes.toString());
  }
  get expectedDuration() {
    var _a, _b;
    if (this.sceneType == void 0)
      return 0;
    const previousDurations = (_b = (_a = this.api.service(RunningTimeService).medianTimes.get(this.index.campaignId)) == null ? void 0 : _a.get(this.sceneType)) != null ? _b : [];
    previousDurations.sort((left, right) => {
      if (left > right)
        return 1;
      if (left < right)
        return -1;
      return 0;
    });
    if (previousDurations.length === 0)
      return 0;
    if (previousDurations.length === 1)
      return previousDurations[0];
    if (previousDurations.length % 2 === 0) {
      const previous = previousDurations[previousDurations.length / 2];
      const next = previousDurations[previousDurations.length / 2 - 1];
      return Math.floor((previous + next) / 2);
    } else {
      return previousDurations[(previousDurations.length - 1) / 2];
    }
  }
  get isActive() {
    var _a;
    if (this.sceneType == void 0)
      return false;
    return (_a = activeSceneTypes.get(this.sceneType)) != null ? _a : false;
  }
  get isCurrentlyRunning() {
    var _a, _b, _c;
    if (((_a = this.metadata.data) == null ? void 0 : _a.durations) == void 0)
      return false;
    for (let index = 0; index < ((_b = this.metadata.data) == null ? void 0 : _b.durations.length); index++) {
      if (((_c = this.metadata.data) == null ? void 0 : _c.durations[index].indexOf("-")) === -1)
        return true;
    }
    return false;
  }
  get lastStart() {
    var _a, _b, _c, _d;
    if (!this.isCurrentlyRunning || ((_a = this.metadata.data) == null ? void 0 : _a.durations) == void 0)
      return 0;
    for (let index = 0; index < ((_b = this.metadata.data) == null ? void 0 : _b.durations.length); index++) {
      if (((_c = this.metadata.data) == null ? void 0 : _c.durations[index].indexOf("-")) === -1)
        return +((_d = this.metadata.data) == null ? void 0 : _d.durations[index]);
    }
    return 0;
  }
  get nextScene() {
    return this._adjacentScene(true);
  }
  get previousScene() {
    return this._adjacentScene(false);
  }
  get session() {
    var _a, _b;
    if (((_b = (_a = this.metadata) == null ? void 0 : _a.data) == null ? void 0 : _b.sessionId) === void 0 || this.metadata.data.sessionId === "")
      return void 0;
    const sessions = this.api.database.read((session) => {
      var _a2;
      return session.index.type === 16 /* Session */ && session.index.campaignId === this.index.campaignId && session.index.id === ((_a2 = this.metadata.data) == null ? void 0 : _a2.sessionId);
    });
    if (sessions.length !== 1)
      return void 0;
    return sessions[0];
  }
  get positionInSession() {
    var _a, _b;
    return (_b = (_a = this.metadata) == null ? void 0 : _a.data) == null ? void 0 : _b.positionInSession;
  }
  _adjacentScene(next) {
    try {
      return this.api.database.readNeighbour(8 /* Scene */, this.index, !next);
    } catch (e) {
      return null;
    }
  }
};

// src/managers/viewsManager/abstracts/AbstractRelationshipView.ts
var AbstractRelationshipView = class {
  constructor(api, model, containerEl, sourcePath) {
    this.api = api;
    this.model = model;
    this.containerEl = containerEl;
    this.sourcePath = sourcePath;
    this._relationshipSortingMap = /* @__PURE__ */ new Map();
    this.canBeOrdered = false;
    this._draggedRow = void 0;
    this._initialPosition = void 0;
    this._initialId = void 0;
    this._newPosition = void 0;
    this._componentSortingMap = /* @__PURE__ */ new Map();
    this._cellClass = /* @__PURE__ */ new Map();
    this._relationshipSortingMap = /* @__PURE__ */ new Map();
    if (this.model.campaign.calendar === 0 /* Gregorian */) {
      this._relationshipSortingMap.set(256 /* Event */, [
        new SorterComparisonElement((component) => {
          var _a;
          return (_a = component.component.date) == null ? void 0 : _a.date;
        })
      ]);
    } else {
      this._relationshipSortingMap.set(256 /* Event */, [
        new FantasyCalendarSorterComparisonElement((component) => {
          var _a;
          return (_a = component.component.date) == null ? void 0 : _a.date;
        })
      ]);
    }
    this._relationshipSortingMap.set(16 /* Session */, [
      new SorterComparisonElement((component) => component.component.index.positionInParent)
    ]);
    this._relationshipSortingMap.set(2 /* Adventure */, [
      new SorterComparisonElement((component) => component.component.index.positionInParent)
    ]);
    this._relationshipSortingMap.set(4 /* Act */, [
      new SorterComparisonElement((component) => component.component.index.parentPosition),
      new SorterComparisonElement((component) => component.component.index.positionInParent)
    ]);
    this._relationshipSortingMap.set(8 /* Scene */, [
      new SorterComparisonElement((component) => component.component.index.parentPosition),
      new SorterComparisonElement((component) => component.component.index.positionInParent)
    ]);
    this._cellClass.set(6 /* Date */, ["smaller", "inline"]);
    this._cellClass.set(11 /* Duration */, ["smaller"]);
    this._cellClass.set(0 /* Index */, ["smaller"]);
    this._cellClass.set(3 /* Age */, ["smaller"]);
    this._cellClass.set(7 /* Url */, ["smaller", "inline"]);
    this._cellClass.set(13 /* SceneExciting */, ["smaller"]);
    this._cellClass.set(12 /* SceneType */, ["smaller"]);
    this._cellClass.set(5 /* Found */, ["smaller"]);
    this._cellClass.set(2 /* Name */, ["inline"]);
    this._cellClass.set(1 /* Image */, ["image"]);
  }
  render() {
    if (this.model instanceof CampaignModel && this.relatedComponentType !== 2 /* Adventure */ && this.relatedComponentType !== 16 /* Session */)
      this.canBeOrdered = false;
    if (this.relationshipType === void 0)
      this.relationshipType = 1 /* Reversed */ | 2 /* Bidirectional */ | 4 /* Unidirectional */;
    if (this.relationshipType === 4 /* Unidirectional */)
      this.relationshipType = 4 /* Unidirectional */ | 2 /* Bidirectional */;
    this._fields = this.api.service(RelationshipService).getTableFields(this.relatedComponentType);
    this._relationships = this.model.getRelationships().filter((relationship) => relationship.component !== void 0 && relationship.component.index.type === this.relatedComponentType && (this.relationshipType === void 0 || (this.relationshipType & relationship.type) === relationship.type));
    if (this._relationships.length > 0) {
      let sorter = void 0;
      if (this.relatedComponentType === 8 /* Scene */ && this.model instanceof SessionModel)
        sorter = [new SorterComparisonElement((component) => component.component.positionInSession)];
      else
        sorter = this._relationshipSortingMap.get(this.relatedComponentType);
      if (sorter === void 0)
        sorter = [new SorterComparisonElement((relationship) => relationship.component.file.basename)];
      this._relationships.sort(this.api.service(SorterService).create(sorter));
      this._addTitle();
      this._tableEl = this.containerEl.createEl("table", { cls: "rpg-manager-table" });
      this._addHeaders();
      this._addRelationships();
    }
  }
  _addTitle() {
    var _a;
    const headerEl = this.containerEl.createEl("h3", { cls: "rpg-manager-table-header" });
    const arrowEl = headerEl.createSpan();
    arrowEl.style.marginRight = "10px";
    (0, import_obsidian34.setIcon)(arrowEl, "openClose");
    const arrowIconEl = arrowEl.children[0];
    arrowIconEl.style.transform = "rotate(90deg)";
    headerEl.createSpan({ text: (_a = this.relationshipTitle) != null ? _a : ComponentType[this.relatedComponentType] + "s" });
    headerEl.addEventListener("click", () => {
      if (this._tableEl.style.display === "none") {
        this._tableEl.style.display = "";
        arrowIconEl.style.transform = "rotate(90deg)";
      } else {
        this._tableEl.style.display = "none";
        arrowIconEl.style.transform = "rotate(0deg)";
      }
    });
  }
  _addHeaders() {
    const tableHeader = this._tableEl.createTHead();
    const headerRow = tableHeader.insertRow();
    if (this.canBeOrdered) {
      const cell = headerRow.createEl("th");
      cell.addClass("rpg-manager-table-draggable-title");
      const iconEl = cell.createSpan();
      (0, import_obsidian34.setIcon)(iconEl, "grip-horizontal");
    }
    this._fields.forEach((field) => {
      var _a;
      const cell = headerRow.createEl("th");
      if (field === 8 /* StoryCircleIndicator */)
        cell.textContent = "";
      else if (field === 0 /* Index */)
        cell.textContent = "#";
      else
        cell.textContent = (_a = tableFieldName.get(field)) != null ? _a : "";
      if (this.api.service(RelationshipService).getTableFieldInline(this.relatedComponentType, field))
        cell.addClass("inline");
    });
    headerRow.insertCell();
  }
  _dragStart(evt) {
    const target = evt.target;
    if (target != void 0) {
      const initialValidPosition = target.dataset.position;
      const initialValidId = target.dataset.id;
      if (initialValidPosition !== void 0 && initialValidId !== void 0) {
        this._initialPosition = +initialValidPosition;
        this._initialId = initialValidId;
      }
      this._draggedRow = target;
    }
  }
  _dragEnd() {
    if (this._initialPosition === void 0 || this._newPosition === void 0 || this._initialId === void 0)
      return;
    for (let index = 1; index < this._tableEl.rows.length; index++) {
      const originalValidPosition = this._tableEl.rows[index].dataset.position;
      const originalValidId = this._tableEl.rows[index].dataset.id;
      if (originalValidPosition !== void 0 && originalValidId !== void 0 && index !== +originalValidPosition) {
        try {
          const element = this.api.database.readById(originalValidId);
          if (element !== void 0) {
            if (this.model instanceof SessionModel && element instanceof SceneModel)
              this.api.service(CodeblockService).addOrUpdate("data.positionInSession", index, element.file);
            else
              this.api.service(CodeblockService).addOrUpdateInIndex("positionInParent", index, element.file);
          }
        } catch (e) {
        }
      }
      this._tableEl.rows[index].children[1].textContent = index.toString();
    }
  }
  _dragOver(evt) {
    if (evt != void 0 && this._draggedRow != void 0) {
      evt.preventDefault();
      if (evt.target != void 0) {
        const target = evt.target;
        if (target.parentNode != void 0 && target.parentNode.parentNode != void 0) {
          const children = Array.from(target.parentNode.parentNode.children);
          const parentNode = target.parentNode;
          const newValidPosition = parentNode.dataset.position;
          if (newValidPosition !== void 0 && +newValidPosition !== this._initialPosition)
            this._newPosition = +newValidPosition;
          if (children.indexOf(parentNode) > children.indexOf(this._draggedRow))
            try {
              parentNode.after(this._draggedRow);
            } catch (e) {
            }
          else
            try {
              parentNode.before(this._draggedRow);
            } catch (e) {
            }
        }
      }
    }
  }
  _addRelationships() {
    const tableBody = this._tableEl.createTBody();
    let index = 0;
    this._relationships.forEach((relationship) => {
      var _a, _b, _c;
      index++;
      const relationshipRow = tableBody.insertRow();
      relationshipRow.dataset.id = (_a = relationship.component) == null ? void 0 : _a.index.id;
      if (this.model instanceof SessionModel && relationship.component instanceof SceneModel)
        relationshipRow.dataset.position = (_b = relationship.component.positionInSession) == null ? void 0 : _b.toString();
      else
        relationshipRow.dataset.position = (_c = relationship.component) == null ? void 0 : _c.index.positionInParent.toString();
      if (this.canBeOrdered) {
        relationshipRow.draggable = true;
        relationshipRow.ondragstart = this._dragStart.bind(this);
        relationshipRow.ondragover = this._dragOver.bind(this);
        relationshipRow.ondragend = this._dragEnd.bind(this);
        const cell = relationshipRow.insertCell();
        cell.addClass("rpg-manager-table-draggable");
        const iconEl = cell.createSpan();
        (0, import_obsidian34.setIcon)(iconEl, "grip-horizontal");
      }
      this._fields.forEach((field) => {
        var _a2;
        const cell = relationshipRow.insertCell();
        const classes = this._cellClass.get(field);
        if (classes !== void 0)
          cell.addClasses(classes);
        if (relationship.component !== void 0) {
          const value = this.getDefaultFieldValue(index, field, relationship.component, relationship.description);
          if (value === "") {
            cell.textContent = "";
          } else {
            let image = void 0;
            let svgContainer = void 0;
            let editedValue = "";
            switch (field) {
              case 1 /* Image */:
                image = new Image(50, 50);
                image.onerror = (evt) => {
                  cell.textContent = "";
                  return;
                };
                image.onload = (evt) => {
                  image.style.objectFit = "cover";
                  cell.append(image);
                  cell.style.width = image.style.width;
                };
                image.src = value;
                break;
              case 12 /* SceneType */:
                editedValue = (_a2 = sceneTypeDescription.get(+value)) != null ? _a2 : "";
                editedValue = editedValue.substring(0, editedValue.indexOf(":"));
                cell.textContent = editedValue;
                break;
              case 13 /* SceneExciting */:
                cell.textContent = value === String(true) ? "Yes" : "";
                break;
              case 11 /* Duration */:
                if (value !== "00:00")
                  cell.textContent = value;
                break;
              case 8 /* StoryCircleIndicator */:
                svgContainer = cell.createDiv();
                (0, import_obsidian34.setIcon)(svgContainer, "pieEighth");
                svgContainer.style.transform = "rotate(" + (+value * 45).toString() + "deg)";
                break;
              default:
                import_obsidian34.MarkdownRenderer.renderMarkdown(this.getDefaultFieldValue(index, field, relationship.component, relationship.description), cell, this.sourcePath, null);
                break;
            }
          }
        }
      });
      const editCell = relationshipRow.insertCell();
      const isRowEditable = this.relationshipType !== void 0 && (relationship.type !== 8 /* Parent */ && relationship.type !== 32 /* Hierarchy */);
      if (isRowEditable) {
        editCell.addClass("rpg-manager-table-editor-container");
        const editorEl = editCell.createDiv({ cls: "rpg-manager-table-editor" });
        (0, import_obsidian34.setIcon)(editorEl, "edit");
        editorEl.addEventListener("click", () => {
          this.api.service(ContentEditorService).open(this.model, relationship.path);
        });
      }
    });
  }
  getDefaultFieldValue(index, field, model, description) {
    var _a;
    switch (field) {
      case 0 /* Index */:
        return index.toString();
      case 4 /* Synopsis */:
        return description != void 0 && description !== "" ? description : (_a = model.synopsis) != null ? _a : "";
      case 1 /* Image */:
        return model.images.length > 0 ? model.images[0].src : "";
      case 2 /* Name */:
        return model.link;
    }
    return this.getFieldValue(field, model);
  }
};

// src/components/act/views/ActRelationshipView.ts
var ActRelationshipView = class extends AbstractRelationshipView {
  constructor() {
    super(...arguments);
    this.canBeOrdered = true;
  }
  getFieldValue(field, model) {
    return "";
  }
};

// src/managers/modalsManager/abstracts/AbstractModalPart.ts
var AbstractModalPart = class {
  constructor(api, modal) {
    this.api = api;
    this.modal = modal;
  }
  prepareAdditionalInformation() {
    return null;
  }
  save(settings, type, create, templateName, name, campaignId, adventureId, actId, sceneId, sessionId, additionalInformation) {
    return __async(this, null, function* () {
      let parentId = campaignId;
      switch (type) {
        case 4 /* Act */:
          parentId = adventureId;
          break;
        case 8 /* Scene */:
          parentId = actId;
          break;
      }
      if (parentId === void 0)
        return;
      this.api.service(FileCreationService).create(settings, type, create, templateName, name, campaignId, parentId, additionalInformation);
      return Promise.resolve(void 0);
    });
  }
};

// src/components/act/modals/ActModalPart.ts
var ActModalPart = class extends AbstractModalPart {
  constructor(api, modal) {
    super(api, modal);
    this._acts = this.api.database.read((component) => component.index.type === 4 /* Act */ && component.index.campaignId === this.modal.campaignId && component.index.parentId === this.modal.adventureId);
  }
  addElement(contentEl) {
    return __async(this, null, function* () {
      const actEl = contentEl.createDiv({ cls: "actContainer" });
      if (this.modal.type === 4 /* Act */) {
        this.addAdditionalElements();
      } else {
        if (this._acts.length === 0) {
          const mainContent = this.modal.getContentEl();
          mainContent.empty();
          mainContent.createEl("h2", { cls: "rpgm-modal-title", text: "Acts missing" });
          mainContent.createSpan({ cls: "", text: "This Obsidian Vault does not contain a Rpg Manager ActModel for the selected adventure. Before creating a " + ComponentType[this.modal.type] + ", please initialise your first act for the adventure." });
        } else {
          this._childEl = contentEl.createDiv({ cls: "child" });
          this._childEl.id = "ActChild";
          this._selectActElements(actEl);
        }
      }
      if (this.modal.type === 4 /* Act */) {
        this.modal.saver = this;
        this.modal.enableButton();
      }
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
      this.modal.sceneModal = this.api.modals.getPartial(this.modal.campaignSetting, 8 /* Scene */, this.modal);
      this.modal.sceneModal.addElement(containerEl);
    });
  }
  validate() {
    if (this.modal.actId === void 0)
      this.modal.actId = this.api.service(IndexService).createUUID();
    return true;
  }
  _selectActElements(containerEl) {
    const groupElement = containerEl.createDiv({ cls: "rpg-manager-modal-grid-navigation-group clearfix" });
    groupElement.createDiv({ cls: "rpg-manager-modal-grid-navigation-group-title", text: "Act" });
    const selectionContainerEl = groupElement.createDiv({ cls: "rpg-manager-modal-grid-navigation-group-container" });
    this._actEl = selectionContainerEl.createEl("select");
    if (this._acts.length > 1) {
      this._actEl.createEl("option", {
        text: "",
        value: ""
      }).selected = true;
    }
    this._acts.forEach((act) => {
      const actOptionEl = this._actEl.createEl("option", {
        text: act.file.basename,
        value: act.index.id
      });
      if (this._acts.length === 1 || this.modal.actId === act.index.id) {
        actOptionEl.selected = true;
        this._selectAct();
      }
    });
    this._actEl.addEventListener("change", (e) => {
      this._selectAct();
    });
    this._actErrorEl = containerEl.createEl("p", { cls: "error" });
  }
  _selectAct() {
    this.modal.actId = this._actEl.value;
    this._childEl.empty();
    this.loadChild(this._childEl);
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/act/ActComponent.ts
var ActComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [ActModalPart];
  }
  get model() {
    return ActModel;
  }
  get template() {
    return ActTemplate;
  }
  get type() {
    return 4 /* Act */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [ActHeaderView, 0 /* Header */],
      [ActRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/components/adventure/views/AdventureHeaderView.ts
var AdventureHeaderView = class extends AbstractHeaderView {
  render() {
    var _a;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    if (this.api.settings.usePlotStructures)
      this.addPlot();
  }
};

// src/components/adventure/templates/AdventureTemplate.ts
var AdventureTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      plot: {
        abt: {
          need: "",
          and: "",
          but: "",
          therefore: ""
        },
        storycircle: {
          you: "",
          need: "",
          go: "",
          search: "",
          find: "",
          take: "",
          return: "",
          change: ""
        }
      },
      data: {
        synopsis: "",
        complete: false
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateLastCodeBlock() {
    const metadata = {
      models: {
        lists: {
          acts: {
            relationship: "hierarchy"
          }
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    const previousAdventures = this.api.database.read((adventure) => adventure.index.type === 2 /* Adventure */ && adventure.index.campaignId === this.campaignId).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((adventure) => adventure.index.positionInParent, 1 /* Descending */)
    ]));
    const positionInParent = previousAdventures.length === 0 ? 1 : previousAdventures[0].index.positionInParent + 1;
    if (this.id === void 0)
      this.id = this.api.service(IndexService).createUUID();
    return {
      type: 2 /* Adventure */,
      campaignSettings: 0 /* Agnostic */,
      id: this.id,
      campaignId: this.campaignId,
      parentId: this.parentId,
      positionInParent
    };
  }
};

// src/components/adventure/views/AdvenureRelationshipView.ts
var AdvenureRelationshipView = class extends AbstractRelationshipView {
  constructor() {
    super(...arguments);
    this.canBeOrdered = true;
  }
  getFieldValue(field, model) {
    return "";
  }
};

// src/components/adventure/modals/AdventureModalPart.ts
var AdventureModalPart = class extends AbstractModalPart {
  constructor(api, modal) {
    super(api, modal);
    this._adventures = this.api.database.read((component) => component.index.type === 2 /* Adventure */ && component.index.campaignId === this.modal.campaignId);
  }
  addElement(contentEl) {
    return __async(this, null, function* () {
      const adventureEl = contentEl.createDiv({ cls: "adventureContainer" });
      if (this.modal.type === 2 /* Adventure */) {
        this.addAdditionalElements();
      } else {
        if (this._adventures.length === 0) {
          const mainContent = this.modal.getContentEl();
          mainContent.empty();
          mainContent.createEl("h2", { cls: "rpgm-modal-title", text: "Adventures missing" });
          mainContent.createSpan({ cls: "", text: "This Obsidian Vault does not contain a Rpg Manager AdventureModel for the selected campaign. Before creating a " + ComponentType[this.modal.type] + ", please initialise your first adventure for the campaign." });
        } else {
          this._childEl = contentEl.createDiv({ cls: "child" });
          this._childEl.id = "AdventureChild";
          this._selectAdventureElements(adventureEl);
        }
      }
      if (this.modal.type === 2 /* Adventure */) {
        this.modal.saver = this;
        this.modal.enableButton();
      }
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
      this.modal.actModal = this.api.modals.getPartial(this.modal.campaignSetting, 4 /* Act */, this.modal);
      this.modal.actModal.addElement(containerEl);
    });
  }
  validate() {
    if (this.modal.adventureId === void 0)
      this.modal.adventureId = this.api.service(IndexService).createUUID();
    return true;
  }
  _selectAdventureElements(containerEl) {
    const groupElement = containerEl.createDiv({ cls: "rpg-manager-modal-grid-navigation-group clearfix" });
    groupElement.createDiv({ cls: "rpg-manager-modal-grid-navigation-group-title", text: "Adventure" });
    const selectionContainerEl = groupElement.createDiv({ cls: "rpg-manager-modal-grid-navigation-group-container" });
    this._adventureEl = selectionContainerEl.createEl("select");
    if (this._adventures.length > 1) {
      this._adventureEl.createEl("option", {
        text: "",
        value: ""
      }).selected = true;
    }
    this._adventures.forEach((adventure) => {
      const adventureOptionEl = this._adventureEl.createEl("option", {
        text: adventure.file.basename,
        value: adventure.index.id.toString()
      });
      if (this._adventures.length === 1 || this.modal.adventureId === adventure.index.id) {
        adventureOptionEl.selected = true;
        this._selectAdventure();
      }
    });
    this._adventureEl.addEventListener("change", (e) => {
      this._selectAdventure();
    });
    this._adventureErrorEl = containerEl.createEl("p", { cls: "error" });
  }
  _selectAdventure() {
    this.modal.adventureId = this._adventureEl.value;
    this._childEl.empty();
    this.loadChild(this._childEl);
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/adventure/AdventureComponent.ts
var AdventureComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [AdventureModalPart];
  }
  get model() {
    return AdventureModel;
  }
  get template() {
    return AdventureTemplate;
  }
  get type() {
    return 2 /* Adventure */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [AdventureHeaderView, 0 /* Header */],
      [AdvenureRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/managers/viewsManager/elements/ModelSelectorElement.ts
var import_obsidian35 = require("obsidian");
var ModelSelectorElement = class extends AbstractElement {
  render(data, containerEl) {
    let selectedModel = void 0;
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const modelSelectorEl = contentEl.createEl("select");
    modelSelectorEl.createEl("option", {
      text: "",
      value: ""
    }).selected = true;
    data.values.list.forEach((model) => {
      const sessionOptionEl = modelSelectorEl.createEl("option", {
        text: model.file.basename,
        value: model.file.path
      });
      if (data.values.index !== void 0 && data.values.index.id === model.index.id) {
        selectedModel = model;
        sessionOptionEl.selected = true;
      }
    });
    modelSelectorEl.addEventListener("change", (e) => {
      var _a, _b;
      if (data.editableKey === void 0)
        return;
      const keyValues = /* @__PURE__ */ new Map();
      let previousSessionId = void 0;
      if (modelSelectorEl.value === "") {
        keyValues.set(data.editableKey, void 0);
        if (data.model instanceof SceneModel)
          previousSessionId = (_a = data.model.session) == null ? void 0 : _a.index.id;
        keyValues.set("data.positionInSession", void 0);
        this.api.service(CodeblockService).addOrUpdateMultiple(keyValues);
      } else {
        const file = this.api.app.vault.getAbstractFileByPath(modelSelectorEl.value);
        if (file == null)
          return;
        const selectedModel2 = this.api.database.readByPath(modelSelectorEl.value);
        if (selectedModel2 === void 0)
          return;
        keyValues.set(data.editableKey, selectedModel2.index.id);
        if (data.model instanceof SceneModel) {
          previousSessionId = (_b = data.model.session) == null ? void 0 : _b.index.id;
          this._addPositionInSession(selectedModel2, data.model, keyValues);
        }
        this.api.service(CodeblockService).addOrUpdateMultiple(keyValues);
      }
      if (previousSessionId !== void 0 && previousSessionId !== modelSelectorEl.value) {
        try {
          const previousSession = this.api.database.readById(previousSessionId);
          previousSession.compactScenePositions(data.model.index.id);
        } catch (e2) {
        }
      }
      this._addModelLink(contentEl, selectedModel);
    });
    if (selectedModel !== void 0)
      this._addModelLink(contentEl, selectedModel);
  }
  _addModelLink(containerEl, model) {
    if (model === void 0) {
    } else {
      const linkContainerEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content-link" });
      import_obsidian35.MarkdownRenderer.renderMarkdown(model.link, linkContainerEl, "", null);
    }
  }
  _addPositionInSession(session, scene, keyValues) {
    const scenes = this.api.database.read((scene2) => {
      var _a;
      return scene2.index.type === 8 /* Scene */ && ((_a = scene2.session) == null ? void 0 : _a.index.id) === session.index.id;
    });
    let positionInSession = 1;
    for (let index = 0; index < scenes.length; index++) {
      if (scenes[index].index.id === scene.index.id)
        continue;
      const scenePosition = scenes[index].positionInSession;
      if (scenePosition === void 0)
        continue;
      if (scenePosition >= positionInSession)
        positionInSession = scenePosition + 1;
    }
    keyValues.set("data.positionInSession", positionInSession);
  }
};

// node_modules/flatpickr/dist/esm/types/options.js
var HOOKS = [
  "onChange",
  "onClose",
  "onDayCreate",
  "onDestroy",
  "onKeyDown",
  "onMonthChange",
  "onOpen",
  "onParseConfig",
  "onReady",
  "onValueUpdate",
  "onYearChange",
  "onPreCalendarPosition"
];
var defaults = {
  _disable: [],
  allowInput: false,
  allowInvalidPreload: false,
  altFormat: "F j, Y",
  altInput: false,
  altInputClass: "form-control input",
  animate: typeof window === "object" && window.navigator.userAgent.indexOf("MSIE") === -1,
  ariaDateFormat: "F j, Y",
  autoFillDefaultTime: true,
  clickOpens: true,
  closeOnSelect: true,
  conjunction: ", ",
  dateFormat: "Y-m-d",
  defaultHour: 12,
  defaultMinute: 0,
  defaultSeconds: 0,
  disable: [],
  disableMobile: false,
  enableSeconds: false,
  enableTime: false,
  errorHandler: function(err) {
    return typeof console !== "undefined" && console.warn(err);
  },
  getWeek: function(givenDate) {
    var date = new Date(givenDate.getTime());
    date.setHours(0, 0, 0, 0);
    date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
    var week1 = new Date(date.getFullYear(), 0, 4);
    return 1 + Math.round(((date.getTime() - week1.getTime()) / 864e5 - 3 + (week1.getDay() + 6) % 7) / 7);
  },
  hourIncrement: 1,
  ignoredFocusElements: [],
  inline: false,
  locale: "default",
  minuteIncrement: 5,
  mode: "single",
  monthSelectorType: "dropdown",
  nextArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",
  noCalendar: false,
  now: new Date(),
  onChange: [],
  onClose: [],
  onDayCreate: [],
  onDestroy: [],
  onKeyDown: [],
  onMonthChange: [],
  onOpen: [],
  onParseConfig: [],
  onReady: [],
  onValueUpdate: [],
  onYearChange: [],
  onPreCalendarPosition: [],
  plugins: [],
  position: "auto",
  positionElement: void 0,
  prevArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",
  shorthandCurrentMonth: false,
  showMonths: 1,
  static: false,
  time_24hr: false,
  weekNumbers: false,
  wrap: false
};

// node_modules/flatpickr/dist/esm/l10n/default.js
var english = {
  weekdays: {
    shorthand: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    longhand: [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ]
  },
  months: {
    shorthand: [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ],
    longhand: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ]
  },
  daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  firstDayOfWeek: 0,
  ordinal: function(nth) {
    var s2 = nth % 100;
    if (s2 > 3 && s2 < 21)
      return "th";
    switch (s2 % 10) {
      case 1:
        return "st";
      case 2:
        return "nd";
      case 3:
        return "rd";
      default:
        return "th";
    }
  },
  rangeSeparator: " to ",
  weekAbbreviation: "Wk",
  scrollTitle: "Scroll to increment",
  toggleTitle: "Click to toggle",
  amPM: ["AM", "PM"],
  yearAriaLabel: "Year",
  monthAriaLabel: "Month",
  hourAriaLabel: "Hour",
  minuteAriaLabel: "Minute",
  time_24hr: false
};
var default_default = english;

// node_modules/flatpickr/dist/esm/utils/index.js
var pad = function(number, length) {
  if (length === void 0) {
    length = 2;
  }
  return ("000" + number).slice(length * -1);
};
var int2 = function(bool) {
  return bool === true ? 1 : 0;
};
function debounce3(fn, wait) {
  var t;
  return function() {
    var _this = this;
    var args = arguments;
    clearTimeout(t);
    t = setTimeout(function() {
      return fn.apply(_this, args);
    }, wait);
  };
}
var arrayify = function(obj) {
  return obj instanceof Array ? obj : [obj];
};

// node_modules/flatpickr/dist/esm/utils/dom.js
function toggleClass(elem, className, bool) {
  if (bool === true)
    return elem.classList.add(className);
  elem.classList.remove(className);
}
function createElement(tag, className, content) {
  var e = window.document.createElement(tag);
  className = className || "";
  content = content || "";
  e.className = className;
  if (content !== void 0)
    e.textContent = content;
  return e;
}
function clearNode(node) {
  while (node.firstChild)
    node.removeChild(node.firstChild);
}
function findParent(node, condition) {
  if (condition(node))
    return node;
  else if (node.parentNode)
    return findParent(node.parentNode, condition);
  return void 0;
}
function createNumberInput(inputClassName, opts) {
  var wrapper = createElement("div", "numInputWrapper"), numInput = createElement("input", "numInput " + inputClassName), arrowUp = createElement("span", "arrowUp"), arrowDown = createElement("span", "arrowDown");
  if (navigator.userAgent.indexOf("MSIE 9.0") === -1) {
    numInput.type = "number";
  } else {
    numInput.type = "text";
    numInput.pattern = "\\d*";
  }
  if (opts !== void 0)
    for (var key in opts)
      numInput.setAttribute(key, opts[key]);
  wrapper.appendChild(numInput);
  wrapper.appendChild(arrowUp);
  wrapper.appendChild(arrowDown);
  return wrapper;
}
function getEventTarget(event) {
  try {
    if (typeof event.composedPath === "function") {
      var path2 = event.composedPath();
      return path2[0];
    }
    return event.target;
  } catch (error) {
    return event.target;
  }
}

// node_modules/flatpickr/dist/esm/utils/formatting.js
var doNothing = function() {
  return void 0;
};
var monthToStr = function(monthNumber, shorthand, locale) {
  return locale.months[shorthand ? "shorthand" : "longhand"][monthNumber];
};
var revFormat = {
  D: doNothing,
  F: function(dateObj, monthName, locale) {
    dateObj.setMonth(locale.months.longhand.indexOf(monthName));
  },
  G: function(dateObj, hour) {
    dateObj.setHours((dateObj.getHours() >= 12 ? 12 : 0) + parseFloat(hour));
  },
  H: function(dateObj, hour) {
    dateObj.setHours(parseFloat(hour));
  },
  J: function(dateObj, day) {
    dateObj.setDate(parseFloat(day));
  },
  K: function(dateObj, amPM, locale) {
    dateObj.setHours(dateObj.getHours() % 12 + 12 * int2(new RegExp(locale.amPM[1], "i").test(amPM)));
  },
  M: function(dateObj, shortMonth, locale) {
    dateObj.setMonth(locale.months.shorthand.indexOf(shortMonth));
  },
  S: function(dateObj, seconds) {
    dateObj.setSeconds(parseFloat(seconds));
  },
  U: function(_, unixSeconds) {
    return new Date(parseFloat(unixSeconds) * 1e3);
  },
  W: function(dateObj, weekNum, locale) {
    var weekNumber = parseInt(weekNum);
    var date = new Date(dateObj.getFullYear(), 0, 2 + (weekNumber - 1) * 7, 0, 0, 0, 0);
    date.setDate(date.getDate() - date.getDay() + locale.firstDayOfWeek);
    return date;
  },
  Y: function(dateObj, year) {
    dateObj.setFullYear(parseFloat(year));
  },
  Z: function(_, ISODate) {
    return new Date(ISODate);
  },
  d: function(dateObj, day) {
    dateObj.setDate(parseFloat(day));
  },
  h: function(dateObj, hour) {
    dateObj.setHours((dateObj.getHours() >= 12 ? 12 : 0) + parseFloat(hour));
  },
  i: function(dateObj, minutes) {
    dateObj.setMinutes(parseFloat(minutes));
  },
  j: function(dateObj, day) {
    dateObj.setDate(parseFloat(day));
  },
  l: doNothing,
  m: function(dateObj, month) {
    dateObj.setMonth(parseFloat(month) - 1);
  },
  n: function(dateObj, month) {
    dateObj.setMonth(parseFloat(month) - 1);
  },
  s: function(dateObj, seconds) {
    dateObj.setSeconds(parseFloat(seconds));
  },
  u: function(_, unixMillSeconds) {
    return new Date(parseFloat(unixMillSeconds));
  },
  w: doNothing,
  y: function(dateObj, year) {
    dateObj.setFullYear(2e3 + parseFloat(year));
  }
};
var tokenRegex = {
  D: "",
  F: "",
  G: "(\\d\\d|\\d)",
  H: "(\\d\\d|\\d)",
  J: "(\\d\\d|\\d)\\w+",
  K: "",
  M: "",
  S: "(\\d\\d|\\d)",
  U: "(.+)",
  W: "(\\d\\d|\\d)",
  Y: "(\\d{4})",
  Z: "(.+)",
  d: "(\\d\\d|\\d)",
  h: "(\\d\\d|\\d)",
  i: "(\\d\\d|\\d)",
  j: "(\\d\\d|\\d)",
  l: "",
  m: "(\\d\\d|\\d)",
  n: "(\\d\\d|\\d)",
  s: "(\\d\\d|\\d)",
  u: "(.+)",
  w: "(\\d\\d|\\d)",
  y: "(\\d{2})"
};
var formats = {
  Z: function(date) {
    return date.toISOString();
  },
  D: function(date, locale, options) {
    return locale.weekdays.shorthand[formats.w(date, locale, options)];
  },
  F: function(date, locale, options) {
    return monthToStr(formats.n(date, locale, options) - 1, false, locale);
  },
  G: function(date, locale, options) {
    return pad(formats.h(date, locale, options));
  },
  H: function(date) {
    return pad(date.getHours());
  },
  J: function(date, locale) {
    return locale.ordinal !== void 0 ? date.getDate() + locale.ordinal(date.getDate()) : date.getDate();
  },
  K: function(date, locale) {
    return locale.amPM[int2(date.getHours() > 11)];
  },
  M: function(date, locale) {
    return monthToStr(date.getMonth(), true, locale);
  },
  S: function(date) {
    return pad(date.getSeconds());
  },
  U: function(date) {
    return date.getTime() / 1e3;
  },
  W: function(date, _, options) {
    return options.getWeek(date);
  },
  Y: function(date) {
    return pad(date.getFullYear(), 4);
  },
  d: function(date) {
    return pad(date.getDate());
  },
  h: function(date) {
    return date.getHours() % 12 ? date.getHours() % 12 : 12;
  },
  i: function(date) {
    return pad(date.getMinutes());
  },
  j: function(date) {
    return date.getDate();
  },
  l: function(date, locale) {
    return locale.weekdays.longhand[date.getDay()];
  },
  m: function(date) {
    return pad(date.getMonth() + 1);
  },
  n: function(date) {
    return date.getMonth() + 1;
  },
  s: function(date) {
    return date.getSeconds();
  },
  u: function(date) {
    return date.getTime();
  },
  w: function(date) {
    return date.getDay();
  },
  y: function(date) {
    return String(date.getFullYear()).substring(2);
  }
};

// node_modules/flatpickr/dist/esm/utils/dates.js
var createDateFormatter = function(_a) {
  var _b = _a.config, config = _b === void 0 ? defaults : _b, _c = _a.l10n, l10n = _c === void 0 ? english : _c, _d = _a.isMobile, isMobile = _d === void 0 ? false : _d;
  return function(dateObj, frmt, overrideLocale) {
    var locale = overrideLocale || l10n;
    if (config.formatDate !== void 0 && !isMobile) {
      return config.formatDate(dateObj, frmt, locale);
    }
    return frmt.split("").map(function(c, i, arr) {
      return formats[c] && arr[i - 1] !== "\\" ? formats[c](dateObj, locale, config) : c !== "\\" ? c : "";
    }).join("");
  };
};
var createDateParser = function(_a) {
  var _b = _a.config, config = _b === void 0 ? defaults : _b, _c = _a.l10n, l10n = _c === void 0 ? english : _c;
  return function(date, givenFormat, timeless, customLocale) {
    if (date !== 0 && !date)
      return void 0;
    var locale = customLocale || l10n;
    var parsedDate;
    var dateOrig = date;
    if (date instanceof Date)
      parsedDate = new Date(date.getTime());
    else if (typeof date !== "string" && date.toFixed !== void 0)
      parsedDate = new Date(date);
    else if (typeof date === "string") {
      var format = givenFormat || (config || defaults).dateFormat;
      var datestr = String(date).trim();
      if (datestr === "today") {
        parsedDate = new Date();
        timeless = true;
      } else if (config && config.parseDate) {
        parsedDate = config.parseDate(date, format);
      } else if (/Z$/.test(datestr) || /GMT$/.test(datestr)) {
        parsedDate = new Date(date);
      } else {
        var matched = void 0, ops = [];
        for (var i = 0, matchIndex = 0, regexStr = ""; i < format.length; i++) {
          var token = format[i];
          var isBackSlash = token === "\\";
          var escaped = format[i - 1] === "\\" || isBackSlash;
          if (tokenRegex[token] && !escaped) {
            regexStr += tokenRegex[token];
            var match2 = new RegExp(regexStr).exec(date);
            if (match2 && (matched = true)) {
              ops[token !== "Y" ? "push" : "unshift"]({
                fn: revFormat[token],
                val: match2[++matchIndex]
              });
            }
          } else if (!isBackSlash)
            regexStr += ".";
        }
        parsedDate = !config || !config.noCalendar ? new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0) : new Date(new Date().setHours(0, 0, 0, 0));
        ops.forEach(function(_a2) {
          var fn = _a2.fn, val = _a2.val;
          return parsedDate = fn(parsedDate, val, locale) || parsedDate;
        });
        parsedDate = matched ? parsedDate : void 0;
      }
    }
    if (!(parsedDate instanceof Date && !isNaN(parsedDate.getTime()))) {
      config.errorHandler(new Error("Invalid date provided: " + dateOrig));
      return void 0;
    }
    if (timeless === true)
      parsedDate.setHours(0, 0, 0, 0);
    return parsedDate;
  };
};
function compareDates(date1, date2, timeless) {
  if (timeless === void 0) {
    timeless = true;
  }
  if (timeless !== false) {
    return new Date(date1.getTime()).setHours(0, 0, 0, 0) - new Date(date2.getTime()).setHours(0, 0, 0, 0);
  }
  return date1.getTime() - date2.getTime();
}
var isBetween = function(ts, ts1, ts2) {
  return ts > Math.min(ts1, ts2) && ts < Math.max(ts1, ts2);
};
var calculateSecondsSinceMidnight = function(hours, minutes, seconds) {
  return hours * 3600 + minutes * 60 + seconds;
};
var parseSeconds = function(secondsSinceMidnight) {
  var hours = Math.floor(secondsSinceMidnight / 3600), minutes = (secondsSinceMidnight - hours * 3600) / 60;
  return [hours, minutes, secondsSinceMidnight - hours * 3600 - minutes * 60];
};
var duration = {
  DAY: 864e5
};
function getDefaultHours(config) {
  var hours = config.defaultHour;
  var minutes = config.defaultMinute;
  var seconds = config.defaultSeconds;
  if (config.minDate !== void 0) {
    var minHour = config.minDate.getHours();
    var minMinutes = config.minDate.getMinutes();
    var minSeconds = config.minDate.getSeconds();
    if (hours < minHour) {
      hours = minHour;
    }
    if (hours === minHour && minutes < minMinutes) {
      minutes = minMinutes;
    }
    if (hours === minHour && minutes === minMinutes && seconds < minSeconds)
      seconds = config.minDate.getSeconds();
  }
  if (config.maxDate !== void 0) {
    var maxHr = config.maxDate.getHours();
    var maxMinutes = config.maxDate.getMinutes();
    hours = Math.min(hours, maxHr);
    if (hours === maxHr)
      minutes = Math.min(maxMinutes, minutes);
    if (hours === maxHr && minutes === maxMinutes)
      seconds = config.maxDate.getSeconds();
  }
  return { hours, minutes, seconds };
}

// node_modules/flatpickr/dist/esm/utils/polyfills.js
if (typeof Object.assign !== "function") {
  Object.assign = function(target) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      args[_i - 1] = arguments[_i];
    }
    if (!target) {
      throw TypeError("Cannot convert undefined or null to object");
    }
    var _loop_1 = function(source2) {
      if (source2) {
        Object.keys(source2).forEach(function(key) {
          return target[key] = source2[key];
        });
      }
    };
    for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
      var source = args_1[_a];
      _loop_1(source);
    }
    return target;
  };
}

// node_modules/flatpickr/dist/esm/index.js
var __assign = function() {
  __assign = Object.assign || function(t) {
    for (var s2, i = 1, n2 = arguments.length; i < n2; i++) {
      s2 = arguments[i];
      for (var p in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p))
          t[p] = s2[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var __spreadArrays = function() {
  for (var s2 = 0, i = 0, il = arguments.length; i < il; i++)
    s2 += arguments[i].length;
  for (var r = Array(s2), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
      r[k] = a[j];
  return r;
};
var DEBOUNCED_CHANGE_MS = 300;
function FlatpickrInstance(element, instanceConfig) {
  var self = {
    config: __assign(__assign({}, defaults), flatpickr.defaultConfig),
    l10n: default_default
  };
  self.parseDate = createDateParser({ config: self.config, l10n: self.l10n });
  self._handlers = [];
  self.pluginElements = [];
  self.loadedPlugins = [];
  self._bind = bind;
  self._setHoursFromDate = setHoursFromDate;
  self._positionCalendar = positionCalendar;
  self.changeMonth = changeMonth;
  self.changeYear = changeYear;
  self.clear = clear;
  self.close = close;
  self.onMouseOver = onMouseOver;
  self._createElement = createElement;
  self.createDay = createDay;
  self.destroy = destroy;
  self.isEnabled = isEnabled;
  self.jumpToDate = jumpToDate;
  self.updateValue = updateValue;
  self.open = open;
  self.redraw = redraw;
  self.set = set;
  self.setDate = setDate;
  self.toggle = toggle;
  function setupHelperFunctions() {
    self.utils = {
      getDaysInMonth: function(month, yr) {
        if (month === void 0) {
          month = self.currentMonth;
        }
        if (yr === void 0) {
          yr = self.currentYear;
        }
        if (month === 1 && (yr % 4 === 0 && yr % 100 !== 0 || yr % 400 === 0))
          return 29;
        return self.l10n.daysInMonth[month];
      }
    };
  }
  function init() {
    self.element = self.input = element;
    self.isOpen = false;
    parseConfig();
    setupLocale();
    setupInputs();
    setupDates();
    setupHelperFunctions();
    if (!self.isMobile)
      build();
    bindEvents();
    if (self.selectedDates.length || self.config.noCalendar) {
      if (self.config.enableTime) {
        setHoursFromDate(self.config.noCalendar ? self.latestSelectedDateObj : void 0);
      }
      updateValue(false);
    }
    setCalendarWidth();
    var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    if (!self.isMobile && isSafari) {
      positionCalendar();
    }
    triggerEvent("onReady");
  }
  function getClosestActiveElement() {
    var _a;
    return ((_a = self.calendarContainer) === null || _a === void 0 ? void 0 : _a.getRootNode()).activeElement || document.activeElement;
  }
  function bindToInstance(fn) {
    return fn.bind(self);
  }
  function setCalendarWidth() {
    var config = self.config;
    if (config.weekNumbers === false && config.showMonths === 1) {
      return;
    } else if (config.noCalendar !== true) {
      window.requestAnimationFrame(function() {
        if (self.calendarContainer !== void 0) {
          self.calendarContainer.style.visibility = "hidden";
          self.calendarContainer.style.display = "block";
        }
        if (self.daysContainer !== void 0) {
          var daysWidth = (self.days.offsetWidth + 1) * config.showMonths;
          self.daysContainer.style.width = daysWidth + "px";
          self.calendarContainer.style.width = daysWidth + (self.weekWrapper !== void 0 ? self.weekWrapper.offsetWidth : 0) + "px";
          self.calendarContainer.style.removeProperty("visibility");
          self.calendarContainer.style.removeProperty("display");
        }
      });
    }
  }
  function updateTime(e) {
    if (self.selectedDates.length === 0) {
      var defaultDate = self.config.minDate === void 0 || compareDates(new Date(), self.config.minDate) >= 0 ? new Date() : new Date(self.config.minDate.getTime());
      var defaults2 = getDefaultHours(self.config);
      defaultDate.setHours(defaults2.hours, defaults2.minutes, defaults2.seconds, defaultDate.getMilliseconds());
      self.selectedDates = [defaultDate];
      self.latestSelectedDateObj = defaultDate;
    }
    if (e !== void 0 && e.type !== "blur") {
      timeWrapper(e);
    }
    var prevValue = self._input.value;
    setHoursFromInputs();
    updateValue();
    if (self._input.value !== prevValue) {
      self._debouncedChange();
    }
  }
  function ampm2military(hour, amPM) {
    return hour % 12 + 12 * int2(amPM === self.l10n.amPM[1]);
  }
  function military2ampm(hour) {
    switch (hour % 24) {
      case 0:
      case 12:
        return 12;
      default:
        return hour % 12;
    }
  }
  function setHoursFromInputs() {
    if (self.hourElement === void 0 || self.minuteElement === void 0)
      return;
    var hours = (parseInt(self.hourElement.value.slice(-2), 10) || 0) % 24, minutes = (parseInt(self.minuteElement.value, 10) || 0) % 60, seconds = self.secondElement !== void 0 ? (parseInt(self.secondElement.value, 10) || 0) % 60 : 0;
    if (self.amPM !== void 0) {
      hours = ampm2military(hours, self.amPM.textContent);
    }
    var limitMinHours = self.config.minTime !== void 0 || self.config.minDate && self.minDateHasTime && self.latestSelectedDateObj && compareDates(self.latestSelectedDateObj, self.config.minDate, true) === 0;
    var limitMaxHours = self.config.maxTime !== void 0 || self.config.maxDate && self.maxDateHasTime && self.latestSelectedDateObj && compareDates(self.latestSelectedDateObj, self.config.maxDate, true) === 0;
    if (self.config.maxTime !== void 0 && self.config.minTime !== void 0 && self.config.minTime > self.config.maxTime) {
      var minBound = calculateSecondsSinceMidnight(self.config.minTime.getHours(), self.config.minTime.getMinutes(), self.config.minTime.getSeconds());
      var maxBound = calculateSecondsSinceMidnight(self.config.maxTime.getHours(), self.config.maxTime.getMinutes(), self.config.maxTime.getSeconds());
      var currentTime = calculateSecondsSinceMidnight(hours, minutes, seconds);
      if (currentTime > maxBound && currentTime < minBound) {
        var result = parseSeconds(minBound);
        hours = result[0];
        minutes = result[1];
        seconds = result[2];
      }
    } else {
      if (limitMaxHours) {
        var maxTime = self.config.maxTime !== void 0 ? self.config.maxTime : self.config.maxDate;
        hours = Math.min(hours, maxTime.getHours());
        if (hours === maxTime.getHours())
          minutes = Math.min(minutes, maxTime.getMinutes());
        if (minutes === maxTime.getMinutes())
          seconds = Math.min(seconds, maxTime.getSeconds());
      }
      if (limitMinHours) {
        var minTime = self.config.minTime !== void 0 ? self.config.minTime : self.config.minDate;
        hours = Math.max(hours, minTime.getHours());
        if (hours === minTime.getHours() && minutes < minTime.getMinutes())
          minutes = minTime.getMinutes();
        if (minutes === minTime.getMinutes())
          seconds = Math.max(seconds, minTime.getSeconds());
      }
    }
    setHours(hours, minutes, seconds);
  }
  function setHoursFromDate(dateObj) {
    var date = dateObj || self.latestSelectedDateObj;
    if (date && date instanceof Date) {
      setHours(date.getHours(), date.getMinutes(), date.getSeconds());
    }
  }
  function setHours(hours, minutes, seconds) {
    if (self.latestSelectedDateObj !== void 0) {
      self.latestSelectedDateObj.setHours(hours % 24, minutes, seconds || 0, 0);
    }
    if (!self.hourElement || !self.minuteElement || self.isMobile)
      return;
    self.hourElement.value = pad(!self.config.time_24hr ? (12 + hours) % 12 + 12 * int2(hours % 12 === 0) : hours);
    self.minuteElement.value = pad(minutes);
    if (self.amPM !== void 0)
      self.amPM.textContent = self.l10n.amPM[int2(hours >= 12)];
    if (self.secondElement !== void 0)
      self.secondElement.value = pad(seconds);
  }
  function onYearInput(event) {
    var eventTarget = getEventTarget(event);
    var year = parseInt(eventTarget.value) + (event.delta || 0);
    if (year / 1e3 > 1 || event.key === "Enter" && !/[^\d]/.test(year.toString())) {
      changeYear(year);
    }
  }
  function bind(element2, event, handler, options) {
    if (event instanceof Array)
      return event.forEach(function(ev) {
        return bind(element2, ev, handler, options);
      });
    if (element2 instanceof Array)
      return element2.forEach(function(el) {
        return bind(el, event, handler, options);
      });
    element2.addEventListener(event, handler, options);
    self._handlers.push({
      remove: function() {
        return element2.removeEventListener(event, handler, options);
      }
    });
  }
  function triggerChange() {
    triggerEvent("onChange");
  }
  function bindEvents() {
    if (self.config.wrap) {
      ["open", "close", "toggle", "clear"].forEach(function(evt) {
        Array.prototype.forEach.call(self.element.querySelectorAll("[data-" + evt + "]"), function(el) {
          return bind(el, "click", self[evt]);
        });
      });
    }
    if (self.isMobile) {
      setupMobile();
      return;
    }
    var debouncedResize = debounce3(onResize, 50);
    self._debouncedChange = debounce3(triggerChange, DEBOUNCED_CHANGE_MS);
    if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))
      bind(self.daysContainer, "mouseover", function(e) {
        if (self.config.mode === "range")
          onMouseOver(getEventTarget(e));
      });
    bind(self._input, "keydown", onKeyDown);
    if (self.calendarContainer !== void 0) {
      bind(self.calendarContainer, "keydown", onKeyDown);
    }
    if (!self.config.inline && !self.config.static)
      bind(window, "resize", debouncedResize);
    if (window.ontouchstart !== void 0)
      bind(window.document, "touchstart", documentClick);
    else
      bind(window.document, "mousedown", documentClick);
    bind(window.document, "focus", documentClick, { capture: true });
    if (self.config.clickOpens === true) {
      bind(self._input, "focus", self.open);
      bind(self._input, "click", self.open);
    }
    if (self.daysContainer !== void 0) {
      bind(self.monthNav, "click", onMonthNavClick);
      bind(self.monthNav, ["keyup", "increment"], onYearInput);
      bind(self.daysContainer, "click", selectDate);
    }
    if (self.timeContainer !== void 0 && self.minuteElement !== void 0 && self.hourElement !== void 0) {
      var selText = function(e) {
        return getEventTarget(e).select();
      };
      bind(self.timeContainer, ["increment"], updateTime);
      bind(self.timeContainer, "blur", updateTime, { capture: true });
      bind(self.timeContainer, "click", timeIncrement);
      bind([self.hourElement, self.minuteElement], ["focus", "click"], selText);
      if (self.secondElement !== void 0)
        bind(self.secondElement, "focus", function() {
          return self.secondElement && self.secondElement.select();
        });
      if (self.amPM !== void 0) {
        bind(self.amPM, "click", function(e) {
          updateTime(e);
        });
      }
    }
    if (self.config.allowInput) {
      bind(self._input, "blur", onBlur);
    }
  }
  function jumpToDate(jumpDate, triggerChange2) {
    var jumpTo = jumpDate !== void 0 ? self.parseDate(jumpDate) : self.latestSelectedDateObj || (self.config.minDate && self.config.minDate > self.now ? self.config.minDate : self.config.maxDate && self.config.maxDate < self.now ? self.config.maxDate : self.now);
    var oldYear = self.currentYear;
    var oldMonth = self.currentMonth;
    try {
      if (jumpTo !== void 0) {
        self.currentYear = jumpTo.getFullYear();
        self.currentMonth = jumpTo.getMonth();
      }
    } catch (e) {
      e.message = "Invalid date supplied: " + jumpTo;
      self.config.errorHandler(e);
    }
    if (triggerChange2 && self.currentYear !== oldYear) {
      triggerEvent("onYearChange");
      buildMonthSwitch();
    }
    if (triggerChange2 && (self.currentYear !== oldYear || self.currentMonth !== oldMonth)) {
      triggerEvent("onMonthChange");
    }
    self.redraw();
  }
  function timeIncrement(e) {
    var eventTarget = getEventTarget(e);
    if (~eventTarget.className.indexOf("arrow"))
      incrementNumInput(e, eventTarget.classList.contains("arrowUp") ? 1 : -1);
  }
  function incrementNumInput(e, delta, inputElem) {
    var target = e && getEventTarget(e);
    var input = inputElem || target && target.parentNode && target.parentNode.firstChild;
    var event = createEvent("increment");
    event.delta = delta;
    input && input.dispatchEvent(event);
  }
  function build() {
    var fragment = window.document.createDocumentFragment();
    self.calendarContainer = createElement("div", "flatpickr-calendar");
    self.calendarContainer.tabIndex = -1;
    if (!self.config.noCalendar) {
      fragment.appendChild(buildMonthNav());
      self.innerContainer = createElement("div", "flatpickr-innerContainer");
      if (self.config.weekNumbers) {
        var _a = buildWeeks(), weekWrapper = _a.weekWrapper, weekNumbers = _a.weekNumbers;
        self.innerContainer.appendChild(weekWrapper);
        self.weekNumbers = weekNumbers;
        self.weekWrapper = weekWrapper;
      }
      self.rContainer = createElement("div", "flatpickr-rContainer");
      self.rContainer.appendChild(buildWeekdays());
      if (!self.daysContainer) {
        self.daysContainer = createElement("div", "flatpickr-days");
        self.daysContainer.tabIndex = -1;
      }
      buildDays();
      self.rContainer.appendChild(self.daysContainer);
      self.innerContainer.appendChild(self.rContainer);
      fragment.appendChild(self.innerContainer);
    }
    if (self.config.enableTime) {
      fragment.appendChild(buildTime());
    }
    toggleClass(self.calendarContainer, "rangeMode", self.config.mode === "range");
    toggleClass(self.calendarContainer, "animate", self.config.animate === true);
    toggleClass(self.calendarContainer, "multiMonth", self.config.showMonths > 1);
    self.calendarContainer.appendChild(fragment);
    var customAppend = self.config.appendTo !== void 0 && self.config.appendTo.nodeType !== void 0;
    if (self.config.inline || self.config.static) {
      self.calendarContainer.classList.add(self.config.inline ? "inline" : "static");
      if (self.config.inline) {
        if (!customAppend && self.element.parentNode)
          self.element.parentNode.insertBefore(self.calendarContainer, self._input.nextSibling);
        else if (self.config.appendTo !== void 0)
          self.config.appendTo.appendChild(self.calendarContainer);
      }
      if (self.config.static) {
        var wrapper = createElement("div", "flatpickr-wrapper");
        if (self.element.parentNode)
          self.element.parentNode.insertBefore(wrapper, self.element);
        wrapper.appendChild(self.element);
        if (self.altInput)
          wrapper.appendChild(self.altInput);
        wrapper.appendChild(self.calendarContainer);
      }
    }
    if (!self.config.static && !self.config.inline)
      (self.config.appendTo !== void 0 ? self.config.appendTo : window.document.body).appendChild(self.calendarContainer);
  }
  function createDay(className, date, _dayNumber, i) {
    var dateIsEnabled = isEnabled(date, true), dayElement = createElement("span", className, date.getDate().toString());
    dayElement.dateObj = date;
    dayElement.$i = i;
    dayElement.setAttribute("aria-label", self.formatDate(date, self.config.ariaDateFormat));
    if (className.indexOf("hidden") === -1 && compareDates(date, self.now) === 0) {
      self.todayDateElem = dayElement;
      dayElement.classList.add("today");
      dayElement.setAttribute("aria-current", "date");
    }
    if (dateIsEnabled) {
      dayElement.tabIndex = -1;
      if (isDateSelected(date)) {
        dayElement.classList.add("selected");
        self.selectedDateElem = dayElement;
        if (self.config.mode === "range") {
          toggleClass(dayElement, "startRange", self.selectedDates[0] && compareDates(date, self.selectedDates[0], true) === 0);
          toggleClass(dayElement, "endRange", self.selectedDates[1] && compareDates(date, self.selectedDates[1], true) === 0);
          if (className === "nextMonthDay")
            dayElement.classList.add("inRange");
        }
      }
    } else {
      dayElement.classList.add("flatpickr-disabled");
    }
    if (self.config.mode === "range") {
      if (isDateInRange(date) && !isDateSelected(date))
        dayElement.classList.add("inRange");
    }
    if (self.weekNumbers && self.config.showMonths === 1 && className !== "prevMonthDay" && i % 7 === 6) {
      self.weekNumbers.insertAdjacentHTML("beforeend", "<span class='flatpickr-day'>" + self.config.getWeek(date) + "</span>");
    }
    triggerEvent("onDayCreate", dayElement);
    return dayElement;
  }
  function focusOnDayElem(targetNode) {
    targetNode.focus();
    if (self.config.mode === "range")
      onMouseOver(targetNode);
  }
  function getFirstAvailableDay(delta) {
    var startMonth = delta > 0 ? 0 : self.config.showMonths - 1;
    var endMonth = delta > 0 ? self.config.showMonths : -1;
    for (var m = startMonth; m != endMonth; m += delta) {
      var month = self.daysContainer.children[m];
      var startIndex = delta > 0 ? 0 : month.children.length - 1;
      var endIndex = delta > 0 ? month.children.length : -1;
      for (var i = startIndex; i != endIndex; i += delta) {
        var c = month.children[i];
        if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj))
          return c;
      }
    }
    return void 0;
  }
  function getNextAvailableDay(current, delta) {
    var givenMonth = current.className.indexOf("Month") === -1 ? current.dateObj.getMonth() : self.currentMonth;
    var endMonth = delta > 0 ? self.config.showMonths : -1;
    var loopDelta = delta > 0 ? 1 : -1;
    for (var m = givenMonth - self.currentMonth; m != endMonth; m += loopDelta) {
      var month = self.daysContainer.children[m];
      var startIndex = givenMonth - self.currentMonth === m ? current.$i + delta : delta < 0 ? month.children.length - 1 : 0;
      var numMonthDays = month.children.length;
      for (var i = startIndex; i >= 0 && i < numMonthDays && i != (delta > 0 ? numMonthDays : -1); i += loopDelta) {
        var c = month.children[i];
        if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj) && Math.abs(current.$i - i) >= Math.abs(delta))
          return focusOnDayElem(c);
      }
    }
    self.changeMonth(loopDelta);
    focusOnDay(getFirstAvailableDay(loopDelta), 0);
    return void 0;
  }
  function focusOnDay(current, offset2) {
    var activeElement = getClosestActiveElement();
    var dayFocused = isInView(activeElement || document.body);
    var startElem = current !== void 0 ? current : dayFocused ? activeElement : self.selectedDateElem !== void 0 && isInView(self.selectedDateElem) ? self.selectedDateElem : self.todayDateElem !== void 0 && isInView(self.todayDateElem) ? self.todayDateElem : getFirstAvailableDay(offset2 > 0 ? 1 : -1);
    if (startElem === void 0) {
      self._input.focus();
    } else if (!dayFocused) {
      focusOnDayElem(startElem);
    } else {
      getNextAvailableDay(startElem, offset2);
    }
  }
  function buildMonthDays(year, month) {
    var firstOfMonth = (new Date(year, month, 1).getDay() - self.l10n.firstDayOfWeek + 7) % 7;
    var prevMonthDays = self.utils.getDaysInMonth((month - 1 + 12) % 12, year);
    var daysInMonth2 = self.utils.getDaysInMonth(month, year), days = window.document.createDocumentFragment(), isMultiMonth = self.config.showMonths > 1, prevMonthDayClass = isMultiMonth ? "prevMonthDay hidden" : "prevMonthDay", nextMonthDayClass = isMultiMonth ? "nextMonthDay hidden" : "nextMonthDay";
    var dayNumber = prevMonthDays + 1 - firstOfMonth, dayIndex = 0;
    for (; dayNumber <= prevMonthDays; dayNumber++, dayIndex++) {
      days.appendChild(createDay("flatpickr-day " + prevMonthDayClass, new Date(year, month - 1, dayNumber), dayNumber, dayIndex));
    }
    for (dayNumber = 1; dayNumber <= daysInMonth2; dayNumber++, dayIndex++) {
      days.appendChild(createDay("flatpickr-day", new Date(year, month, dayNumber), dayNumber, dayIndex));
    }
    for (var dayNum = daysInMonth2 + 1; dayNum <= 42 - firstOfMonth && (self.config.showMonths === 1 || dayIndex % 7 !== 0); dayNum++, dayIndex++) {
      days.appendChild(createDay("flatpickr-day " + nextMonthDayClass, new Date(year, month + 1, dayNum % daysInMonth2), dayNum, dayIndex));
    }
    var dayContainer = createElement("div", "dayContainer");
    dayContainer.appendChild(days);
    return dayContainer;
  }
  function buildDays() {
    if (self.daysContainer === void 0) {
      return;
    }
    clearNode(self.daysContainer);
    if (self.weekNumbers)
      clearNode(self.weekNumbers);
    var frag = document.createDocumentFragment();
    for (var i = 0; i < self.config.showMonths; i++) {
      var d = new Date(self.currentYear, self.currentMonth, 1);
      d.setMonth(self.currentMonth + i);
      frag.appendChild(buildMonthDays(d.getFullYear(), d.getMonth()));
    }
    self.daysContainer.appendChild(frag);
    self.days = self.daysContainer.firstChild;
    if (self.config.mode === "range" && self.selectedDates.length === 1) {
      onMouseOver();
    }
  }
  function buildMonthSwitch() {
    if (self.config.showMonths > 1 || self.config.monthSelectorType !== "dropdown")
      return;
    var shouldBuildMonth = function(month2) {
      if (self.config.minDate !== void 0 && self.currentYear === self.config.minDate.getFullYear() && month2 < self.config.minDate.getMonth()) {
        return false;
      }
      return !(self.config.maxDate !== void 0 && self.currentYear === self.config.maxDate.getFullYear() && month2 > self.config.maxDate.getMonth());
    };
    self.monthsDropdownContainer.tabIndex = -1;
    self.monthsDropdownContainer.innerHTML = "";
    for (var i = 0; i < 12; i++) {
      if (!shouldBuildMonth(i))
        continue;
      var month = createElement("option", "flatpickr-monthDropdown-month");
      month.value = new Date(self.currentYear, i).getMonth().toString();
      month.textContent = monthToStr(i, self.config.shorthandCurrentMonth, self.l10n);
      month.tabIndex = -1;
      if (self.currentMonth === i) {
        month.selected = true;
      }
      self.monthsDropdownContainer.appendChild(month);
    }
  }
  function buildMonth() {
    var container = createElement("div", "flatpickr-month");
    var monthNavFragment = window.document.createDocumentFragment();
    var monthElement;
    if (self.config.showMonths > 1 || self.config.monthSelectorType === "static") {
      monthElement = createElement("span", "cur-month");
    } else {
      self.monthsDropdownContainer = createElement("select", "flatpickr-monthDropdown-months");
      self.monthsDropdownContainer.setAttribute("aria-label", self.l10n.monthAriaLabel);
      bind(self.monthsDropdownContainer, "change", function(e) {
        var target = getEventTarget(e);
        var selectedMonth = parseInt(target.value, 10);
        self.changeMonth(selectedMonth - self.currentMonth);
        triggerEvent("onMonthChange");
      });
      buildMonthSwitch();
      monthElement = self.monthsDropdownContainer;
    }
    var yearInput = createNumberInput("cur-year", { tabindex: "-1" });
    var yearElement = yearInput.getElementsByTagName("input")[0];
    yearElement.setAttribute("aria-label", self.l10n.yearAriaLabel);
    if (self.config.minDate) {
      yearElement.setAttribute("min", self.config.minDate.getFullYear().toString());
    }
    if (self.config.maxDate) {
      yearElement.setAttribute("max", self.config.maxDate.getFullYear().toString());
      yearElement.disabled = !!self.config.minDate && self.config.minDate.getFullYear() === self.config.maxDate.getFullYear();
    }
    var currentMonth = createElement("div", "flatpickr-current-month");
    currentMonth.appendChild(monthElement);
    currentMonth.appendChild(yearInput);
    monthNavFragment.appendChild(currentMonth);
    container.appendChild(monthNavFragment);
    return {
      container,
      yearElement,
      monthElement
    };
  }
  function buildMonths() {
    clearNode(self.monthNav);
    self.monthNav.appendChild(self.prevMonthNav);
    if (self.config.showMonths) {
      self.yearElements = [];
      self.monthElements = [];
    }
    for (var m = self.config.showMonths; m--; ) {
      var month = buildMonth();
      self.yearElements.push(month.yearElement);
      self.monthElements.push(month.monthElement);
      self.monthNav.appendChild(month.container);
    }
    self.monthNav.appendChild(self.nextMonthNav);
  }
  function buildMonthNav() {
    self.monthNav = createElement("div", "flatpickr-months");
    self.yearElements = [];
    self.monthElements = [];
    self.prevMonthNav = createElement("span", "flatpickr-prev-month");
    self.prevMonthNav.innerHTML = self.config.prevArrow;
    self.nextMonthNav = createElement("span", "flatpickr-next-month");
    self.nextMonthNav.innerHTML = self.config.nextArrow;
    buildMonths();
    Object.defineProperty(self, "_hidePrevMonthArrow", {
      get: function() {
        return self.__hidePrevMonthArrow;
      },
      set: function(bool) {
        if (self.__hidePrevMonthArrow !== bool) {
          toggleClass(self.prevMonthNav, "flatpickr-disabled", bool);
          self.__hidePrevMonthArrow = bool;
        }
      }
    });
    Object.defineProperty(self, "_hideNextMonthArrow", {
      get: function() {
        return self.__hideNextMonthArrow;
      },
      set: function(bool) {
        if (self.__hideNextMonthArrow !== bool) {
          toggleClass(self.nextMonthNav, "flatpickr-disabled", bool);
          self.__hideNextMonthArrow = bool;
        }
      }
    });
    self.currentYearElement = self.yearElements[0];
    updateNavigationCurrentMonth();
    return self.monthNav;
  }
  function buildTime() {
    self.calendarContainer.classList.add("hasTime");
    if (self.config.noCalendar)
      self.calendarContainer.classList.add("noCalendar");
    var defaults2 = getDefaultHours(self.config);
    self.timeContainer = createElement("div", "flatpickr-time");
    self.timeContainer.tabIndex = -1;
    var separator = createElement("span", "flatpickr-time-separator", ":");
    var hourInput = createNumberInput("flatpickr-hour", {
      "aria-label": self.l10n.hourAriaLabel
    });
    self.hourElement = hourInput.getElementsByTagName("input")[0];
    var minuteInput = createNumberInput("flatpickr-minute", {
      "aria-label": self.l10n.minuteAriaLabel
    });
    self.minuteElement = minuteInput.getElementsByTagName("input")[0];
    self.hourElement.tabIndex = self.minuteElement.tabIndex = -1;
    self.hourElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getHours() : self.config.time_24hr ? defaults2.hours : military2ampm(defaults2.hours));
    self.minuteElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getMinutes() : defaults2.minutes);
    self.hourElement.setAttribute("step", self.config.hourIncrement.toString());
    self.minuteElement.setAttribute("step", self.config.minuteIncrement.toString());
    self.hourElement.setAttribute("min", self.config.time_24hr ? "0" : "1");
    self.hourElement.setAttribute("max", self.config.time_24hr ? "23" : "12");
    self.hourElement.setAttribute("maxlength", "2");
    self.minuteElement.setAttribute("min", "0");
    self.minuteElement.setAttribute("max", "59");
    self.minuteElement.setAttribute("maxlength", "2");
    self.timeContainer.appendChild(hourInput);
    self.timeContainer.appendChild(separator);
    self.timeContainer.appendChild(minuteInput);
    if (self.config.time_24hr)
      self.timeContainer.classList.add("time24hr");
    if (self.config.enableSeconds) {
      self.timeContainer.classList.add("hasSeconds");
      var secondInput = createNumberInput("flatpickr-second");
      self.secondElement = secondInput.getElementsByTagName("input")[0];
      self.secondElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getSeconds() : defaults2.seconds);
      self.secondElement.setAttribute("step", self.minuteElement.getAttribute("step"));
      self.secondElement.setAttribute("min", "0");
      self.secondElement.setAttribute("max", "59");
      self.secondElement.setAttribute("maxlength", "2");
      self.timeContainer.appendChild(createElement("span", "flatpickr-time-separator", ":"));
      self.timeContainer.appendChild(secondInput);
    }
    if (!self.config.time_24hr) {
      self.amPM = createElement("span", "flatpickr-am-pm", self.l10n.amPM[int2((self.latestSelectedDateObj ? self.hourElement.value : self.config.defaultHour) > 11)]);
      self.amPM.title = self.l10n.toggleTitle;
      self.amPM.tabIndex = -1;
      self.timeContainer.appendChild(self.amPM);
    }
    return self.timeContainer;
  }
  function buildWeekdays() {
    if (!self.weekdayContainer)
      self.weekdayContainer = createElement("div", "flatpickr-weekdays");
    else
      clearNode(self.weekdayContainer);
    for (var i = self.config.showMonths; i--; ) {
      var container = createElement("div", "flatpickr-weekdaycontainer");
      self.weekdayContainer.appendChild(container);
    }
    updateWeekdays();
    return self.weekdayContainer;
  }
  function updateWeekdays() {
    if (!self.weekdayContainer) {
      return;
    }
    var firstDayOfWeek = self.l10n.firstDayOfWeek;
    var weekdays2 = __spreadArrays(self.l10n.weekdays.shorthand);
    if (firstDayOfWeek > 0 && firstDayOfWeek < weekdays2.length) {
      weekdays2 = __spreadArrays(weekdays2.splice(firstDayOfWeek, weekdays2.length), weekdays2.splice(0, firstDayOfWeek));
    }
    for (var i = self.config.showMonths; i--; ) {
      self.weekdayContainer.children[i].innerHTML = "\n      <span class='flatpickr-weekday'>\n        " + weekdays2.join("</span><span class='flatpickr-weekday'>") + "\n      </span>\n      ";
    }
  }
  function buildWeeks() {
    self.calendarContainer.classList.add("hasWeeks");
    var weekWrapper = createElement("div", "flatpickr-weekwrapper");
    weekWrapper.appendChild(createElement("span", "flatpickr-weekday", self.l10n.weekAbbreviation));
    var weekNumbers = createElement("div", "flatpickr-weeks");
    weekWrapper.appendChild(weekNumbers);
    return {
      weekWrapper,
      weekNumbers
    };
  }
  function changeMonth(value, isOffset) {
    if (isOffset === void 0) {
      isOffset = true;
    }
    var delta = isOffset ? value : value - self.currentMonth;
    if (delta < 0 && self._hidePrevMonthArrow === true || delta > 0 && self._hideNextMonthArrow === true)
      return;
    self.currentMonth += delta;
    if (self.currentMonth < 0 || self.currentMonth > 11) {
      self.currentYear += self.currentMonth > 11 ? 1 : -1;
      self.currentMonth = (self.currentMonth + 12) % 12;
      triggerEvent("onYearChange");
      buildMonthSwitch();
    }
    buildDays();
    triggerEvent("onMonthChange");
    updateNavigationCurrentMonth();
  }
  function clear(triggerChangeEvent, toInitial) {
    if (triggerChangeEvent === void 0) {
      triggerChangeEvent = true;
    }
    if (toInitial === void 0) {
      toInitial = true;
    }
    self.input.value = "";
    if (self.altInput !== void 0)
      self.altInput.value = "";
    if (self.mobileInput !== void 0)
      self.mobileInput.value = "";
    self.selectedDates = [];
    self.latestSelectedDateObj = void 0;
    if (toInitial === true) {
      self.currentYear = self._initialDate.getFullYear();
      self.currentMonth = self._initialDate.getMonth();
    }
    if (self.config.enableTime === true) {
      var _a = getDefaultHours(self.config), hours = _a.hours, minutes = _a.minutes, seconds = _a.seconds;
      setHours(hours, minutes, seconds);
    }
    self.redraw();
    if (triggerChangeEvent)
      triggerEvent("onChange");
  }
  function close() {
    self.isOpen = false;
    if (!self.isMobile) {
      if (self.calendarContainer !== void 0) {
        self.calendarContainer.classList.remove("open");
      }
      if (self._input !== void 0) {
        self._input.classList.remove("active");
      }
    }
    triggerEvent("onClose");
  }
  function destroy() {
    if (self.config !== void 0)
      triggerEvent("onDestroy");
    for (var i = self._handlers.length; i--; ) {
      self._handlers[i].remove();
    }
    self._handlers = [];
    if (self.mobileInput) {
      if (self.mobileInput.parentNode)
        self.mobileInput.parentNode.removeChild(self.mobileInput);
      self.mobileInput = void 0;
    } else if (self.calendarContainer && self.calendarContainer.parentNode) {
      if (self.config.static && self.calendarContainer.parentNode) {
        var wrapper = self.calendarContainer.parentNode;
        wrapper.lastChild && wrapper.removeChild(wrapper.lastChild);
        if (wrapper.parentNode) {
          while (wrapper.firstChild)
            wrapper.parentNode.insertBefore(wrapper.firstChild, wrapper);
          wrapper.parentNode.removeChild(wrapper);
        }
      } else
        self.calendarContainer.parentNode.removeChild(self.calendarContainer);
    }
    if (self.altInput) {
      self.input.type = "text";
      if (self.altInput.parentNode)
        self.altInput.parentNode.removeChild(self.altInput);
      delete self.altInput;
    }
    if (self.input) {
      self.input.type = self.input._type;
      self.input.classList.remove("flatpickr-input");
      self.input.removeAttribute("readonly");
    }
    [
      "_showTimeInput",
      "latestSelectedDateObj",
      "_hideNextMonthArrow",
      "_hidePrevMonthArrow",
      "__hideNextMonthArrow",
      "__hidePrevMonthArrow",
      "isMobile",
      "isOpen",
      "selectedDateElem",
      "minDateHasTime",
      "maxDateHasTime",
      "days",
      "daysContainer",
      "_input",
      "_positionElement",
      "innerContainer",
      "rContainer",
      "monthNav",
      "todayDateElem",
      "calendarContainer",
      "weekdayContainer",
      "prevMonthNav",
      "nextMonthNav",
      "monthsDropdownContainer",
      "currentMonthElement",
      "currentYearElement",
      "navigationCurrentMonth",
      "selectedDateElem",
      "config"
    ].forEach(function(k) {
      try {
        delete self[k];
      } catch (_) {
      }
    });
  }
  function isCalendarElem(elem) {
    return self.calendarContainer.contains(elem);
  }
  function documentClick(e) {
    if (self.isOpen && !self.config.inline) {
      var eventTarget_1 = getEventTarget(e);
      var isCalendarElement = isCalendarElem(eventTarget_1);
      var isInput = eventTarget_1 === self.input || eventTarget_1 === self.altInput || self.element.contains(eventTarget_1) || e.path && e.path.indexOf && (~e.path.indexOf(self.input) || ~e.path.indexOf(self.altInput));
      var lostFocus = !isInput && !isCalendarElement && !isCalendarElem(e.relatedTarget);
      var isIgnored = !self.config.ignoredFocusElements.some(function(elem) {
        return elem.contains(eventTarget_1);
      });
      if (lostFocus && isIgnored) {
        if (self.config.allowInput) {
          self.setDate(self._input.value, false, self.config.altInput ? self.config.altFormat : self.config.dateFormat);
        }
        if (self.timeContainer !== void 0 && self.minuteElement !== void 0 && self.hourElement !== void 0 && self.input.value !== "" && self.input.value !== void 0) {
          updateTime();
        }
        self.close();
        if (self.config && self.config.mode === "range" && self.selectedDates.length === 1)
          self.clear(false);
      }
    }
  }
  function changeYear(newYear) {
    if (!newYear || self.config.minDate && newYear < self.config.minDate.getFullYear() || self.config.maxDate && newYear > self.config.maxDate.getFullYear())
      return;
    var newYearNum = newYear, isNewYear = self.currentYear !== newYearNum;
    self.currentYear = newYearNum || self.currentYear;
    if (self.config.maxDate && self.currentYear === self.config.maxDate.getFullYear()) {
      self.currentMonth = Math.min(self.config.maxDate.getMonth(), self.currentMonth);
    } else if (self.config.minDate && self.currentYear === self.config.minDate.getFullYear()) {
      self.currentMonth = Math.max(self.config.minDate.getMonth(), self.currentMonth);
    }
    if (isNewYear) {
      self.redraw();
      triggerEvent("onYearChange");
      buildMonthSwitch();
    }
  }
  function isEnabled(date, timeless) {
    var _a;
    if (timeless === void 0) {
      timeless = true;
    }
    var dateToCheck = self.parseDate(date, void 0, timeless);
    if (self.config.minDate && dateToCheck && compareDates(dateToCheck, self.config.minDate, timeless !== void 0 ? timeless : !self.minDateHasTime) < 0 || self.config.maxDate && dateToCheck && compareDates(dateToCheck, self.config.maxDate, timeless !== void 0 ? timeless : !self.maxDateHasTime) > 0)
      return false;
    if (!self.config.enable && self.config.disable.length === 0)
      return true;
    if (dateToCheck === void 0)
      return false;
    var bool = !!self.config.enable, array = (_a = self.config.enable) !== null && _a !== void 0 ? _a : self.config.disable;
    for (var i = 0, d = void 0; i < array.length; i++) {
      d = array[i];
      if (typeof d === "function" && d(dateToCheck))
        return bool;
      else if (d instanceof Date && dateToCheck !== void 0 && d.getTime() === dateToCheck.getTime())
        return bool;
      else if (typeof d === "string") {
        var parsed = self.parseDate(d, void 0, true);
        return parsed && parsed.getTime() === dateToCheck.getTime() ? bool : !bool;
      } else if (typeof d === "object" && dateToCheck !== void 0 && d.from && d.to && dateToCheck.getTime() >= d.from.getTime() && dateToCheck.getTime() <= d.to.getTime())
        return bool;
    }
    return !bool;
  }
  function isInView(elem) {
    if (self.daysContainer !== void 0)
      return elem.className.indexOf("hidden") === -1 && elem.className.indexOf("flatpickr-disabled") === -1 && self.daysContainer.contains(elem);
    return false;
  }
  function onBlur(e) {
    var isInput = e.target === self._input;
    var valueChanged = self._input.value.trimEnd() !== getDateStr();
    if (isInput && valueChanged && !(e.relatedTarget && isCalendarElem(e.relatedTarget))) {
      self.setDate(self._input.value, true, e.target === self.altInput ? self.config.altFormat : self.config.dateFormat);
    }
  }
  function onKeyDown(e) {
    var eventTarget = getEventTarget(e);
    var isInput = self.config.wrap ? element.contains(eventTarget) : eventTarget === self._input;
    var allowInput = self.config.allowInput;
    var allowKeydown = self.isOpen && (!allowInput || !isInput);
    var allowInlineKeydown = self.config.inline && isInput && !allowInput;
    if (e.keyCode === 13 && isInput) {
      if (allowInput) {
        self.setDate(self._input.value, true, eventTarget === self.altInput ? self.config.altFormat : self.config.dateFormat);
        self.close();
        return eventTarget.blur();
      } else {
        self.open();
      }
    } else if (isCalendarElem(eventTarget) || allowKeydown || allowInlineKeydown) {
      var isTimeObj = !!self.timeContainer && self.timeContainer.contains(eventTarget);
      switch (e.keyCode) {
        case 13:
          if (isTimeObj) {
            e.preventDefault();
            updateTime();
            focusAndClose();
          } else
            selectDate(e);
          break;
        case 27:
          e.preventDefault();
          focusAndClose();
          break;
        case 8:
        case 46:
          if (isInput && !self.config.allowInput) {
            e.preventDefault();
            self.clear();
          }
          break;
        case 37:
        case 39:
          if (!isTimeObj && !isInput) {
            e.preventDefault();
            var activeElement = getClosestActiveElement();
            if (self.daysContainer !== void 0 && (allowInput === false || activeElement && isInView(activeElement))) {
              var delta_1 = e.keyCode === 39 ? 1 : -1;
              if (!e.ctrlKey)
                focusOnDay(void 0, delta_1);
              else {
                e.stopPropagation();
                changeMonth(delta_1);
                focusOnDay(getFirstAvailableDay(1), 0);
              }
            }
          } else if (self.hourElement)
            self.hourElement.focus();
          break;
        case 38:
        case 40:
          e.preventDefault();
          var delta = e.keyCode === 40 ? 1 : -1;
          if (self.daysContainer && eventTarget.$i !== void 0 || eventTarget === self.input || eventTarget === self.altInput) {
            if (e.ctrlKey) {
              e.stopPropagation();
              changeYear(self.currentYear - delta);
              focusOnDay(getFirstAvailableDay(1), 0);
            } else if (!isTimeObj)
              focusOnDay(void 0, delta * 7);
          } else if (eventTarget === self.currentYearElement) {
            changeYear(self.currentYear - delta);
          } else if (self.config.enableTime) {
            if (!isTimeObj && self.hourElement)
              self.hourElement.focus();
            updateTime(e);
            self._debouncedChange();
          }
          break;
        case 9:
          if (isTimeObj) {
            var elems = [
              self.hourElement,
              self.minuteElement,
              self.secondElement,
              self.amPM
            ].concat(self.pluginElements).filter(function(x) {
              return x;
            });
            var i = elems.indexOf(eventTarget);
            if (i !== -1) {
              var target = elems[i + (e.shiftKey ? -1 : 1)];
              e.preventDefault();
              (target || self._input).focus();
            }
          } else if (!self.config.noCalendar && self.daysContainer && self.daysContainer.contains(eventTarget) && e.shiftKey) {
            e.preventDefault();
            self._input.focus();
          }
          break;
        default:
          break;
      }
    }
    if (self.amPM !== void 0 && eventTarget === self.amPM) {
      switch (e.key) {
        case self.l10n.amPM[0].charAt(0):
        case self.l10n.amPM[0].charAt(0).toLowerCase():
          self.amPM.textContent = self.l10n.amPM[0];
          setHoursFromInputs();
          updateValue();
          break;
        case self.l10n.amPM[1].charAt(0):
        case self.l10n.amPM[1].charAt(0).toLowerCase():
          self.amPM.textContent = self.l10n.amPM[1];
          setHoursFromInputs();
          updateValue();
          break;
      }
    }
    if (isInput || isCalendarElem(eventTarget)) {
      triggerEvent("onKeyDown", e);
    }
  }
  function onMouseOver(elem, cellClass) {
    if (cellClass === void 0) {
      cellClass = "flatpickr-day";
    }
    if (self.selectedDates.length !== 1 || elem && (!elem.classList.contains(cellClass) || elem.classList.contains("flatpickr-disabled")))
      return;
    var hoverDate = elem ? elem.dateObj.getTime() : self.days.firstElementChild.dateObj.getTime(), initialDate = self.parseDate(self.selectedDates[0], void 0, true).getTime(), rangeStartDate = Math.min(hoverDate, self.selectedDates[0].getTime()), rangeEndDate = Math.max(hoverDate, self.selectedDates[0].getTime());
    var containsDisabled = false;
    var minRange = 0, maxRange = 0;
    for (var t = rangeStartDate; t < rangeEndDate; t += duration.DAY) {
      if (!isEnabled(new Date(t), true)) {
        containsDisabled = containsDisabled || t > rangeStartDate && t < rangeEndDate;
        if (t < initialDate && (!minRange || t > minRange))
          minRange = t;
        else if (t > initialDate && (!maxRange || t < maxRange))
          maxRange = t;
      }
    }
    var hoverableCells = Array.from(self.rContainer.querySelectorAll("*:nth-child(-n+" + self.config.showMonths + ") > ." + cellClass));
    hoverableCells.forEach(function(dayElem) {
      var date = dayElem.dateObj;
      var timestamp = date.getTime();
      var outOfRange = minRange > 0 && timestamp < minRange || maxRange > 0 && timestamp > maxRange;
      if (outOfRange) {
        dayElem.classList.add("notAllowed");
        ["inRange", "startRange", "endRange"].forEach(function(c) {
          dayElem.classList.remove(c);
        });
        return;
      } else if (containsDisabled && !outOfRange)
        return;
      ["startRange", "inRange", "endRange", "notAllowed"].forEach(function(c) {
        dayElem.classList.remove(c);
      });
      if (elem !== void 0) {
        elem.classList.add(hoverDate <= self.selectedDates[0].getTime() ? "startRange" : "endRange");
        if (initialDate < hoverDate && timestamp === initialDate)
          dayElem.classList.add("startRange");
        else if (initialDate > hoverDate && timestamp === initialDate)
          dayElem.classList.add("endRange");
        if (timestamp >= minRange && (maxRange === 0 || timestamp <= maxRange) && isBetween(timestamp, initialDate, hoverDate))
          dayElem.classList.add("inRange");
      }
    });
  }
  function onResize() {
    if (self.isOpen && !self.config.static && !self.config.inline)
      positionCalendar();
  }
  function open(e, positionElement) {
    if (positionElement === void 0) {
      positionElement = self._positionElement;
    }
    if (self.isMobile === true) {
      if (e) {
        e.preventDefault();
        var eventTarget = getEventTarget(e);
        if (eventTarget) {
          eventTarget.blur();
        }
      }
      if (self.mobileInput !== void 0) {
        self.mobileInput.focus();
        self.mobileInput.click();
      }
      triggerEvent("onOpen");
      return;
    } else if (self._input.disabled || self.config.inline) {
      return;
    }
    var wasOpen = self.isOpen;
    self.isOpen = true;
    if (!wasOpen) {
      self.calendarContainer.classList.add("open");
      self._input.classList.add("active");
      triggerEvent("onOpen");
      positionCalendar(positionElement);
    }
    if (self.config.enableTime === true && self.config.noCalendar === true) {
      if (self.config.allowInput === false && (e === void 0 || !self.timeContainer.contains(e.relatedTarget))) {
        setTimeout(function() {
          return self.hourElement.select();
        }, 50);
      }
    }
  }
  function minMaxDateSetter(type) {
    return function(date) {
      var dateObj = self.config["_" + type + "Date"] = self.parseDate(date, self.config.dateFormat);
      var inverseDateObj = self.config["_" + (type === "min" ? "max" : "min") + "Date"];
      if (dateObj !== void 0) {
        self[type === "min" ? "minDateHasTime" : "maxDateHasTime"] = dateObj.getHours() > 0 || dateObj.getMinutes() > 0 || dateObj.getSeconds() > 0;
      }
      if (self.selectedDates) {
        self.selectedDates = self.selectedDates.filter(function(d) {
          return isEnabled(d);
        });
        if (!self.selectedDates.length && type === "min")
          setHoursFromDate(dateObj);
        updateValue();
      }
      if (self.daysContainer) {
        redraw();
        if (dateObj !== void 0)
          self.currentYearElement[type] = dateObj.getFullYear().toString();
        else
          self.currentYearElement.removeAttribute(type);
        self.currentYearElement.disabled = !!inverseDateObj && dateObj !== void 0 && inverseDateObj.getFullYear() === dateObj.getFullYear();
      }
    };
  }
  function parseConfig() {
    var boolOpts = [
      "wrap",
      "weekNumbers",
      "allowInput",
      "allowInvalidPreload",
      "clickOpens",
      "time_24hr",
      "enableTime",
      "noCalendar",
      "altInput",
      "shorthandCurrentMonth",
      "inline",
      "static",
      "enableSeconds",
      "disableMobile"
    ];
    var userConfig = __assign(__assign({}, JSON.parse(JSON.stringify(element.dataset || {}))), instanceConfig);
    var formats2 = {};
    self.config.parseDate = userConfig.parseDate;
    self.config.formatDate = userConfig.formatDate;
    Object.defineProperty(self.config, "enable", {
      get: function() {
        return self.config._enable;
      },
      set: function(dates) {
        self.config._enable = parseDateRules(dates);
      }
    });
    Object.defineProperty(self.config, "disable", {
      get: function() {
        return self.config._disable;
      },
      set: function(dates) {
        self.config._disable = parseDateRules(dates);
      }
    });
    var timeMode = userConfig.mode === "time";
    if (!userConfig.dateFormat && (userConfig.enableTime || timeMode)) {
      var defaultDateFormat = flatpickr.defaultConfig.dateFormat || defaults.dateFormat;
      formats2.dateFormat = userConfig.noCalendar || timeMode ? "H:i" + (userConfig.enableSeconds ? ":S" : "") : defaultDateFormat + " H:i" + (userConfig.enableSeconds ? ":S" : "");
    }
    if (userConfig.altInput && (userConfig.enableTime || timeMode) && !userConfig.altFormat) {
      var defaultAltFormat = flatpickr.defaultConfig.altFormat || defaults.altFormat;
      formats2.altFormat = userConfig.noCalendar || timeMode ? "h:i" + (userConfig.enableSeconds ? ":S K" : " K") : defaultAltFormat + (" h:i" + (userConfig.enableSeconds ? ":S" : "") + " K");
    }
    Object.defineProperty(self.config, "minDate", {
      get: function() {
        return self.config._minDate;
      },
      set: minMaxDateSetter("min")
    });
    Object.defineProperty(self.config, "maxDate", {
      get: function() {
        return self.config._maxDate;
      },
      set: minMaxDateSetter("max")
    });
    var minMaxTimeSetter = function(type) {
      return function(val) {
        self.config[type === "min" ? "_minTime" : "_maxTime"] = self.parseDate(val, "H:i:S");
      };
    };
    Object.defineProperty(self.config, "minTime", {
      get: function() {
        return self.config._minTime;
      },
      set: minMaxTimeSetter("min")
    });
    Object.defineProperty(self.config, "maxTime", {
      get: function() {
        return self.config._maxTime;
      },
      set: minMaxTimeSetter("max")
    });
    if (userConfig.mode === "time") {
      self.config.noCalendar = true;
      self.config.enableTime = true;
    }
    Object.assign(self.config, formats2, userConfig);
    for (var i = 0; i < boolOpts.length; i++)
      self.config[boolOpts[i]] = self.config[boolOpts[i]] === true || self.config[boolOpts[i]] === "true";
    HOOKS.filter(function(hook) {
      return self.config[hook] !== void 0;
    }).forEach(function(hook) {
      self.config[hook] = arrayify(self.config[hook] || []).map(bindToInstance);
    });
    self.isMobile = !self.config.disableMobile && !self.config.inline && self.config.mode === "single" && !self.config.disable.length && !self.config.enable && !self.config.weekNumbers && /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    for (var i = 0; i < self.config.plugins.length; i++) {
      var pluginConf = self.config.plugins[i](self) || {};
      for (var key in pluginConf) {
        if (HOOKS.indexOf(key) > -1) {
          self.config[key] = arrayify(pluginConf[key]).map(bindToInstance).concat(self.config[key]);
        } else if (typeof userConfig[key] === "undefined")
          self.config[key] = pluginConf[key];
      }
    }
    if (!userConfig.altInputClass) {
      self.config.altInputClass = getInputElem().className + " " + self.config.altInputClass;
    }
    triggerEvent("onParseConfig");
  }
  function getInputElem() {
    return self.config.wrap ? element.querySelector("[data-input]") : element;
  }
  function setupLocale() {
    if (typeof self.config.locale !== "object" && typeof flatpickr.l10ns[self.config.locale] === "undefined")
      self.config.errorHandler(new Error("flatpickr: invalid locale " + self.config.locale));
    self.l10n = __assign(__assign({}, flatpickr.l10ns.default), typeof self.config.locale === "object" ? self.config.locale : self.config.locale !== "default" ? flatpickr.l10ns[self.config.locale] : void 0);
    tokenRegex.D = "(" + self.l10n.weekdays.shorthand.join("|") + ")";
    tokenRegex.l = "(" + self.l10n.weekdays.longhand.join("|") + ")";
    tokenRegex.M = "(" + self.l10n.months.shorthand.join("|") + ")";
    tokenRegex.F = "(" + self.l10n.months.longhand.join("|") + ")";
    tokenRegex.K = "(" + self.l10n.amPM[0] + "|" + self.l10n.amPM[1] + "|" + self.l10n.amPM[0].toLowerCase() + "|" + self.l10n.amPM[1].toLowerCase() + ")";
    var userConfig = __assign(__assign({}, instanceConfig), JSON.parse(JSON.stringify(element.dataset || {})));
    if (userConfig.time_24hr === void 0 && flatpickr.defaultConfig.time_24hr === void 0) {
      self.config.time_24hr = self.l10n.time_24hr;
    }
    self.formatDate = createDateFormatter(self);
    self.parseDate = createDateParser({ config: self.config, l10n: self.l10n });
  }
  function positionCalendar(customPositionElement) {
    if (typeof self.config.position === "function") {
      return void self.config.position(self, customPositionElement);
    }
    if (self.calendarContainer === void 0)
      return;
    triggerEvent("onPreCalendarPosition");
    var positionElement = customPositionElement || self._positionElement;
    var calendarHeight = Array.prototype.reduce.call(self.calendarContainer.children, function(acc, child) {
      return acc + child.offsetHeight;
    }, 0), calendarWidth = self.calendarContainer.offsetWidth, configPos = self.config.position.split(" "), configPosVertical = configPos[0], configPosHorizontal = configPos.length > 1 ? configPos[1] : null, inputBounds = positionElement.getBoundingClientRect(), distanceFromBottom = window.innerHeight - inputBounds.bottom, showOnTop = configPosVertical === "above" || configPosVertical !== "below" && distanceFromBottom < calendarHeight && inputBounds.top > calendarHeight;
    var top = window.pageYOffset + inputBounds.top + (!showOnTop ? positionElement.offsetHeight + 2 : -calendarHeight - 2);
    toggleClass(self.calendarContainer, "arrowTop", !showOnTop);
    toggleClass(self.calendarContainer, "arrowBottom", showOnTop);
    if (self.config.inline)
      return;
    var left = window.pageXOffset + inputBounds.left;
    var isCenter = false;
    var isRight = false;
    if (configPosHorizontal === "center") {
      left -= (calendarWidth - inputBounds.width) / 2;
      isCenter = true;
    } else if (configPosHorizontal === "right") {
      left -= calendarWidth - inputBounds.width;
      isRight = true;
    }
    toggleClass(self.calendarContainer, "arrowLeft", !isCenter && !isRight);
    toggleClass(self.calendarContainer, "arrowCenter", isCenter);
    toggleClass(self.calendarContainer, "arrowRight", isRight);
    var right = window.document.body.offsetWidth - (window.pageXOffset + inputBounds.right);
    var rightMost = left + calendarWidth > window.document.body.offsetWidth;
    var centerMost = right + calendarWidth > window.document.body.offsetWidth;
    toggleClass(self.calendarContainer, "rightMost", rightMost);
    if (self.config.static)
      return;
    self.calendarContainer.style.top = top + "px";
    if (!rightMost) {
      self.calendarContainer.style.left = left + "px";
      self.calendarContainer.style.right = "auto";
    } else if (!centerMost) {
      self.calendarContainer.style.left = "auto";
      self.calendarContainer.style.right = right + "px";
    } else {
      var doc = getDocumentStyleSheet();
      if (doc === void 0)
        return;
      var bodyWidth = window.document.body.offsetWidth;
      var centerLeft = Math.max(0, bodyWidth / 2 - calendarWidth / 2);
      var centerBefore = ".flatpickr-calendar.centerMost:before";
      var centerAfter = ".flatpickr-calendar.centerMost:after";
      var centerIndex = doc.cssRules.length;
      var centerStyle = "{left:" + inputBounds.left + "px;right:auto;}";
      toggleClass(self.calendarContainer, "rightMost", false);
      toggleClass(self.calendarContainer, "centerMost", true);
      doc.insertRule(centerBefore + "," + centerAfter + centerStyle, centerIndex);
      self.calendarContainer.style.left = centerLeft + "px";
      self.calendarContainer.style.right = "auto";
    }
  }
  function getDocumentStyleSheet() {
    var editableSheet = null;
    for (var i = 0; i < document.styleSheets.length; i++) {
      var sheet = document.styleSheets[i];
      if (!sheet.cssRules)
        continue;
      try {
        sheet.cssRules;
      } catch (err) {
        continue;
      }
      editableSheet = sheet;
      break;
    }
    return editableSheet != null ? editableSheet : createStyleSheet();
  }
  function createStyleSheet() {
    var style = document.createElement("style");
    document.head.appendChild(style);
    return style.sheet;
  }
  function redraw() {
    if (self.config.noCalendar || self.isMobile)
      return;
    buildMonthSwitch();
    updateNavigationCurrentMonth();
    buildDays();
  }
  function focusAndClose() {
    self._input.focus();
    if (window.navigator.userAgent.indexOf("MSIE") !== -1 || navigator.msMaxTouchPoints !== void 0) {
      setTimeout(self.close, 0);
    } else {
      self.close();
    }
  }
  function selectDate(e) {
    e.preventDefault();
    e.stopPropagation();
    var isSelectable = function(day) {
      return day.classList && day.classList.contains("flatpickr-day") && !day.classList.contains("flatpickr-disabled") && !day.classList.contains("notAllowed");
    };
    var t = findParent(getEventTarget(e), isSelectable);
    if (t === void 0)
      return;
    var target = t;
    var selectedDate = self.latestSelectedDateObj = new Date(target.dateObj.getTime());
    var shouldChangeMonth = (selectedDate.getMonth() < self.currentMonth || selectedDate.getMonth() > self.currentMonth + self.config.showMonths - 1) && self.config.mode !== "range";
    self.selectedDateElem = target;
    if (self.config.mode === "single")
      self.selectedDates = [selectedDate];
    else if (self.config.mode === "multiple") {
      var selectedIndex = isDateSelected(selectedDate);
      if (selectedIndex)
        self.selectedDates.splice(parseInt(selectedIndex), 1);
      else
        self.selectedDates.push(selectedDate);
    } else if (self.config.mode === "range") {
      if (self.selectedDates.length === 2) {
        self.clear(false, false);
      }
      self.latestSelectedDateObj = selectedDate;
      self.selectedDates.push(selectedDate);
      if (compareDates(selectedDate, self.selectedDates[0], true) !== 0)
        self.selectedDates.sort(function(a, b) {
          return a.getTime() - b.getTime();
        });
    }
    setHoursFromInputs();
    if (shouldChangeMonth) {
      var isNewYear = self.currentYear !== selectedDate.getFullYear();
      self.currentYear = selectedDate.getFullYear();
      self.currentMonth = selectedDate.getMonth();
      if (isNewYear) {
        triggerEvent("onYearChange");
        buildMonthSwitch();
      }
      triggerEvent("onMonthChange");
    }
    updateNavigationCurrentMonth();
    buildDays();
    updateValue();
    if (!shouldChangeMonth && self.config.mode !== "range" && self.config.showMonths === 1)
      focusOnDayElem(target);
    else if (self.selectedDateElem !== void 0 && self.hourElement === void 0) {
      self.selectedDateElem && self.selectedDateElem.focus();
    }
    if (self.hourElement !== void 0)
      self.hourElement !== void 0 && self.hourElement.focus();
    if (self.config.closeOnSelect) {
      var single = self.config.mode === "single" && !self.config.enableTime;
      var range = self.config.mode === "range" && self.selectedDates.length === 2 && !self.config.enableTime;
      if (single || range) {
        focusAndClose();
      }
    }
    triggerChange();
  }
  var CALLBACKS = {
    locale: [setupLocale, updateWeekdays],
    showMonths: [buildMonths, setCalendarWidth, buildWeekdays],
    minDate: [jumpToDate],
    maxDate: [jumpToDate],
    positionElement: [updatePositionElement],
    clickOpens: [
      function() {
        if (self.config.clickOpens === true) {
          bind(self._input, "focus", self.open);
          bind(self._input, "click", self.open);
        } else {
          self._input.removeEventListener("focus", self.open);
          self._input.removeEventListener("click", self.open);
        }
      }
    ]
  };
  function set(option, value) {
    if (option !== null && typeof option === "object") {
      Object.assign(self.config, option);
      for (var key in option) {
        if (CALLBACKS[key] !== void 0)
          CALLBACKS[key].forEach(function(x) {
            return x();
          });
      }
    } else {
      self.config[option] = value;
      if (CALLBACKS[option] !== void 0)
        CALLBACKS[option].forEach(function(x) {
          return x();
        });
      else if (HOOKS.indexOf(option) > -1)
        self.config[option] = arrayify(value);
    }
    self.redraw();
    updateValue(true);
  }
  function setSelectedDate(inputDate, format) {
    var dates = [];
    if (inputDate instanceof Array)
      dates = inputDate.map(function(d) {
        return self.parseDate(d, format);
      });
    else if (inputDate instanceof Date || typeof inputDate === "number")
      dates = [self.parseDate(inputDate, format)];
    else if (typeof inputDate === "string") {
      switch (self.config.mode) {
        case "single":
        case "time":
          dates = [self.parseDate(inputDate, format)];
          break;
        case "multiple":
          dates = inputDate.split(self.config.conjunction).map(function(date) {
            return self.parseDate(date, format);
          });
          break;
        case "range":
          dates = inputDate.split(self.l10n.rangeSeparator).map(function(date) {
            return self.parseDate(date, format);
          });
          break;
        default:
          break;
      }
    } else
      self.config.errorHandler(new Error("Invalid date supplied: " + JSON.stringify(inputDate)));
    self.selectedDates = self.config.allowInvalidPreload ? dates : dates.filter(function(d) {
      return d instanceof Date && isEnabled(d, false);
    });
    if (self.config.mode === "range")
      self.selectedDates.sort(function(a, b) {
        return a.getTime() - b.getTime();
      });
  }
  function setDate(date, triggerChange2, format) {
    if (triggerChange2 === void 0) {
      triggerChange2 = false;
    }
    if (format === void 0) {
      format = self.config.dateFormat;
    }
    if (date !== 0 && !date || date instanceof Array && date.length === 0)
      return self.clear(triggerChange2);
    setSelectedDate(date, format);
    self.latestSelectedDateObj = self.selectedDates[self.selectedDates.length - 1];
    self.redraw();
    jumpToDate(void 0, triggerChange2);
    setHoursFromDate();
    if (self.selectedDates.length === 0) {
      self.clear(false);
    }
    updateValue(triggerChange2);
    if (triggerChange2)
      triggerEvent("onChange");
  }
  function parseDateRules(arr) {
    return arr.slice().map(function(rule) {
      if (typeof rule === "string" || typeof rule === "number" || rule instanceof Date) {
        return self.parseDate(rule, void 0, true);
      } else if (rule && typeof rule === "object" && rule.from && rule.to)
        return {
          from: self.parseDate(rule.from, void 0),
          to: self.parseDate(rule.to, void 0)
        };
      return rule;
    }).filter(function(x) {
      return x;
    });
  }
  function setupDates() {
    self.selectedDates = [];
    self.now = self.parseDate(self.config.now) || new Date();
    var preloadedDate = self.config.defaultDate || ((self.input.nodeName === "INPUT" || self.input.nodeName === "TEXTAREA") && self.input.placeholder && self.input.value === self.input.placeholder ? null : self.input.value);
    if (preloadedDate)
      setSelectedDate(preloadedDate, self.config.dateFormat);
    self._initialDate = self.selectedDates.length > 0 ? self.selectedDates[0] : self.config.minDate && self.config.minDate.getTime() > self.now.getTime() ? self.config.minDate : self.config.maxDate && self.config.maxDate.getTime() < self.now.getTime() ? self.config.maxDate : self.now;
    self.currentYear = self._initialDate.getFullYear();
    self.currentMonth = self._initialDate.getMonth();
    if (self.selectedDates.length > 0)
      self.latestSelectedDateObj = self.selectedDates[0];
    if (self.config.minTime !== void 0)
      self.config.minTime = self.parseDate(self.config.minTime, "H:i");
    if (self.config.maxTime !== void 0)
      self.config.maxTime = self.parseDate(self.config.maxTime, "H:i");
    self.minDateHasTime = !!self.config.minDate && (self.config.minDate.getHours() > 0 || self.config.minDate.getMinutes() > 0 || self.config.minDate.getSeconds() > 0);
    self.maxDateHasTime = !!self.config.maxDate && (self.config.maxDate.getHours() > 0 || self.config.maxDate.getMinutes() > 0 || self.config.maxDate.getSeconds() > 0);
  }
  function setupInputs() {
    self.input = getInputElem();
    if (!self.input) {
      self.config.errorHandler(new Error("Invalid input element specified"));
      return;
    }
    self.input._type = self.input.type;
    self.input.type = "text";
    self.input.classList.add("flatpickr-input");
    self._input = self.input;
    if (self.config.altInput) {
      self.altInput = createElement(self.input.nodeName, self.config.altInputClass);
      self._input = self.altInput;
      self.altInput.placeholder = self.input.placeholder;
      self.altInput.disabled = self.input.disabled;
      self.altInput.required = self.input.required;
      self.altInput.tabIndex = self.input.tabIndex;
      self.altInput.type = "text";
      self.input.setAttribute("type", "hidden");
      if (!self.config.static && self.input.parentNode)
        self.input.parentNode.insertBefore(self.altInput, self.input.nextSibling);
    }
    if (!self.config.allowInput)
      self._input.setAttribute("readonly", "readonly");
    updatePositionElement();
  }
  function updatePositionElement() {
    self._positionElement = self.config.positionElement || self._input;
  }
  function setupMobile() {
    var inputType = self.config.enableTime ? self.config.noCalendar ? "time" : "datetime-local" : "date";
    self.mobileInput = createElement("input", self.input.className + " flatpickr-mobile");
    self.mobileInput.tabIndex = 1;
    self.mobileInput.type = inputType;
    self.mobileInput.disabled = self.input.disabled;
    self.mobileInput.required = self.input.required;
    self.mobileInput.placeholder = self.input.placeholder;
    self.mobileFormatStr = inputType === "datetime-local" ? "Y-m-d\\TH:i:S" : inputType === "date" ? "Y-m-d" : "H:i:S";
    if (self.selectedDates.length > 0) {
      self.mobileInput.defaultValue = self.mobileInput.value = self.formatDate(self.selectedDates[0], self.mobileFormatStr);
    }
    if (self.config.minDate)
      self.mobileInput.min = self.formatDate(self.config.minDate, "Y-m-d");
    if (self.config.maxDate)
      self.mobileInput.max = self.formatDate(self.config.maxDate, "Y-m-d");
    if (self.input.getAttribute("step"))
      self.mobileInput.step = String(self.input.getAttribute("step"));
    self.input.type = "hidden";
    if (self.altInput !== void 0)
      self.altInput.type = "hidden";
    try {
      if (self.input.parentNode)
        self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling);
    } catch (_a) {
    }
    bind(self.mobileInput, "change", function(e) {
      self.setDate(getEventTarget(e).value, false, self.mobileFormatStr);
      triggerEvent("onChange");
      triggerEvent("onClose");
    });
  }
  function toggle(e) {
    if (self.isOpen === true)
      return self.close();
    self.open(e);
  }
  function triggerEvent(event, data) {
    if (self.config === void 0)
      return;
    var hooks = self.config[event];
    if (hooks !== void 0 && hooks.length > 0) {
      for (var i = 0; hooks[i] && i < hooks.length; i++)
        hooks[i](self.selectedDates, self.input.value, self, data);
    }
    if (event === "onChange") {
      self.input.dispatchEvent(createEvent("change"));
      self.input.dispatchEvent(createEvent("input"));
    }
  }
  function createEvent(name) {
    var e = document.createEvent("Event");
    e.initEvent(name, true, true);
    return e;
  }
  function isDateSelected(date) {
    for (var i = 0; i < self.selectedDates.length; i++) {
      var selectedDate = self.selectedDates[i];
      if (selectedDate instanceof Date && compareDates(selectedDate, date) === 0)
        return "" + i;
    }
    return false;
  }
  function isDateInRange(date) {
    if (self.config.mode !== "range" || self.selectedDates.length < 2)
      return false;
    return compareDates(date, self.selectedDates[0]) >= 0 && compareDates(date, self.selectedDates[1]) <= 0;
  }
  function updateNavigationCurrentMonth() {
    if (self.config.noCalendar || self.isMobile || !self.monthNav)
      return;
    self.yearElements.forEach(function(yearElement, i) {
      var d = new Date(self.currentYear, self.currentMonth, 1);
      d.setMonth(self.currentMonth + i);
      if (self.config.showMonths > 1 || self.config.monthSelectorType === "static") {
        self.monthElements[i].textContent = monthToStr(d.getMonth(), self.config.shorthandCurrentMonth, self.l10n) + " ";
      } else {
        self.monthsDropdownContainer.value = d.getMonth().toString();
      }
      yearElement.value = d.getFullYear().toString();
    });
    self._hidePrevMonthArrow = self.config.minDate !== void 0 && (self.currentYear === self.config.minDate.getFullYear() ? self.currentMonth <= self.config.minDate.getMonth() : self.currentYear < self.config.minDate.getFullYear());
    self._hideNextMonthArrow = self.config.maxDate !== void 0 && (self.currentYear === self.config.maxDate.getFullYear() ? self.currentMonth + 1 > self.config.maxDate.getMonth() : self.currentYear > self.config.maxDate.getFullYear());
  }
  function getDateStr(specificFormat) {
    var format = specificFormat || (self.config.altInput ? self.config.altFormat : self.config.dateFormat);
    return self.selectedDates.map(function(dObj) {
      return self.formatDate(dObj, format);
    }).filter(function(d, i, arr) {
      return self.config.mode !== "range" || self.config.enableTime || arr.indexOf(d) === i;
    }).join(self.config.mode !== "range" ? self.config.conjunction : self.l10n.rangeSeparator);
  }
  function updateValue(triggerChange2) {
    if (triggerChange2 === void 0) {
      triggerChange2 = true;
    }
    if (self.mobileInput !== void 0 && self.mobileFormatStr) {
      self.mobileInput.value = self.latestSelectedDateObj !== void 0 ? self.formatDate(self.latestSelectedDateObj, self.mobileFormatStr) : "";
    }
    self.input.value = getDateStr(self.config.dateFormat);
    if (self.altInput !== void 0) {
      self.altInput.value = getDateStr(self.config.altFormat);
    }
    if (triggerChange2 !== false)
      triggerEvent("onValueUpdate");
  }
  function onMonthNavClick(e) {
    var eventTarget = getEventTarget(e);
    var isPrevMonth = self.prevMonthNav.contains(eventTarget);
    var isNextMonth = self.nextMonthNav.contains(eventTarget);
    if (isPrevMonth || isNextMonth) {
      changeMonth(isPrevMonth ? -1 : 1);
    } else if (self.yearElements.indexOf(eventTarget) >= 0) {
      eventTarget.select();
    } else if (eventTarget.classList.contains("arrowUp")) {
      self.changeYear(self.currentYear + 1);
    } else if (eventTarget.classList.contains("arrowDown")) {
      self.changeYear(self.currentYear - 1);
    }
  }
  function timeWrapper(e) {
    e.preventDefault();
    var isKeyDown = e.type === "keydown", eventTarget = getEventTarget(e), input = eventTarget;
    if (self.amPM !== void 0 && eventTarget === self.amPM) {
      self.amPM.textContent = self.l10n.amPM[int2(self.amPM.textContent === self.l10n.amPM[0])];
    }
    var min = parseFloat(input.getAttribute("min")), max = parseFloat(input.getAttribute("max")), step = parseFloat(input.getAttribute("step")), curValue = parseInt(input.value, 10), delta = e.delta || (isKeyDown ? e.which === 38 ? 1 : -1 : 0);
    var newValue = curValue + step * delta;
    if (typeof input.value !== "undefined" && input.value.length === 2) {
      var isHourElem = input === self.hourElement, isMinuteElem = input === self.minuteElement;
      if (newValue < min) {
        newValue = max + newValue + int2(!isHourElem) + (int2(isHourElem) && int2(!self.amPM));
        if (isMinuteElem)
          incrementNumInput(void 0, -1, self.hourElement);
      } else if (newValue > max) {
        newValue = input === self.hourElement ? newValue - max - int2(!self.amPM) : min;
        if (isMinuteElem)
          incrementNumInput(void 0, 1, self.hourElement);
      }
      if (self.amPM && isHourElem && (step === 1 ? newValue + curValue === 23 : Math.abs(newValue - curValue) > step)) {
        self.amPM.textContent = self.l10n.amPM[int2(self.amPM.textContent === self.l10n.amPM[0])];
      }
      input.value = pad(newValue);
    }
  }
  init();
  return self;
}
function _flatpickr(nodeList, config) {
  var nodes = Array.prototype.slice.call(nodeList).filter(function(x) {
    return x instanceof HTMLElement;
  });
  var instances = [];
  for (var i = 0; i < nodes.length; i++) {
    var node = nodes[i];
    try {
      if (node.getAttribute("data-fp-omit") !== null)
        continue;
      if (node._flatpickr !== void 0) {
        node._flatpickr.destroy();
        node._flatpickr = void 0;
      }
      node._flatpickr = FlatpickrInstance(node, config || {});
      instances.push(node._flatpickr);
    } catch (e) {
      console.error(e);
    }
  }
  return instances.length === 1 ? instances[0] : instances;
}
if (typeof HTMLElement !== "undefined" && typeof HTMLCollection !== "undefined" && typeof NodeList !== "undefined") {
  HTMLCollection.prototype.flatpickr = NodeList.prototype.flatpickr = function(config) {
    return _flatpickr(this, config);
  };
  HTMLElement.prototype.flatpickr = function(config) {
    return _flatpickr([this], config);
  };
}
var flatpickr = function(selector, config) {
  if (typeof selector === "string") {
    return _flatpickr(window.document.querySelectorAll(selector), config);
  } else if (selector instanceof Node) {
    return _flatpickr([selector], config);
  } else {
    return _flatpickr(selector, config);
  }
};
flatpickr.defaultConfig = {};
flatpickr.l10ns = {
  en: __assign({}, default_default),
  default: __assign({}, default_default)
};
flatpickr.localize = function(l10n) {
  flatpickr.l10ns.default = __assign(__assign({}, flatpickr.l10ns.default), l10n);
};
flatpickr.setDefaults = function(config) {
  flatpickr.defaultConfig = __assign(__assign({}, flatpickr.defaultConfig), config);
};
flatpickr.parseDate = createDateParser({});
flatpickr.formatDate = createDateFormatter({});
flatpickr.compareDates = compareDates;
if (typeof jQuery !== "undefined" && typeof jQuery.fn !== "undefined") {
  jQuery.fn.flatpickr = function(config) {
    return _flatpickr(this, config);
  };
}
Date.prototype.fp_incr = function(days) {
  return new Date(this.getFullYear(), this.getMonth(), this.getDate() + (typeof days === "string" ? parseInt(days, 10) : days));
};
if (typeof window !== "undefined") {
  window.flatpickr = flatpickr;
}
var esm_default = flatpickr;

// src/services/dateService/views/elements/DateElement.ts
var DateElement = class extends AbstractElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const options = {
      allowInput: true,
      dateFormat: "Y-m-d",
      altInput: true,
      onChange: (selectedDate, dateStr, instance) => {
        if (data.editableKey !== void 0)
          this.api.service(CodeblockService).addOrUpdate(data.editableKey, dateStr);
      }
    };
    if (data.values !== void 0)
      options.defaultDate = data.values.date;
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const flatpickrEl = contentEl.createEl("input", { cls: "flatpickr", type: "text" });
    flatpickrEl.readOnly = true;
    esm_default(flatpickrEl, options);
  }
};

// src/services/fantasyCalendarService/picker/FantasyCalendarDatePicker.ts
var FantasyCalendarDatePicker = class {
  constructor(_api, _containerEl, _id, _model, _saver, _currentDate) {
    this._api = _api;
    this._containerEl = _containerEl;
    this._id = _id;
    this._model = _model;
    this._saver = _saver;
    this._currentDate = _currentDate;
    this._listener = (evt) => this._eventMaybeClose(evt);
    if (this._model.campaign.fantasyCalendar === void 0)
      throw new Error("");
    if (this._currentDate === void 0) {
      if (this._model.campaign.date !== void 0) {
        this._currentDate = this._model.campaign.date.date;
      }
    }
    this._calendar = this._model.campaign.fantasyCalendar;
    this._percentageWidth = (100 / this._calendar.static.weekdays.length).toString() + "%";
    this._width = (300 / this._calendar.static.weekdays.length).toString() + "px";
    this._height = 300 / this._calendar.static.weekdays.length > 39 ? "39px" : (300 / this._calendar.static.weekdays.length).toString() + "px";
    this._containerEl.addEventListener("focusin", this._show.bind(this));
  }
  _eventMaybeClose(evt) {
    const clickedClassName = evt.target;
    if (clickedClassName == null)
      this.hide();
    let inPicker = true;
    try {
      inPicker = clickedClassName.className.indexOf(this._id) !== -1;
    } catch (e) {
      inPicker = false;
    }
    if (!inPicker)
      this.hide();
  }
  _show() {
    return __async(this, null, function* () {
      this._pickerEl = document.createElement("div");
      this._pickerEl.addClass("rpg-manager-fantasy-calendar-picker");
      this._pickerEl.addClass(this._id);
      const pickerContainerEl = this._pickerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-container " + this._id });
      this._addNavigatorContainer(pickerContainerEl);
      this._addMonthContainer(pickerContainerEl);
      document.body.append(this._pickerEl);
      this._pickerEl.style.left = this._containerEl.getBoundingClientRect().left.toString() + "px";
      this._pickerEl.style.top = (this._containerEl.getBoundingClientRect().top + this._containerEl.offsetHeight).toString() + "px";
      this._loadMonth();
      document.body.addEventListener("click", this._listener);
    });
  }
  _save(date) {
    this._containerEl.value = this._api.service(FantasyCalendarService).getDay(date, this._calendar).displayDate;
    this._saver(this._containerEl.value);
    this.hide();
  }
  hide() {
    return __async(this, null, function* () {
      document.body.removeEventListener("click", this._listener);
      if (this._pickerEl === void 0)
        return;
      this._pickerEl.remove();
      this._pickerEl = void 0;
      const possiblePickers = document.getElementsByClassName(this._id);
      for (let index = 0; index < possiblePickers.length; index++) {
        if (possiblePickers[index].hasClass("rpg-manager-fantasy-calendar-picker"))
          possiblePickers[index].remove();
      }
    });
  }
  _addNavigatorContainer(containerEl) {
    const navigationContainerEl = containerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-navigation clearfix " + this._id });
    const previousMonthElement = navigationContainerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-navigation-previous " + this._id, text: "<" });
    previousMonthElement.addEventListener("click", this._previousMonth.bind(this));
    const monthSelectorContainerEl = navigationContainerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-navigation-month-container " + this._id });
    this._monthSelectorEl = monthSelectorContainerEl.createEl("select", { cls: "rpg-manager-fantasy-calendar-picker-navigation-month-selector " + this._id });
    this._monthSelectorEl.addEventListener("change", () => {
      this._loadMonth();
    });
    this._calendar.static.months.forEach((month, index) => {
      const monthEl = this._monthSelectorEl.createEl("option", { value: index.toString(), text: month.name });
      this._monthSelectorEl.add(monthEl);
    });
    if (this._currentDate !== void 0)
      this._monthSelectorEl.selectedIndex = this._currentDate.month;
    const nextMonthElement = navigationContainerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-navigation-next " + this._id, text: ">" });
    nextMonthElement.addEventListener("click", this._nextMonth.bind(this));
    const yearSelectorContainer = navigationContainerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-navigation-year-container " + this._id });
    this._yearSelectorEl = yearSelectorContainer.createEl("input", { cls: "rpg-manager-fantasy-calendar-picker-navigation-year " + this._id, type: "number", value: this._currentDate !== void 0 ? this._currentDate.year.toString() : "" });
    this._yearSelectorEl.addEventListener("focusout", () => {
      this._loadMonth();
    });
    this._yearSelectorEl.addEventListener("keyup", (evt) => {
      if (evt.key === "Tab") {
        evt.preventDefault();
        this._loadMonth();
      }
      if (evt.key === "Enter") {
        this._loadMonth();
      }
    });
    this._yearSelectorEl.addEventListener("change", (evt) => {
      this._loadMonth();
    });
    const addYear = yearSelectorContainer.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-navigation-year-add " + this._id, text: "+" });
    addYear.addEventListener("click", () => {
      this._yearSelectorEl.value = (+this._yearSelectorEl.value + 1).toString();
      this._loadMonth();
    });
    const removeYear = yearSelectorContainer.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-navigation-year-remove " + this._id, text: "-" });
    removeYear.addEventListener("click", () => {
      this._yearSelectorEl.value = (+this._yearSelectorEl.value - 1).toString();
      this._loadMonth();
    });
  }
  _addMonthContainer(containerEl) {
    this._monthContainerEl = containerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-month " + this._id });
  }
  _previousMonth() {
    if (+this._monthSelectorEl.value === 0) {
      this._yearSelectorEl.value = (+this._yearSelectorEl.value - 1).toString();
      this._monthSelectorEl.selectedIndex = this._calendar.static.months.length - 1;
    } else {
      this._monthSelectorEl.selectedIndex = this._monthSelectorEl.selectedIndex - 1;
    }
    this._loadMonth();
  }
  _nextMonth() {
    if (+this._monthSelectorEl.value === this._calendar.static.months.length - 1) {
      this._yearSelectorEl.value = (+this._yearSelectorEl.value + 1).toString();
      this._monthSelectorEl.selectedIndex = 0;
    } else {
      this._monthSelectorEl.selectedIndex = this._monthSelectorEl.selectedIndex + 1;
    }
    this._loadMonth();
  }
  _loadMonth() {
    var _a, _b, _c;
    this._monthContainerEl.empty();
    const daysInAWeek = this._calendar.static.weekdays.length;
    const weekdays2 = this._calendar.static.weekdays;
    const month = this._calendar.static.months[+this._monthSelectorEl.value];
    const weekdaysEl = this._monthContainerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-month-weekdays " + this._id });
    const weekdayContainerEl = weekdaysEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-month-weekday-container " + this._id });
    weekdays2.forEach((day) => {
      const weekdayEl = weekdayContainerEl.createSpan({ cls: "rpg-manager-fantasy-calendar-picker-month-weekday " + this._id, text: day.name.substring(0, 3) });
      this._setDayStyle(weekdayEl);
    });
    let dayCount = 0;
    let awaitWeekStart = true;
    let dayOfTheWeek = 0;
    const firstDay = this._api.service(FantasyCalendarService).getDay({ year: +this._yearSelectorEl.value, month: +this._monthSelectorEl.value, day: 1 }, this._calendar);
    const daysEl = this._monthContainerEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-month-days " + this._id });
    const dayContainerEl = daysEl.createDiv({ cls: "rpg-manager-fantasy-calendar-picker-month-day-container " + this._id });
    while (dayCount < month.length) {
      const dayEl = dayContainerEl.createSpan({ cls: "rpg-manager-fantasy-calendar-picker-month-day " + this._id });
      let date = {
        year: +this._yearSelectorEl.value,
        month: +this._monthSelectorEl.value,
        day: dayCount + 1
      };
      if (awaitWeekStart && firstDay.weekday > dayOfTheWeek) {
        date = this._removeDays(date.year, date.month, firstDay.weekday - dayOfTheWeek);
        dayEl.addClass("rpg-manager-fantasy-calendar-picker-previous-month-day");
        dayEl.addClass(this._id);
      } else {
        if (((_a = this._currentDate) == null ? void 0 : _a.year) === date.year && ((_b = this._currentDate) == null ? void 0 : _b.month) === date.month && ((_c = this._currentDate) == null ? void 0 : _c.day) === date.day)
          dayEl.addClass("rpg-manager-fantasy-calendar-picker-month-day-selected");
        if (this._calendar.current.year === date.year && this._calendar.current.month === date.month && this._calendar.current.day === date.day)
          dayEl.addClass("rpg-manager-fantasy-calendar-picker-month-day-today");
        awaitWeekStart = false;
        dayCount++;
      }
      dayEl.textContent = date.day.toString();
      dayOfTheWeek++;
      this._setDayStyle(dayEl);
      dayEl.addEventListener("click", () => {
        this._save(date);
      });
    }
    let additionalDays = 0;
    while (dayOfTheWeek % daysInAWeek !== 0) {
      additionalDays++;
      const newDate = this._addDays(+this._yearSelectorEl.value, +this._monthSelectorEl.value, additionalDays);
      const dayEl = dayContainerEl.createSpan({ cls: "rpg-manager-fantasy-calendar-picker-month-day " + this._id });
      dayEl.textContent = newDate.day.toString();
      dayEl.addClass("rpg-manager-fantasy-calendar-picker-previous-month-day");
      dayEl.addClass(this._id);
      this._setDayStyle(dayEl);
      dayEl.addEventListener("click", () => {
        this._save(newDate);
      });
      dayOfTheWeek++;
    }
  }
  _removeDays(year, month, daysToRemove) {
    let newYear = month === 0 ? year - 1 : year;
    let newMonth = month === 0 ? this._calendar.static.months.length : month - 1;
    let newDay = this._calendar.static.months[newMonth].length;
    daysToRemove--;
    while (daysToRemove > 0) {
      if (newDay === 1) {
        if (newMonth === 0) {
          newYear--;
          newMonth = this._calendar.static.months.length;
        } else {
          newMonth--;
        }
        newDay = this._calendar.static.months[newMonth].length;
      } else {
        newDay--;
      }
      daysToRemove--;
    }
    return {
      year: newYear,
      month: newMonth,
      day: newDay
    };
  }
  _addDays(year, month, daysToAdd) {
    let newDay = 1;
    let newMonth = month === this._calendar.static.months.length ? 0 : month + 1;
    let newYear = month === this._calendar.static.months.length ? year + 1 : year;
    daysToAdd--;
    while (daysToAdd > 0) {
      if (newDay === this._calendar.static.months[newMonth].length) {
        if (newMonth === this._calendar.static.months.length) {
          newMonth = 0;
          newYear++;
        } else {
          newMonth++;
        }
        newDay = 1;
      } else {
        newDay++;
      }
      daysToAdd--;
    }
    return {
      year: newYear,
      month: newMonth,
      day: newDay
    };
  }
  _setDayStyle(containerEl) {
    containerEl.style.width = this._percentageWidth;
    containerEl.style.flexBasis = this._percentageWidth;
    containerEl.style.maxWidth = this._width;
    containerEl.style.height = this._height;
    containerEl.style.lineHeight = this._height;
  }
};

// src/services/fantasyCalendarService/views/elements/FantasyCalendarElement.ts
var FantasyCalendarElement = class extends AbstractElement {
  render(data, containerEl) {
    var _a;
    this._data = data;
    const calendar = data.model.campaign.fantasyCalendar;
    if (calendar === void 0)
      return;
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    let dateValue = "";
    if (data.values !== void 0 && data.values.date !== void 0 && data.model.campaign.fantasyCalendar !== void 0)
      dateValue = this.api.service(FantasyCalendarService).getDay(data.values.date, data.model.campaign.fantasyCalendar).displayDate;
    const id = v4_default();
    this._inputEl = contentEl.createEl("input", { cls: "rpg-manager-fantasy-calendar-picker-launcher " + id });
    this._inputEl.type = "text";
    this._inputEl.value = dateValue;
    const picker = new FantasyCalendarDatePicker(this.api, this._inputEl, id, data.model, this._saveDate.bind(this), (_a = data.values) == null ? void 0 : _a.date);
    this._inputEl.addEventListener("change", () => {
      this._saveDate(this._inputEl.value);
      picker.hide();
    });
  }
  _saveDate(newDate) {
    return __async(this, null, function* () {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i;
      if (newDate == void 0)
        return;
      if (((_a = this._data.values) == null ? void 0 : _a.category) === void 0 && this._data.category === void 0)
        return;
      const categoryName = (_c = (_b = this._data.values) == null ? void 0 : _b.category) != null ? _c : this._data.category;
      if (categoryName === void 0)
        return;
      const calendar = this._data.model.campaign.fantasyCalendar;
      if (calendar === void 0)
        return;
      let categories = calendar.categories.filter((category) => category.name === categoryName);
      if (categories.length === 0)
        categories = [yield this.api.service(FantasyCalendarService).addCategory(categoryName, calendar)];
      const events = calendar.events.filter((event) => event.note === this._data.model.file.path.slice(0, -3) && event.category === categories[0].id);
      if (newDate === "" && events.length > 0) {
        for (let index = 0; index < calendar.events.length; index++) {
          if (calendar.events[index].note === this._data.model.file.path.slice(0, -3) && calendar.events[index].category === categories[0].id) {
            calendar.events.splice(index, 1);
            break;
          }
        }
      } else {
        const [monthAndDay, yearNumber] = newDate.split(",");
        const monthSeparator = monthAndDay.lastIndexOf(" ");
        const monthName = monthAndDay.substring(0, monthSeparator);
        const dirtyDay = monthAndDay.substring(monthSeparator);
        const day = dirtyDay.replace(/\D/g, "");
        if (monthName == void 0 || day == void 0 || yearNumber == void 0 || !Number.isInteger(+yearNumber) || monthName === "" || day === "")
          return;
        const newFantasyCalendarDay = this.api.service(FantasyCalendarService).getDay({ year: +yearNumber, month: monthName, day: +day }, calendar);
        if (((_e = (_d = this._data.values) == null ? void 0 : _d.date) == null ? void 0 : _e.year) === newFantasyCalendarDay.date.year && ((_g = (_f = this._data.values) == null ? void 0 : _f.date) == null ? void 0 : _g.month) === newFantasyCalendarDay.date.month && ((_i = (_h = this._data.values) == null ? void 0 : _h.date) == null ? void 0 : _i.day) === newFantasyCalendarDay.date.day)
          return;
        let event = void 0;
        if (events.length === 1) {
          event = events[0];
          event.date = newFantasyCalendarDay.date;
        } else {
          let name = this._data.model.file.basename;
          switch (categoryName) {
            case "RPG Manager Death" /* Death */:
              name = "Death of " + name;
              break;
            case "RPG Manager Birth" /* Birth */:
              name = "Birth of " + name;
              break;
            case "RPG Manager Clue Found" /* ClueFound */:
              name = "Clue " + name + " found";
              break;
            case "RPG Manager Event" /* Event */:
              name = "Event " + name;
              break;
          }
          if (categoryName === "current" /* CurrentDate */) {
            calendar.current = newFantasyCalendarDay.date;
          } else {
            event = {
              auto: false,
              id: "ID_RPGM_" + Date.now().toString(),
              name,
              note: this._data.model.file.path.slice(0, -3),
              category: categories[0].id,
              description: "",
              date: newFantasyCalendarDay.date
            };
            calendar.events.push(event);
          }
        }
        this._data.values = this.api.service(DateService).getDate(newFantasyCalendarDay.date.year + "-" + newFantasyCalendarDay.date.month + "-" + newFantasyCalendarDay.date.day, "RPG Manager Scene" /* Scene */, this._data.model);
      }
      yield this.api.app.plugins.getPlugin("fantasy-calendar").saveCalendar();
      this.api.app.plugins.getPlugin("fantasy-calendar").api.getHelper(calendar).update(calendar);
      this._data.model.touch(true);
      this.api.app.workspace.trigger("rpgmanager:refresh-views");
      setTimeout(() => {
        this.api.app.workspace.trigger("fantasy-calendars-settings-loaded");
        this.api.app.plugins.getPlugin("fantasy-calendar").api.getHelper(calendar).update(calendar);
      }, 1e3);
    });
  }
};

// src/components/campaign/views/CampaignHeaderView.ts
var CampaignHeaderView = class extends AbstractHeaderView {
  render() {
    this.addTitle();
    this.addComponentOptions();
    const adventures = this.api.database.readChildren(2 /* Adventure */, this.model.index.id).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((component) => component.file.stat.mtime, 1 /* Descending */)
    ]));
    this.addInfoElement(ModelSelectorElement, { model: this.model, title: "Current Adventure", values: { index: this.model.currentAdventureId, list: adventures }, editableKey: "data.currentAdventureId" });
    let acts = this.api.database.read((model) => model.index.type === 4 /* Act */ && model.index.campaignId === this.model.index.id).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((component) => component.file.stat.mtime, 1 /* Descending */)
    ]));
    if (this.model.currentAdventureId != void 0)
      acts = acts.filter((act) => {
        var _a;
        return act.index.parentId === ((_a = this.model.currentAdventureId) == null ? void 0 : _a.id);
      });
    this.addInfoElement(ModelSelectorElement, { model: this.model, title: "Current Act", values: { index: this.model.currentActId, list: acts }, editableKey: "data.currentActId" });
    const sessions = this.api.database.readChildren(16 /* Session */, this.model.index.id).sort(this.api.service(SorterService).create([
      new SorterComparisonElement((component) => component.file.stat.mtime, 1 /* Descending */)
    ]));
    this.addInfoElement(ModelSelectorElement, { model: this.model, title: "Current Session", values: { index: this.model.currentSessionId, list: sessions }, editableKey: "data.currentSessionId" });
    this.addInfoElement(this.model.calendar === 0 /* Gregorian */ ? DateElement : FantasyCalendarElement, { model: this.model, title: "Current Date", values: this.model.date, category: "current" /* CurrentDate */, editableKey: "data.date" });
    if (this.api.settings.usePlotStructures)
      this.addPlot();
  }
  addTitle() {
    if (this.model.images.length == 0) {
      super.addTitle();
    } else {
      const titleOverlayEl = this.titleContainerEl.createDiv({ cls: "rpg-manager-header-container-title-overlay" });
      const titleEl = titleOverlayEl.createDiv({ cls: "rpg-manager-header-container-title-name" });
      titleEl.textContent = this.model.file.basename;
      this.titleContainerEl.addClass("rpg-manager-header-container-title-overlay");
      this.titleContainerEl.style.backgroundImage = "url('" + this.model.images[0].src + "')";
    }
  }
};

// src/components/campaign/templates/CampaignTemplate.ts
var CampaignTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      plot: {
        abt: {
          need: "",
          and: "",
          but: "",
          therefore: ""
        },
        storycircle: {
          you: "",
          need: "",
          go: "",
          search: "",
          find: "",
          take: "",
          return: "",
          change: ""
        }
      },
      data: {
        date: "",
        synopsis: "",
        complete: false,
        currentAdventureId: "",
        currentActId: "",
        currentSessionId: ""
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateLastCodeBlock() {
    const metadata = {
      models: {
        lists: {
          pcs: {
            relationship: "hierarchy"
          },
          subplots: {
            relationship: "hierarchy"
          },
          adventures: {
            relationship: "hierarchy"
          },
          acts: {
            relationship: "hierarchy"
          },
          sessions: {
            relationship: "hierarchy"
          },
          events: {
            relationship: "hierarchy"
          },
          npcs: {
            relationship: "hierarchy"
          }
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 1 /* Campaign */,
      campaignSettings: 0 /* Agnostic */,
      id: this.campaignId,
      campaignId: this.campaignId,
      parentId: this.campaignId,
      positionInParent: 0
    };
  }
};

// src/components/campaign/modals/CampaignModalPart.ts
var CampaignModalPart = class extends AbstractModalPart {
  constructor(api, modal) {
    super(api, modal);
    this._campaigns = this.api.database.read((campaign) => campaign.index.type === 1 /* Campaign */);
  }
  addElement(contentEl) {
    return __async(this, null, function* () {
      const campaignEl = contentEl.createDiv({ cls: "campaignContainer" });
      if (this.modal.type === 1 /* Campaign */) {
        this.addAdditionalElements();
      } else {
        if (this._campaigns.length === 0) {
          const mainContent = this.modal.getContentEl();
          mainContent.empty();
          mainContent.createEl("h2", { cls: "rpgm-modal-title", text: "Main campaign missing" });
          mainContent.createSpan({ cls: "", text: "This Obsidian Vault does not contain a Rpg Manager campaign yet. Before creating a " + ComponentType[this.modal.type] + ", please initialise your first campaign." });
        } else {
          this._childEl = contentEl.createDiv({ cls: "child" });
          this._childEl.id = "CampaignChild";
          this._selectCampaignElements(campaignEl);
        }
      }
      if (this.modal.type === 1 /* Campaign */) {
        this.modal.saver = this;
      }
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
      if (this.modal.type !== 2 /* Adventure */ && this.modal.type !== 16 /* Session */ && this.modal.type !== 4 /* Act */ && this.modal.type !== 8 /* Scene */) {
        this.modal.elementModal = this.api.modals.getPartial(this.modal.campaignSetting, this.modal.type, this.modal);
        this.modal.elementModal.addElement(containerEl);
      } else {
        if (this.modal.type === 2 /* Adventure */ || this.modal.type === 4 /* Act */ || this.modal.type === 8 /* Scene */) {
          this.modal.adventureModal = this.api.modals.getPartial(this.modal.campaignSetting, 2 /* Adventure */, this.modal);
          this.modal.adventureModal.addElement(containerEl);
        } else if (this.modal.type === 16 /* Session */) {
          this.modal.sessionModal = this.api.modals.getPartial(this.modal.campaignSetting, 16 /* Session */, this.modal);
          this.modal.sessionModal.addElement(containerEl);
        }
      }
    });
  }
  validate() {
    if (this.modal.campaignId === void 0)
      this.modal.campaignId = this.api.service(IndexService).createUUID();
    return true;
  }
  _selectCampaignElements(containerEl) {
    const groupElement = containerEl.createDiv({ cls: "rpg-manager-modal-grid-navigation-group clearfix" });
    groupElement.createDiv({ cls: "rpg-manager-modal-grid-navigation-group-title", text: "Campaign" });
    const selectionContainerEl = groupElement.createDiv({ cls: "rpg-manager-modal-grid-navigation-group-container" });
    this._campaignEl = selectionContainerEl.createEl("select");
    if (this._campaigns.length > 1) {
      this._campaignEl.createEl("option", {
        text: "",
        value: ""
      }).selected = true;
    }
    this._campaigns.forEach((campaign) => {
      const campaignOptionEl = this._campaignEl.createEl("option", {
        text: campaign.file.basename,
        value: campaign.index.campaignId.toString()
      });
      if (this._campaigns.length === 1) {
        campaignOptionEl.selected = true;
        this._selectCampaign();
      }
    });
    this._campaignEl.addEventListener("change", (e) => {
      this._selectCampaign();
    });
    this._campaignErrorEl = containerEl.createEl("p", { cls: "error" });
  }
  _selectCampaign() {
    this.modal.campaignId = this._campaignEl.value;
    this._childEl.empty();
    this.loadChild(this._childEl);
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
  prepareAdditionalInformation() {
  }
};

// src/components/campaign/CampaignComponent.ts
var CampaignComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [CampaignModalPart];
  }
  get model() {
    return CampaignModel;
  }
  get template() {
    return CampaignTemplate;
  }
  get type() {
    return 1 /* Campaign */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [CampaignHeaderView, 0 /* Header */]
    ]);
  }
};

// src/services/pronounService/enums/Pronoun.ts
var Pronoun = /* @__PURE__ */ ((Pronoun2) => {
  Pronoun2[Pronoun2["they"] = 0] = "they";
  Pronoun2[Pronoun2["she"] = 1] = "she";
  Pronoun2[Pronoun2["he"] = 2] = "he";
  Pronoun2[Pronoun2["it"] = 3] = "it";
  Pronoun2[Pronoun2["ae"] = 4] = "ae";
  Pronoun2[Pronoun2["e"] = 5] = "e";
  Pronoun2[Pronoun2["per"] = 6] = "per";
  Pronoun2[Pronoun2["ve"] = 7] = "ve";
  Pronoun2[Pronoun2["xe"] = 8] = "xe";
  Pronoun2[Pronoun2["ze"] = 9] = "ze";
  return Pronoun2;
})(Pronoun || {});

// src/services/pronounService/PronounService.ts
var PronounService = class extends AbstractService {
  createPronoun(readablePronoun) {
    readablePronoun = readablePronoun.toLowerCase();
    return Pronoun[readablePronoun];
  }
  createReadablePronoun(pronoun) {
    return Pronoun[pronoun].toString().toLowerCase();
  }
  readPronoun(pronoun) {
    switch (pronoun) {
      case 0 /* they */:
        return "They / Them / Themself";
        break;
      case 1 /* she */:
        return "She / Her / Herself";
        break;
      case 2 /* he */:
        return "He / Him / Himself";
        break;
      case 3 /* it */:
        return "It / Its / Itself";
        break;
      case 4 /* ae */:
        return "(f)Ae / (f)Aer / (f)Aerself";
        break;
      case 5 /* e */:
        return "E(Ey) / Em / Eirelf";
        break;
      case 6 /* per */:
        return "Per / Per / Perself";
        break;
      case 7 /* ve */:
        return "Ve / Ver / Verself";
        break;
      case 8 /* xe */:
        return "Xe / Xem / Xemself";
        break;
      case 9 /* ze */:
        return "Ze(Zie) / Hir / Hirself";
        break;
    }
  }
};

// src/components/character/abstracts/AbstractCharacterData.ts
var AbstractCharacterData = class extends AbstractModel {
  get death() {
    var _a;
    return this.api.service(DateService).getDate((_a = this.metadata.data) == null ? void 0 : _a.death, "RPG Manager Death" /* Death */, this);
  }
  get dob() {
    var _a;
    return this.api.service(DateService).getDate((_a = this.metadata.data) == null ? void 0 : _a.dob, "RPG Manager Birth" /* Birth */, this);
  }
  get goals() {
    var _a;
    const response = (_a = this.metadata.data) == null ? void 0 : _a.goals;
    if (response === void 0 || response === "")
      return void 0;
    return response;
  }
  get pronoun() {
    var _a, _b;
    if (((_a = this.metadata.data) == null ? void 0 : _a.pronoun) == null || ((_b = this.metadata.data) == null ? void 0 : _b.pronoun) === "")
      return void 0;
    return this.api.service(PronounService).createPronoun(this.metadata.data.pronoun);
  }
};

// src/components/character/models/CharacterModel.ts
var CharacterModel = class extends AbstractCharacterData {
  get age() {
    return this.api.service(DateService).getAge(this.dob, this.death, this.campaign.date, this);
  }
  get isDead() {
    return this.death !== void 0;
  }
};

// src/managers/viewsManager/elements/ShortTextElement.ts
var ShortTextElement = class extends AbstractTextElement {
  render(data, containerEl) {
    this.renderText(data, containerEl, false);
  }
};

// src/components/character/views/elements/PronounElement.ts
var PronounElement = class extends AbstractTextElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const pronounSelectorEl = contentEl.createEl("select");
    pronounSelectorEl.createEl("option", {
      text: "",
      value: ""
    }).selected = true;
    Object.keys(Pronoun).filter((v) => isNaN(Number(v))).forEach((type, index) => {
      const pronoun = this.api.service(PronounService).createPronoun(type);
      const optionEl = pronounSelectorEl.createEl("option", {
        text: this.api.service(PronounService).readPronoun(pronoun),
        value: type
      });
      if (data.model.pronoun !== void 0 && pronoun === data.model.pronoun) {
        optionEl.selected = true;
      }
    });
    pronounSelectorEl.addEventListener("change", () => {
      if (data.editableKey === void 0)
        return;
      if (pronounSelectorEl.value !== "")
        this.api.service(CodeblockService).addOrUpdate(data.editableKey, pronounSelectorEl.value);
      else
        this.api.service(CodeblockService).addOrUpdate(data.editableKey, void 0);
    });
  }
};

// src/components/character/views/CharacterHeaderView.ts
var CharacterHeaderView = class extends AbstractHeaderView {
  render() {
    var _a;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, {
      model: this.model,
      title: "Description",
      values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>',
      editableKey: "data.synopsis"
    });
    this.addInfoElement(PronounElement, {
      model: this.model,
      title: "Pronoun",
      values: this.model.pronoun,
      editableKey: "data.pronoun"
    });
    if (this.model.age !== void 0)
      this.addInfoElement(ShortTextElement, { model: this.model, title: "Age", values: this.model.age.toString() });
    this.addInfoElement(this.model.campaign.calendar === 0 /* Gregorian */ ? DateElement : FantasyCalendarElement, {
      model: this.model,
      title: "Date of Birth",
      values: this.model.dob,
      category: "RPG Manager Birth" /* Birth */,
      editableKey: "data.dob"
    });
    this.addInfoElement(this.model.campaign.calendar === 0 /* Gregorian */ ? DateElement : FantasyCalendarElement, {
      model: this.model,
      title: "Date of Death",
      values: this.model.death,
      category: "RPG Manager Death" /* Death */,
      editableKey: "data.death"
    });
    if (this.model.death != null) {
      let death = this.api.service(DateService).getReadableDate(this.model.death, this.model);
      if (this.model.age !== void 0)
        death += " at age " + this.model.age;
      this.addInfoElement(ShortTextElement, { model: this.model, title: "Death", values: death });
    }
  }
};

// src/components/character/templates/CharacterTemplate.ts
var CharacterTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      data: {
        synopsis: "",
        complete: false,
        dob: "",
        death: "",
        goals: "",
        pronoun: ""
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          pcs: {
            relationship: "unidirectional"
          },
          npcs: {
            relationship: "unidirectional"
          },
          factions: {},
          locations: {}
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 32 /* Character */,
      campaignSettings: 0 /* Agnostic */,
      id: this.api.service(IndexService).createUUID(),
      campaignId: this.campaignId,
      parentId: this.campaignId,
      positionInParent: 0
    };
  }
};

// src/components/character/views/CharacterRelationshipView.ts
var CharacterRelationshipView = class extends AbstractRelationshipView {
  getFieldValue(field, model) {
    var _a, _b;
    switch (field) {
      case 3 /* Age */:
        return (_b = (_a = model.age) == null ? void 0 : _a.toString()) != null ? _b : "";
    }
    return "";
  }
};

// src/components/character/modals/CharacterModalPart.ts
var CharacterModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "characterContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/character/CharacterComponent.ts
var CharacterComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [CharacterModalPart];
  }
  get model() {
    return CharacterModel;
  }
  get template() {
    return CharacterTemplate;
  }
  get type() {
    return 32 /* Character */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [CharacterHeaderView, 0 /* Header */],
      [CharacterRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/components/character/templates/NonPlayerCharacterTemplate.ts
var NonPlayerCharacterTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      data: {
        synopsis: "",
        death: "",
        dob: "",
        goals: "",
        pronoun: "",
        complete: false
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          subplots: {},
          pcs: {
            relationship: "unidirectional"
          },
          npcs: {
            relationship: "unidirectional"
          },
          factions: {},
          locations: {},
          events: {},
          clues: {}
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 64 /* NonPlayerCharacter */,
      campaignSettings: 0 /* Agnostic */,
      id: this.api.service(IndexService).createUUID(),
      campaignId: this.campaignId,
      parentId: this.campaignId,
      positionInParent: 0
    };
  }
};

// src/components/character/views/NonPlayerCharacterRelationshipView.ts
var NonPlayerCharacterRelationshipView = class extends CharacterRelationshipView {
};

// src/components/character/modals/NonPlayerCharacterModalPart.ts
var NonPlayerCharacterModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "characterContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/character/views/NonPlayerCharacterHeaderView.ts
var NonPlayerCharacterHeaderView = class extends AbstractHeaderView {
  render() {
    var _a, _b;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, {
      model: this.model,
      title: "Description",
      values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>',
      editableKey: "data.synopsis"
    });
    this.addInfoElement(LongTextElement, {
      model: this.model,
      title: "Goals",
      values: (_b = this.model.goals) != null ? _b : '<span class="missing">Goals Missing</span>',
      editableKey: "data.goals"
    });
    this.addInfoElement(PronounElement, {
      model: this.model,
      title: "Pronoun",
      values: this.model.pronoun,
      editableKey: "data.pronoun"
    });
    if (this.model.age !== void 0)
      this.addInfoElement(ShortTextElement, { model: this.model, title: "Age", values: this.model.age.toString() });
    this.addInfoElement(this.model.campaign.calendar === 0 /* Gregorian */ ? DateElement : FantasyCalendarElement, {
      model: this.model,
      title: "Date of Birth",
      values: this.model.dob,
      category: "RPG Manager Birth" /* Birth */,
      editableKey: "data.dob"
    });
    this.addInfoElement(this.model.campaign.calendar === 0 /* Gregorian */ ? DateElement : FantasyCalendarElement, {
      model: this.model,
      title: "Date of Death",
      values: this.model.death,
      category: "RPG Manager Death" /* Death */,
      editableKey: "data.death"
    });
    if (this.model.death != null) {
      let death = this.api.service(DateService).getReadableDate(this.model.death, this.model);
      if (this.model.age !== void 0)
        death += " at age " + this.model.age;
      this.addInfoElement(ShortTextElement, { model: this.model, title: "Death", values: death });
    }
  }
};

// src/components/character/NonPlayerCharacterComponent.ts
var NonPlayerCharacterComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [NonPlayerCharacterModalPart];
  }
  get model() {
    return CharacterModel;
  }
  get template() {
    return NonPlayerCharacterTemplate;
  }
  get type() {
    return 64 /* NonPlayerCharacter */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [NonPlayerCharacterHeaderView, 0 /* Header */],
      [NonPlayerCharacterRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/components/clue/abstracts/AbstractClueData.ts
var AbstractClueData = class extends AbstractModel {
  get found() {
    var _a, _b;
    if (((_a = this.metadata.data) == null ? void 0 : _a.found) === void 0 || this.metadata.data.found === false)
      return void 0;
    if (typeof this.metadata.data.found === "boolean")
      return void 0;
    return this.api.service(DateService).getDate((_b = this.metadata.data) == null ? void 0 : _b.found, "RPG Manager Clue Found" /* ClueFound */, this);
  }
};

// src/components/clue/models/ClueModel.ts
var ClueModel = class extends AbstractClueData {
};

// src/components/clue/views/ClueHeaderView.ts
var ClueHeaderView = class extends AbstractHeaderView {
  render() {
    var _a;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    this.addInfoElement(ShortTextElement, { model: this.model, title: "Found", values: this.model.found ? "Yes" : "No", editableKey: "data.synopsis" });
    this.addInfoElement(this.model.campaign.fantasyCalendar !== void 0 ? FantasyCalendarElement : DateElement, { model: this.model, title: "Date Found", values: this.model.found, category: "RPG Manager Clue Found" /* ClueFound */, editableKey: "data.found" });
  }
};

// src/components/clue/templates/ClueTemplate.ts
var ClueTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      data: {
        synopsis: "",
        complete: false,
        found: ""
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          subplots: {},
          pcs: {},
          npcs: {},
          locations: {},
          clues: {},
          events: {}
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 512 /* Clue */,
      campaignSettings: 0 /* Agnostic */,
      id: this.api.service(IndexService).createUUID(),
      campaignId: this.campaignId,
      parentId: this.campaignId,
      positionInParent: 0
    };
  }
};

// src/components/clue/views/ClueRelationshipView.ts
var ClueRelationshipView = class extends AbstractRelationshipView {
  getFieldValue(field, model) {
    switch (field) {
      case 5 /* Found */:
        return this.api.service(DateService).getReadableDate(model.found, model);
    }
    return "";
  }
};

// src/components/clue/modals/ClueModalPart.ts
var ClueModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "clueContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/clue/ClueComponent.ts
var ClueComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [ClueModalPart];
  }
  get model() {
    return ClueModel;
  }
  get template() {
    return ClueTemplate;
  }
  get type() {
    return 512 /* Clue */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [ClueHeaderView, 0 /* Header */],
      [ClueRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/components/event/abstracts/AbstractEventData.ts
var AbstractEventData = class extends AbstractModel {
  get date() {
    var _a;
    return this.api.service(DateService).getDate((_a = this.metadata.data) == null ? void 0 : _a.date, "RPG Manager Event" /* Event */, this);
  }
};

// src/components/event/models/EventModel.ts
var EventModel = class extends AbstractEventData {
};

// src/components/event/views/EventHeaderView.ts
var EventHeaderView = class extends AbstractHeaderView {
  render() {
    var _a;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    this.addInfoElement(this.model.campaign.calendar === 0 /* Gregorian */ ? DateElement : FantasyCalendarElement, { model: this.model, title: "Event Date", values: this.model.date, category: "RPG Manager Event" /* Event */, editableKey: "data.date" });
  }
};

// src/components/event/templates/EventTemplate.ts
var EventTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      data: {
        synopsis: "",
        complete: false,
        date: ""
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          subplots: {},
          pcs: {},
          npcs: {},
          clues: {},
          locations: {}
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 256 /* Event */,
      campaignSettings: 0 /* Agnostic */,
      id: this.api.service(IndexService).createUUID(),
      campaignId: this.campaignId,
      parentId: this.parentId,
      positionInParent: 0
    };
  }
};

// src/components/event/views/EventRelationshipView.ts
var EventRelationshipView = class extends AbstractRelationshipView {
  getFieldValue(field, model) {
    switch (field) {
      case 6 /* Date */:
        return this.api.service(DateService).getReadableDate(model.date, model);
    }
    return "";
  }
};

// src/components/event/modals/EventModalPart.ts
var EventModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "eventContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/event/EventComponent.ts
var EventComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [EventModalPart];
  }
  get model() {
    return EventModel;
  }
  get template() {
    return EventTemplate;
  }
  get type() {
    return 256 /* Event */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [EventHeaderView, 0 /* Header */],
      [EventRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/components/faction/abstracts/AbstractFactionData.ts
var AbstractFactionData = class extends AbstractModel {
};

// src/components/faction/models/FactionModel.ts
var FactionModel = class extends AbstractFactionData {
};

// src/components/faction/views/FactionHeaderView.ts
var FactionHeaderView = class extends AbstractHeaderView {
  render() {
    var _a;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
  }
};

// src/components/faction/templates/FactionTemplate.ts
var FactionTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      data: {
        synopsis: "",
        complete: false
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          pcs: {},
          npcs: {},
          locations: {},
          subplots: {}
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 1024 /* Faction */,
      campaignSettings: 0 /* Agnostic */,
      id: this.api.service(IndexService).createUUID(),
      campaignId: this.campaignId,
      parentId: this.parentId,
      positionInParent: 0
    };
  }
};

// src/components/faction/views/FactionRelationshipView.ts
var FactionRelationshipView = class extends AbstractRelationshipView {
  getFieldValue(field, model) {
    return "";
  }
};

// src/components/faction/modals/FactionModalPart.ts
var FactionModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "factionContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/faction/FactionComponent.ts
var FactionComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [FactionModalPart];
  }
  get model() {
    return FactionModel;
  }
  get template() {
    return FactionTemplate;
  }
  get type() {
    return 1024 /* Faction */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [FactionHeaderView, 0 /* Header */],
      [FactionRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/components/location/abstracts/AbstractLocationData.ts
var AbstractLocationData = class extends AbstractModel {
  get address() {
    var _a;
    return (_a = this.metadata.data) == null ? void 0 : _a.address;
  }
};

// src/components/location/models/LocationModel.ts
var LocationModel = class extends AbstractLocationData {
};

// src/components/location/views/LocationHeaderView.ts
var LocationHeaderView = class extends AbstractHeaderView {
  render() {
    var _a, _b;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    this.addInfoElement(ShortTextElement, { model: this.model, title: "Address", values: (_b = this.model.address) != null ? _b : "", editableKey: "data.address" });
  }
};

// src/components/location/templates/LocationTemplate.ts
var LocationTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      data: {
        synopsis: "",
        complete: false,
        address: ""
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          pcs: {},
          npcs: {},
          events: {},
          clues: {},
          locations: [
            {
              relationship: "parent",
              title: "Inside"
            },
            {
              relationship: "child",
              title: "Contains"
            },
            {
              relationship: "",
              title: "Related Locations"
            }
          ]
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 128 /* Location */,
      campaignSettings: 0 /* Agnostic */,
      id: this.api.service(IndexService).createUUID(),
      campaignId: this.campaignId,
      parentId: this.campaignId,
      positionInParent: 0
    };
  }
};

// src/components/location/views/LocationRelationshipView.ts
var LocationRelationshipView = class extends AbstractRelationshipView {
  getFieldValue(field, model) {
    return "";
  }
};

// src/components/location/modals/LocationModalPart.ts
var LocationModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "locationContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/location/LocationComponent.ts
var LocationComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [LocationModalPart];
  }
  get model() {
    return LocationModel;
  }
  get template() {
    return LocationTemplate;
  }
  get type() {
    return 128 /* Location */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [LocationHeaderView, 0 /* Header */],
      [LocationRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/components/music/abstracts/AbstractMusicData.ts
var AbstractMusicData = class extends AbstractModel {
  get url() {
    var _a;
    return (_a = this.metadata.data) == null ? void 0 : _a.url;
  }
};

// src/fetchers/abstracts/AbstractFetcher.ts
var AbstractFetcher = class {
  constructor(api) {
    this.api = api;
  }
};

// src/fetchers/youTubeFetcher/YouTubeImageFetcher.ts
var YouTubeImageFetcher = class extends AbstractFetcher {
  constructor() {
    super(...arguments);
    this.fetchUrl = "https://www.googleapis.com/youtube/v3/";
  }
  playlistEndPoint(playlistId) {
    return this.fetchUrl + "playlistItems?key=" + this.api.settings.YouTubeKey + "&part=snippet&playlistId=" + playlistId;
  }
  songEndPoint(songId) {
    return this.fetchUrl + "videos?key=" + this.api.settings.YouTubeKey + "&part=snippet&indexService=" + songId;
  }
  fetchImage(url) {
    return __async(this, null, function* () {
      var _a, _b, _c, _d;
      const youTubeApiKey = this.api.settings.YouTubeKey;
      if (youTubeApiKey === "" || youTubeApiKey == null)
        return void 0;
      let apiResponse;
      const playlistIdentifier = "playlist?list=";
      const songIdentifier = "watch?v=";
      const alternativeSongIdentifier = "youtu.be/";
      let playlistId;
      let songId;
      try {
        if (url.indexOf(playlistIdentifier) !== -1) {
          playlistId = url.substring(url.indexOf(playlistIdentifier) + playlistIdentifier.length);
        } else if (url.indexOf(songIdentifier) !== -1) {
          songId = url.substring(url.indexOf(songIdentifier) + songIdentifier.length);
        } else if (url.indexOf(alternativeSongIdentifier) !== -1) {
          songId = url.substring(url.indexOf(alternativeSongIdentifier) + alternativeSongIdentifier.length);
        }
        if (playlistId !== void 0) {
          apiResponse = yield fetch(this.playlistEndPoint(playlistId));
        } else if (songId !== void 0) {
          apiResponse = yield fetch(this.songEndPoint(songId));
        }
        if (apiResponse === void 0)
          return void 0;
        const jsonData = yield apiResponse.json();
        if (jsonData === void 0)
          return void 0;
        return (_d = (_c = (_b = (_a = jsonData.items[0]) == null ? void 0 : _a.snippet) == null ? void 0 : _b.thumbnails) == null ? void 0 : _c.high) == null ? void 0 : _d.url;
      } catch (e) {
        return void 0;
      }
    });
  }
};

// src/components/music/models/MusicModel.ts
var MusicModel = class extends AbstractMusicData {
  get image() {
    if (super.images.length > 0)
      return super.images[0].src;
    if (this.url == void 0)
      return void 0;
    if (this._dynamicImage === void 0) {
      this._fetchImage().then((image) => {
        this._dynamicImage = image;
      });
      return void 0;
    }
    return this._dynamicImage != null ? this._dynamicImage : void 0;
  }
  getThumbnail() {
    return __async(this, null, function* () {
      if (this._dynamicImage != null)
        return this._dynamicImage;
      if (this.url === void 0)
        return void 0;
      this._dynamicImage = yield this._fetchImage();
      return this._dynamicImage != null ? this._dynamicImage : void 0;
    });
  }
  _fetchImage() {
    return __async(this, null, function* () {
      var _a;
      let response = null;
      if (this.url == void 0)
        return null;
      if (this.url.indexOf("youtube.com") !== -1 || this.url.indexOf("youtu.be") !== -1) {
        response = (_a = yield this.api.fetcher(YouTubeImageFetcher).fetchImage(this.url)) != null ? _a : null;
      }
      return response;
    });
  }
};

// src/components/music/views/MusicHeaderView.ts
var MusicHeaderView = class extends AbstractHeaderView {
  render() {
    var _a, _b;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    this.addInfoElement(ShortTextElement, { model: this.model, title: "Url", values: (_b = this.model.url) != null ? _b : "", editableKey: "data.url" });
  }
};

// src/components/music/templates/MusicTemplate.ts
var MusicTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      data: {
        synopsis: "",
        complete: false,
        url: ""
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          musics: [
            {
              relationship: "parent",
              title: "Part of playlists"
            },
            {
              relationship: "child",
              title: "Songs"
            }
          ]
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 2048 /* Music */,
      campaignSettings: 0 /* Agnostic */,
      id: this.api.service(IndexService).createUUID(),
      campaignId: this.campaignId,
      parentId: this.campaignId,
      positionInParent: 0
    };
  }
};

// src/components/music/views/MusicRelationshipView.ts
var MusicRelationshipView = class extends AbstractRelationshipView {
  getFieldValue(field, model) {
    var _a;
    switch (field) {
      case 7 /* Url */:
        return (_a = model.url) != null ? _a : "";
    }
    return "";
  }
};

// src/components/music/modals/MusicModalPart.ts
var MusicModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "musicContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/music/MusicComponent.ts
var MusicComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [MusicModalPart];
  }
  get model() {
    return MusicModel;
  }
  get template() {
    return MusicTemplate;
  }
  get type() {
    return 2048 /* Music */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [MusicHeaderView, 0 /* Header */],
      [MusicRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/services/plotsService/views/elements/StoryCircleStageElement.ts
var StoryCircleStageElement = class extends AbstractElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const storyCircleStageSelectorEl = contentEl.createEl("select");
    storyCircleStageSelectorEl.createEl("option", {
      text: "",
      value: ""
    }).selected = true;
    Object.keys(StoryCircleStage).filter((v) => isNaN(Number(v))).forEach((type, index) => {
      const storyCircleStageOptionEl = storyCircleStageSelectorEl.createEl("option", {
        text: type,
        value: type
      });
      if (data.values !== void 0 && data.values === this.api.service(PlotService).getStoryCircleStage(type))
        storyCircleStageOptionEl.selected = true;
    });
    storyCircleStageSelectorEl.addEventListener("change", (e) => {
      if (data.editableKey !== void 0)
        this.api.service(CodeblockService).addOrUpdate(data.editableKey, storyCircleStageSelectorEl.value.toLowerCase());
    });
  }
};

// src/components/scene/modals/SceneTypeDescriptionModal.ts
var import_obsidian36 = require("obsidian");
var sceneTypeDescription2 = [
  {
    title: "Action",
    description: "*The player characters DO something*\nAn **Action** scene type is a scene in which the player characters need to **DO** something.From building, to searching or studying, this type of scene requires the player characters to be active.",
    isActive: true
  },
  {
    title: "Combat",
    description: "*The player characters fight*\nA **Combat** scene type is a scene in which the player characters engage in a fight.",
    isActive: true
  },
  {
    title: "Encounter",
    description: "*The player characters meet someone*\nAn **Encounter** scene type is a scene in which the player characters have a social encounter with one or more NPCs. These type of scenes are usually for social gatherings, to receive information, but they do not include the player characters having to obtain something: for that there is the **Social Combat** type od scenes",
    isActive: false
  },
  {
    title: "Exposition",
    description: "*The storyteller introduce a change of scenery*\nAn **Exposition** scene type is a storyteller-lead scene in which the storyteller present something to the player characters. These type of scenes are generally short in duration and are very useful to introduce a change.",
    isActive: false
  },
  {
    title: "Investigation",
    description: "*The player characters obtain information from the surrounding environment*\nAn **Investigation** scene type is a scene in which the player characters must obtain some information from the surrounding environment. These type of scenes are similar to the **Social Combat**, but do not include NPCs from which to collect the information, hence are less social and more active",
    isActive: true
  },
  {
    title: "Planning",
    description: "*The player characters decide what to do next*\nA **Planning** scene type is a player character-lead scene in which the player characters plan how to move and take a decision. Often, these type of scenes are focussed on decisions alone.",
    isActive: false
  },
  {
    title: "Preparation",
    description: "*The player characters prepare what they need to do something*\nA **Praparation** scene type is a player character-lead scene in which the player characters do something after having gone through a **Planning**, as the **Preparation** scenes should not include decisions.The difference with an **Action** scene is that thhe **Preparation** scenes are mainly driven by the player characters, while the **Action** ones include external involvement.",
    isActive: false
  },
  {
    title: "Recap",
    description: "*The player characters discuss amongst themselves*\nA **Recap** scene type is a player character-lead scene in which the player characters recap something they have done. THe scene is similar to the **Planning**, but does not involve any type of decision process.",
    isActive: false
  },
  {
    title: "Social Combat",
    description: "*The player characters obtain information from an NPC*\nA **Social Combat** scene type is a scene in which the player characters must obtain something from an NPC through a discussion. The goal is to `win the argument` adn it is normally performed through persuasion, intimidation or fast talk.",
    isActive: true
  }
];
var SceneTypeDescriptionModal = class extends AbstractModal {
  onOpen() {
    super.onOpen();
    const { contentEl } = this;
    contentEl.empty();
    contentEl.addClass("rpgm-modal");
    this._sceneTypeDescriptionsEl = contentEl.createDiv({ cls: "rpgm-modal-scene-descriptions" });
    this._sceneTypeDescriptionsEl.createEl("h1", { text: "SceneModel Types" });
    sceneTypeDescription2.forEach((sceneTypeInformation) => {
      this._displaySceneTypeInformation(sceneTypeInformation);
    });
  }
  _displaySceneTypeInformation(sceneTypeInformation) {
    const descriptionContainerEl = this._sceneTypeDescriptionsEl.createDiv("description-container");
    descriptionContainerEl.createEl("h2", { text: sceneTypeInformation.title });
    const descriptionEl = descriptionContainerEl.createDiv();
    descriptionContainerEl.createSpan({ text: "This is " + (sceneTypeInformation.isActive ? "" : "NOT ") + 'an "active" type of scene' });
    import_obsidian36.MarkdownRenderer.renderMarkdown(sceneTypeInformation.description, descriptionEl, "", null);
  }
  onClose() {
    super.onClose();
  }
};

// src/services/analyserService/views/elements/SceneTypeElement.ts
var SceneTypeElement = class extends AbstractElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const sceneTypeSelectorEl = contentEl.createEl("select");
    contentEl.createSpan({ text: "?" }).addEventListener("click", () => {
      new SceneTypeDescriptionModal(this.api).open();
    });
    sceneTypeSelectorEl.createEl("option", {
      text: "",
      value: ""
    }).selected = true;
    Object.keys(SceneType).filter((v) => isNaN(Number(v))).forEach((type, index) => {
      var _a;
      const sceneTypeOptionEl = sceneTypeSelectorEl.createEl("option", {
        text: (_a = sceneTypeDescription.get(SceneType[type])) != null ? _a : type,
        value: type
      });
      if (data.values !== void 0 && data.values === SceneType[type])
        sceneTypeOptionEl.selected = true;
    });
    sceneTypeSelectorEl.addEventListener("change", (e) => {
      if (data.editableKey !== void 0)
        this.api.service(CodeblockService).addOrUpdate(data.editableKey, sceneTypeSelectorEl.value);
    });
  }
};

// src/managers/viewsManager/elements/CheckboxElement.ts
var CheckboxElement = class extends AbstractElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const checkboxEl = contentEl.createEl("input");
    checkboxEl.type = "checkbox";
    checkboxEl.checked = data.values;
    checkboxEl.addEventListener("change", () => {
      if (data.editableKey)
        this.api.service(CodeblockService).addOrUpdate(data.editableKey, checkboxEl.checked);
    });
  }
};

// src/services/runningTimeService/views/elements/RunElement.ts
var RunElement = class extends AbstractElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const startStopEl = contentEl.createEl("a", { href: "#", text: data.values.isRunning ? "stop" : "start" });
    startStopEl.addEventListener("click", (e) => {
      e.preventDefault();
      if (data.values.isRunning) {
        this.api.service(RunningTimeService).stopScene(data.values.scene);
      } else {
        this.api.service(RunningTimeService).startScene(data.values.scene);
      }
    });
  }
};

// src/services/runningTimeService/views/elements/RuntimeDurationElement.ts
var RuntimeDurationElement = class extends AbstractElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    this._runningTime = contentEl.createSpan();
    this._runningTime.textContent = this.api.service(DateService).formatMinutesSeconds(data.values.runtime);
    if (data.values.scene.isCurrentlyRunning) {
      this._model = data.values.scene;
      setInterval(() => {
        this._runningTime.textContent = this._countOngoingDuration();
      }, 1e3);
    }
  }
  _countOngoingDuration() {
    var _a;
    let duration2 = (_a = this._model.currentDuration) != null ? _a : 0;
    if (this._model.lastStart !== void 0 && this._model.lastStart !== 0)
      duration2 += Math.floor(Date.now() / 1e3) - this._model.lastStart;
    return this.api.service(DateService).formatMinutesSeconds(duration2);
  }
};

// src/components/scene/views/SceneHeaderView.ts
var SceneHeaderView = class extends AbstractHeaderView {
  render() {
    var _a, _b, _c, _d;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    const act = this.api.database.readById(this.model.index.parentId);
    const acts = this.api.database.readChildren(4 /* Act */, act.index.parentId);
    this.addInfoElement(ParentSwitcherSelectorElement, { model: this.model, title: "Part of Act", values: { index: this.model.index, list: acts } });
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    this.addInfoElement(LongTextElement, { model: this.model, title: "Trigger", values: (_b = this.model.trigger) != null ? _b : '<span class="missing">Trigger Missing</span>', editableKey: "data.trigger" });
    this.addInfoElement(LongTextElement, { model: this.model, title: "Action", values: (_c = this.model.action) != null ? _c : '<span class="missing">Action Missing</span>', editableKey: "data.action" });
    if (this.model.campaign.calendar === 0 /* Gregorian */)
      this.addInfoElement(DateElement, { model: this.model, title: "Scene Date", values: this.model.date, editableKey: "data.date" });
    else
      this.addInfoElement(FantasyCalendarElement, { model: this.model, title: "Scene Date", values: this.model.date, category: "RPG Manager Scene" /* Scene */, editableKey: "data.date" });
    const sessions = this.api.database.read((session) => session.index.type === 16 /* Session */ && session.index.campaignId === this.model.index.campaignId);
    this.addInfoElement(ModelSelectorElement, { model: this.model, title: "Session", values: { index: (_d = this.model.session) == null ? void 0 : _d.index, list: sessions }, editableKey: "data.sessionId" });
    if (this.api.settings.usePlotStructures)
      this.addInfoElement(StoryCircleStageElement, { model: this.model, title: "Story Circle Stage", values: this.model.storyCircleStage, editableKey: "data.storyCircleStage" });
    if (this.api.settings.useSceneAnalyser) {
      this.addInfoElement(SceneTypeElement, {
        model: this.model,
        title: "Scene Type",
        values: this.model.sceneType,
        editableKey: "data.sceneType"
      });
      this.addInfoElement(CheckboxElement, {
        model: this.model,
        title: "External Actions?",
        values: this.model.isExciting,
        editableKey: "data.isActedUpon"
      });
      this.addInfoElement(RunElement, {
        model: this.model,
        title: "SceneRun",
        values: { isRunning: this.model.isCurrentlyRunning, scene: this.model }
      });
      if (this.model.currentDuration > 0 || this.model.isCurrentlyRunning)
        this.addInfoElement(RuntimeDurationElement, {
          model: this.model,
          title: "Duration",
          values: { isRunning: this.model.isCurrentlyRunning, runtime: this.model.currentDuration, scene: this.model }
        });
      let abtStage = void 0;
      switch (this.model.storyCircleStage) {
        case 0 /* You */:
        case 1 /* Need */:
          abtStage = 0 /* Need */;
          break;
        case 2 /* Go */:
        case 3 /* Search */:
          abtStage = 1 /* And */;
          break;
        case 4 /* Find */:
        case 5 /* Take */:
          abtStage = 2 /* But */;
          break;
        case 6 /* Return */:
        case 7 /* Change */:
          abtStage = 3 /* Therefore */;
          break;
      }
      if (abtStage !== void 0) {
        const analyser = this.api.service(AnalyserService).createScene(this.model, abtStage);
        this.addAnalyser(analyser, 2 /* Scene */);
      }
    }
  }
};

// src/components/scene/templates/SceneTemplate.ts
var SceneTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    var _a, _b, _c;
    const synopsis = "";
    let sceneType = "";
    let isActedUpon = false;
    let storyCircleStage = "";
    if (this.additionalInformation !== void 0) {
      if (((_a = this.data) == null ? void 0 : _a.sceneType) !== void 0)
        sceneType = this.data.sceneType;
      if (((_b = this.data) == null ? void 0 : _b.isActedUpon) !== void 0)
        isActedUpon = this.data.isActedUpon;
      if (((_c = this.data) == null ? void 0 : _c.storyCircleStage) !== void 0)
        storyCircleStage = this.data.storyCircleStage;
    }
    const metadata = {
      data: {
        synopsis,
        complete: false,
        sessionId: 0,
        action: "",
        trigger: "",
        date: "",
        sceneType,
        isActedUpon,
        duration: 0,
        durations: [],
        storyCircleStage
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateLastCodeBlock() {
    const metadata = {
      models: {
        lists: {
          subplots: {
            relationship: "unidirectional"
          },
          musics: {
            relationship: "unidirectional"
          },
          pcs: {
            relationship: "unidirectional"
          },
          npcs: {
            relationship: "unidirectional"
          },
          factions: {
            relationship: "unidirectional"
          },
          clues: {
            relationship: "unidirectional"
          },
          locations: {
            relationship: "unidirectional"
          },
          events: {
            relationship: "unidirectional"
          }
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    let positionInParent = 1;
    if (this.positionInParent == void 0) {
      const previousScenes = this.api.database.read((scene) => scene.index.type === 8 /* Scene */ && scene.index.campaignId === this.campaignId && scene.index.parentId === this.parentId).sort(this.api.service(SorterService).create([
        new SorterComparisonElement((scene) => scene.index.positionInParent, 1 /* Descending */)
      ]));
      positionInParent = previousScenes.length === 0 ? 1 : previousScenes[0].index.positionInParent + 1;
    } else {
      positionInParent = this.positionInParent;
    }
    return {
      type: 8 /* Scene */,
      campaignSettings: 0 /* Agnostic */,
      id: this.id,
      campaignId: this.campaignId,
      parentId: this.parentId,
      positionInParent
    };
  }
};

// src/components/scene/views/SceneRelationshipView.ts
var SceneRelationshipView = class extends AbstractRelationshipView {
  constructor() {
    super(...arguments);
    this.canBeOrdered = true;
  }
  getFieldValue(field, model) {
    var _a, _b, _c, _d;
    switch (field) {
      case 11 /* Duration */:
        return model.duration;
        break;
      case 12 /* SceneType */:
        if (!this.api.settings.useSceneAnalyser)
          return "";
        return (_b = (_a = model.sceneType) == null ? void 0 : _a.toString()) != null ? _b : "";
      case 13 /* SceneExciting */:
        if (!this.api.settings.useSceneAnalyser)
          return "";
        return String(model.isExciting);
      case 8 /* StoryCircleIndicator */:
        if (!this.api.settings.usePlotStructures)
          return "";
        return (_d = (_c = model.storyCircleStage) == null ? void 0 : _c.toString()) != null ? _d : "";
      case 6 /* Date */:
        return this.api.service(DateService).getReadableDate(model.date, model);
    }
    return "";
  }
};

// src/components/scene/modals/SceneModalPart.ts
var SceneModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "sceneContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/scene/SceneComponent.ts
var SceneComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [SceneModalPart];
  }
  get model() {
    return SceneModel;
  }
  get template() {
    return SceneTemplate;
  }
  get type() {
    return 8 /* Scene */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [SceneHeaderView, 0 /* Header */],
      [SceneRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/services/dateService/views/elements/TimeElement.ts
var TimeElement = class extends AbstractElement {
  render(data, containerEl) {
    const infoEl = containerEl.createDiv({ cls: "rpg-manager-header-container-info-data-container rpg-manager-header-container-info-data-container-short clearfix" });
    this.createTitle(data.model, data.title, infoEl);
    const options = {
      allowInput: true,
      enableTime: true,
      noCalendar: true,
      minuteIncrement: 15,
      time_24hr: true,
      onChange: (selectedDate, dateStr, instance) => {
        const [hours, minutes] = dateStr.split(":");
        const duration2 = +hours * 60 + +minutes;
        if (data.editableKey !== void 0)
          this.api.service(CodeblockService).addOrUpdate(data.editableKey, duration2);
      }
    };
    if (data.values !== void 0) {
      const hours = Math.floor(data.values / 60);
      const minutes = data.values % 60;
      options.defaultDate = hours.toString() + ":" + (minutes < 10 ? "0" : "") + minutes.toString();
    }
    const contentEl = infoEl.createDiv({ cls: "rpg-manager-header-container-info-data-container-content clearfix" });
    const flatpickrEl = contentEl.createEl("input", { cls: "flatpickr", type: "text" });
    flatpickrEl.readOnly = true;
    esm_default(flatpickrEl, options);
  }
};

// src/components/session/views/SessionHeaderView.ts
var SessionHeaderView = class extends AbstractHeaderView {
  render() {
    var _a;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    this.addInfoElement(DateElement, { model: this.model, title: "Session Date", values: this.model.irl, editableKey: "data.irl" });
    if (this.api.settings.usePlotStructures)
      this.addInfoElement(AbtStageElement, { model: this.model, title: "ABT Stage", values: this.model.abtStage, editableKey: "data.abtStage" });
    if (this.api.settings.useSceneAnalyser) {
      this.addInfoElement(TimeElement, {
        model: this.model,
        title: "Target Duration",
        values: this.model.targetDuration,
        editableKey: "data.targetDuration"
      });
      const analyser = this.api.service(AnalyserService).createSession(this.model, this.model.abtStage);
      if (analyser.scenesCount > 0) {
        this.addAnalyser(analyser, 1 /* Visual */);
        this.addAnalyser(analyser, 0 /* Extended */);
      }
    }
  }
};

// src/components/session/templates/SessionTemplate.ts
var SessionTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      data: {
        synopsis: "",
        complete: false,
        irl: void 0,
        abtStage: void 0
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          scenes: {
            relationship: "hierarchy"
          }
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateLastCodeBlock() {
    const metadata = {
      models: {
        lists: {
          subplots: {
            relationship: "hierarchy"
          },
          musics: {
            relationship: "hierarchy"
          },
          pcs: {
            relationship: "hierarchy"
          },
          npcs: {
            relationship: "hierarchy"
          },
          factions: {
            relationship: "hierarchy"
          },
          clues: {
            relationship: "hierarchy"
          },
          locations: {
            relationship: "hierarchy"
          },
          events: {
            relationship: "hierarchy"
          }
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    let positionInParent = 1;
    if (this.positionInParent == void 0) {
      const previousSessions = this.api.database.read((session) => session.index.type === 16 /* Session */ && session.index.campaignId === this.campaignId).sort(this.api.service(SorterService).create([
        new SorterComparisonElement((session) => session.index.positionInParent, 1 /* Descending */)
      ]));
      positionInParent = previousSessions.length === 0 ? 1 : previousSessions[0].index.positionInParent + 1;
    } else {
      positionInParent = this.positionInParent;
    }
    return {
      type: 16 /* Session */,
      campaignSettings: 0 /* Agnostic */,
      id: this.id,
      campaignId: this.campaignId,
      parentId: this.campaignId,
      positionInParent
    };
  }
};

// src/components/session/views/SessionRelationshipView.ts
var SessionRelationshipView = class extends AbstractRelationshipView {
  constructor() {
    super(...arguments);
    this.canBeOrdered = true;
  }
  getFieldValue(field, model) {
    if (field === 6 /* Date */)
      return this.api.service(DateService).getReadableDate(model.irl, model);
    return "";
  }
};

// src/components/session/modals/SessionModalPart.ts
var SessionModalPart = class extends AbstractModalPart {
  constructor(api, modal) {
    super(api, modal);
  }
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "sessionContainer" });
      this.addAdditionalElements();
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    if (this.modal.sessionId === void 0)
      this.modal.sessionId = this.api.service(IndexService).createUUID();
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/session/SessionComponent.ts
var SessionComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [SessionModalPart];
  }
  get model() {
    return SessionModel;
  }
  get template() {
    return SessionTemplate;
  }
  get type() {
    return 16 /* Session */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [SessionHeaderView, 0 /* Header */],
      [SessionRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/components/subplot/abstracts/AbstractSubplotData.ts
var AbstractSubplotData = class extends Plots {
};

// src/components/subplot/models/SubplotModel.ts
var SubplotModel = class extends AbstractSubplotData {
  constructor() {
    super(...arguments);
    this.stage = 1 /* Subplot */;
  }
};

// src/components/subplot/views/SubplotHeaderView.ts
var SubplotHeaderView = class extends AbstractHeaderView {
  render() {
    var _a;
    this.addBreadcrumb();
    this.addTitle();
    this.addComponentOptions();
    this.addGallery();
    this.addInfoElement(LongTextElement, { model: this.model, title: "Description", values: (_a = this.model.synopsis) != null ? _a : '<span class="missing">Synopsis Missing</span>', editableKey: "data.synopsis" });
    if (this.api.settings.usePlotStructures)
      this.addPlot();
  }
};

// src/components/subplot/templates/SubplotTemplate.ts
var SubplotTemplate = class extends AbstractComponentTemplate {
  generateDataCodeBlock() {
    const metadata = {
      plot: {
        abt: {
          need: "",
          and: "",
          but: "",
          therefore: ""
        },
        storycircle: {
          you: "",
          need: "",
          go: "",
          search: "",
          find: "",
          take: "",
          return: "",
          change: ""
        }
      },
      data: {
        synopsis: "",
        complete: false
      }
    };
    return this.generateRpgManagerDataCodeBlock(metadata);
  }
  generateInitialCodeBlock() {
    const metadata = {
      models: {
        header: true,
        lists: {
          events: {},
          clues: {},
          factions: {},
          npcs: {},
          locations: {}
        }
      }
    };
    return this.generateRpgManagerCodeBlock(metadata);
  }
  generateID() {
    return {
      type: 4096 /* Subplot */,
      campaignSettings: 0 /* Agnostic */,
      id: this.api.service(IndexService).createUUID(),
      campaignId: this.campaignId,
      parentId: this.campaignId,
      positionInParent: 0
    };
  }
};

// src/components/subplot/views/SubplotRelationshipView.ts
var SubplotRelationshipView = class extends AbstractRelationshipView {
  getFieldValue(field, model) {
    return "";
  }
};

// src/components/subplot/modals/SubplotModalPart.ts
var SubplotModalPart = class extends AbstractModalPart {
  addElement(contentEl) {
    return __async(this, null, function* () {
      contentEl.createDiv({ cls: "subplotContainer" });
      this.modal.saver = this;
      this.modal.enableButton();
    });
  }
  loadChild(containerEl) {
    return __async(this, null, function* () {
    });
  }
  validate() {
    return true;
  }
  addAdditionalElements() {
    return __async(this, null, function* () {
    });
  }
};

// src/components/subplot/SubplotComponent.ts
var SubplotComponent = class {
  get campaignSettings() {
    return 0 /* Agnostic */;
  }
  get modalParts() {
    return [SubplotModalPart];
  }
  get model() {
    return SubplotModel;
  }
  get template() {
    return SubplotTemplate;
  }
  get type() {
    return 4096 /* Subplot */;
  }
  get views() {
    return /* @__PURE__ */ new Map([
      [SubplotHeaderView, 0 /* Header */],
      [SubplotRelationshipView, 1 /* Relationships */]
    ]);
  }
};

// src/services/allComponentManipulatorService/AllComponentManipulatorService.ts
var AllComponentManipulatorService = class extends AbstractService {
  updateImagePath(oldPath, newPath) {
    return __async(this, null, function* () {
      return this._updatePath(oldPath, newPath);
    });
  }
  updateRelationshipPath(oldPath, newPath) {
    return __async(this, null, function* () {
      return this._updatePath(oldPath, newPath, this._updateRelationship.bind(this));
    });
  }
  _updatePath(oldPath, newPath, callbackFunction) {
    return __async(this, null, function* () {
      const allFiles = this.api.app.vault.getMarkdownFiles();
      allFiles.forEach((file) => {
        this.api.service(FileManipulatorService).read(file).then((fileManipulator) => {
          fileManipulator.read().then((isReady) => {
            if (!isReady)
              return;
            if (!fileManipulator.content.contains("path:"))
              return;
            if (!fileManipulator.content.contains(oldPath))
              return;
            const updatedFileContent = fileManipulator.content.replaceAll(oldPath, newPath);
            fileManipulator.maybeWrite(updatedFileContent).then(() => {
              if (callbackFunction !== void 0)
                callbackFunction(file);
            });
          });
        });
      });
    });
  }
  _updateRelationship(file) {
    return __async(this, null, function* () {
      const component = this.api.database.readByPath(file.path);
      if (component === void 0)
        return;
      component.readMetadata().then(() => {
        component.addReverseRelationships();
      });
    });
  }
};

// src/fetchers/releaseNoteFetcher/ReleaseNoteFetcher.ts
var ReleaseNoteFetcher = class extends AbstractFetcher {
  constructor() {
    super(...arguments);
    this.fetchUrl = "https://raw.githubusercontent.com/carlonicora/obsidian-rpg-manager/master/ChangeLog.md";
  }
  fetchMarkdown() {
    return __async(this, null, function* () {
      const apiResponse = yield fetch(this.fetchUrl);
      if (apiResponse === void 0)
        return void 0;
      const response = yield apiResponse.text();
      return response;
    });
  }
};

// src/services/diceService/DiceResult.ts
var DiceResult = class {
  constructor(type, result) {
    if (type != null)
      this.type = type;
    if (result != null) {
      this.result = result;
      switch (this.result) {
        case 1:
          this.rollResult = 2 /* CriticalFailure */;
          break;
        case this.type:
          this.rollResult = 1 /* CriticalSuccess */;
          break;
        default:
          this.rollResult = 0 /* Standard */;
          break;
      }
    }
  }
};

// src/services/diceService/DiceService.ts
var DiceService = class {
  roll(numberOfDices, diceType) {
    const response = [];
    for (let diceCount = 0; diceCount < numberOfDices; diceCount++) {
      response.push(new DiceResult(diceType, this._genrateRandomNumber(diceType)));
    }
    return response;
  }
  rollSingleDice(diceType) {
    return this.roll(1, diceType)[0];
  }
  _genrateRandomNumber(max) {
    Math.ceil(1);
    Math.floor(max);
    return Math.floor(Math.random() * max) + 1;
  }
};

// src/services/graphViewService/GraphViewService.ts
var GraphViewService = class extends AbstractService {
  constructor(api) {
    super(api);
    this.api = api;
    this.registerEvent(this.api.app.metadataCache.on("resolve", (file) => this._onSave(file)));
  }
  _onSave(file) {
    return __async(this, null, function* () {
      const element = this.api.database.readByPath(file.path);
      if (element === void 0)
        return;
      const domain = yield this.api.service(CodeblockService).read(file, "RpgManagerID");
      if (domain === void 0)
        return;
      const content = domain.originalFileContent.split("\n");
      const newRelationships = [];
      const relationshipsToRemove = [];
      const additionalContent = [];
      if (domain.codeblockEnd.line + 1 < content.length) {
        for (let index = domain.codeblockEnd.line + 1; index < content.length; index++) {
          if (content[index].startsWith("[[") && content[index].endsWith("|]]"))
            relationshipsToRemove.push(content[index].substring(2, content[index].length - 3).toLowerCase());
          else
            additionalContent.push(content[index]);
        }
      }
      const existingRelationshipCount = relationshipsToRemove.length;
      for (let index = 0; index < element.getRelationships().relationships.length; index++) {
        const relationship = element.getRelationships().relationships[index];
        if (relationship.component !== void 0 && !relationship.isInContent && !relationship.isAlsoInContent && (relationship.type === 2 /* Bidirectional */ || relationship.type === 4 /* Unidirectional */ || relationship.type === 16 /* Child */)) {
          this._updateAvailableRelationships(relationshipsToRemove, newRelationships, relationship.component.file.basename);
        }
      }
      if (relationshipsToRemove.length !== 0 || newRelationships.length !== existingRelationshipCount) {
        let newHiddenLinkContent = "";
        for (let index = 0; index < newRelationships.length; index++) {
          newHiddenLinkContent += newRelationships[index] + "\n";
        }
        if (newHiddenLinkContent !== "")
          newHiddenLinkContent = newHiddenLinkContent.substring(0, newHiddenLinkContent.length - 1);
        let newFileContent = "";
        let isInRpgManagerID = false;
        for (let index = 0; index < content.length; index++) {
          newFileContent += content[index] + "\n";
          if (!isInRpgManagerID && content[index] === "```RpgManagerID")
            isInRpgManagerID = true;
          else if (isInRpgManagerID && content[index] === "```")
            break;
        }
        newFileContent += newHiddenLinkContent;
        if (additionalContent.length > 0)
          newFileContent += "\n" + additionalContent.join("\n");
        if (newFileContent !== domain.originalFileContent)
          this.api.app.vault.modify(file, newFileContent);
      }
    });
  }
  _updateAvailableRelationships(existingRelationships, newRelationships, relationship) {
    for (let index = 0; index < existingRelationships.length; index++) {
      if (existingRelationships[index] === relationship.toLowerCase()) {
        existingRelationships.splice(index, 1);
        break;
      }
    }
    newRelationships.push("[[" + relationship + "|]]");
  }
};

// src/api/Bootstrapper.ts
var Bootstrapper = class {
  static initialise(api) {
    this._addComponents(api);
    this._addServices(api);
    this._addFetchers(api);
  }
  static _addComponents(api) {
    api.components.register(ActComponent);
    api.components.register(AdventureComponent);
    api.components.register(CampaignComponent);
    api.components.register(CharacterComponent);
    api.components.register(NonPlayerCharacterComponent);
    api.components.register(ClueComponent);
    api.components.register(EventComponent);
    api.components.register(FactionComponent);
    api.components.register(LocationComponent);
    api.components.register(MusicComponent);
    api.components.register(SceneComponent);
    api.components.register(SessionComponent);
    api.components.register(SubplotComponent);
  }
  static _addServices(api) {
    api.services.register(PlotWizardService);
    api.services.register(AllComponentManipulatorService);
    api.services.register(AnalyserService);
    api.services.register(BreadcrumbService);
    api.services.register(CodeblockService);
    api.services.register(ComponentOptionsService);
    api.services.register(ContentEditorService);
    api.services.register(DiceService);
    api.services.register(FileCreationService);
    api.services.register(FileManipulatorService);
    api.services.register(GalleryService);
    api.services.register(GraphViewService);
    api.services.register(HelpService);
    api.services.register(IndexService);
    api.services.register(ImageService);
    api.services.register(LinkSuggesterService);
    api.services.register(LoggerService);
    api.services.register(PlotService);
    api.services.register(PronounService);
    api.services.register(RelationshipService);
    api.services.register(RunningTimeService);
    api.services.register(SceneBuilderService);
    api.services.register(SearchService);
    api.services.register(SorterService);
    api.services.register(TagService);
    api.services.register(YamlService);
    if (api.app.plugins.enabledPlugins.has("fantasy-calendar"))
      api.services.register(FantasyCalendarService);
    api.services.register(DateService);
  }
  static _addFetchers(api) {
    api.fetchers.register(ReleaseNoteFetcher);
    api.fetchers.register(YouTubeImageFetcher);
  }
};

// src/managers/fetchersManager/FetchersManager.ts
var FetchersManager = class {
  constructor(_api) {
    this._api = _api;
    this._fetchers = /* @__PURE__ */ new Map();
  }
  get(fetcherClass) {
    return this._fetchers.get(fetcherClass);
  }
  register(fetcherClass) {
    this._fetchers.set(fetcherClass, new fetcherClass(this._api));
  }
};

// src/managers/staticViewsManager/StaticViewsManager.ts
var StaticViewsManager = class {
  constructor(_api) {
    this._api = _api;
    this._showInRightLeaf = /* @__PURE__ */ new Map([
      ["rpgm-creator-view" /* RPGManager */, true],
      ["rpgm-timeline-view" /* Timeline */, false],
      ["rpgm-error-view" /* Errors */, true],
      ["rpgm-release-note-view" /* ReleaseNote */, false]
    ]);
  }
  create(_0) {
    return __async(this, arguments, function* (type, params = []) {
      this._api.app.workspace.detachLeavesOfType(type.toString());
      const showInRightLeaf = this._showInRightLeaf.get(type);
      if (showInRightLeaf === true || showInRightLeaf === void 0) {
        yield this._api.app.workspace.getRightLeaf(false).setViewState({
          type: type.toString(),
          active: true
        });
      } else {
        yield this._api.app.workspace.getLeaf(true).setViewState({
          type: type.toString(),
          active: true
        });
      }
      const leaf = this._api.app.workspace.getLeavesOfType(type.toString())[0];
      const view = leaf.view;
      this._api.app.workspace.revealLeaf(leaf);
      view.initialise(params);
      view.render();
    });
  }
};

// src/managers/databaseManager/Database.ts
var import_obsidian37 = require("obsidian");
var Database = class extends import_obsidian37.Component {
  constructor(_api) {
    super();
    this._api = _api;
    this.recordset = [];
    this._isDatabaseReady = false;
    this._basenameIndex = /* @__PURE__ */ new Map();
  }
  ready() {
    return __async(this, null, function* () {
      this._isDatabaseReady = true;
      this._api.app.workspace.trigger("rpgmanager:database-ready");
      this._api.service(RunningTimeService).updateMedianTimes(true);
      this.registerEvent(this._api.app.metadataCache.on("resolve", (file) => this.onSave(file)));
      this.registerEvent(this._api.app.vault.on("rename", (file, oldPath) => this._onRename(file, oldPath)));
      this.registerEvent(this._api.app.vault.on("delete", (file) => this._onDelete(file)));
      this._api.app.workspace.trigger("rpgmanager:index-complete");
      this._api.app.workspace.trigger("rpgmanager:force-refresh-views");
    });
  }
  get isReady() {
    return this._isDatabaseReady;
  }
  create(component) {
    let isNew = true;
    for (let componentsCounter = 0; componentsCounter < this.recordset.length; componentsCounter++) {
      if (this.recordset[componentsCounter].file.path === component.file.path) {
        this.recordset[componentsCounter] = component;
        isNew = false;
      }
    }
    if (isNew) {
      this.recordset.push(component);
      this._basenameIndex.set(component.file.path, component.file.basename);
    }
  }
  read(query) {
    return this.recordset.filter(query !== null ? query : true);
  }
  update(component) {
    this.create(component);
  }
  delete(component) {
    const key = typeof component === "string" ? component : component.file.path;
    let index = void 0;
    for (let componentsCounter = 0; componentsCounter < this.recordset.length; componentsCounter++) {
      if (this.recordset[componentsCounter].file.path === key) {
        index = componentsCounter;
        break;
      }
    }
    if (index !== void 0) {
      this.recordset.splice(index, 1);
      this._basenameIndex.delete(key);
    }
    return index !== void 0;
  }
  readByPath(path2) {
    const response = this.recordset.filter((component) => component.file.path === path2);
    return response.length === 1 ? response[0] : void 0;
  }
  readByBaseName(basename) {
    const response = this.recordset.filter((component) => component.file.basename === basename);
    return response.length === 1 ? response[0] : void 0;
  }
  readById(id) {
    const result = this.read((component) => component.index.id === id);
    if (result.length !== 1)
      throw new Error("");
    return result[0];
  }
  readChildren(type, id) {
    return this.read((model) => model.index.type === type && model.index.parentId === id);
  }
  readNeighbour(type, id, previous) {
    const result = this.read((model) => model.index.type === type && (id.campaignId !== void 0 ? model.index.campaignId === id.campaignId : true) && (id.parentId !== void 0 ? model.index.parentId === id.parentId : true) && model.index.positionInParent === (previous ? id.positionInParent - 1 : id.positionInParent + 1));
    if (result.length === 0)
      throw new ComponentNotFoundError(this._api, id);
    return result[0];
  }
  _replaceFileContent(file, oldBaseName, newBaseName) {
    return __async(this, null, function* () {
      const content = yield this._api.app.vault.read(file);
      const newFileContent = content.replaceAll("[[" + oldBaseName + "]]", "[[" + newBaseName + "]]").replaceAll("[[" + oldBaseName + "|", "[[" + newBaseName + "|");
      if (content !== newFileContent) {
        return this._api.app.vault.modify(file, newFileContent).then(() => {
          return;
        });
      }
    });
  }
  _onDelete(file) {
    return __async(this, null, function* () {
      if (this.delete(file.path))
        this._api.app.workspace.trigger("rpgmanager:refresh-views");
    });
  }
  _onRename(file, oldPath) {
    return __async(this, null, function* () {
      const oldBaseName = this._basenameIndex.get(oldPath);
      const newBaseName = file.path;
      const metadata = this._api.app.metadataCache.getFileCache(file);
      const component = this.readByPath(file.path);
      yield this._basenameIndex.delete(oldPath);
      if (component !== void 0)
        yield this._basenameIndex.set(file.path, file.basename);
      if (this._api.service(GalleryService).imageExtensions.contains(file.extension)) {
        this._api.service(AllComponentManipulatorService).updateImagePath(oldPath, file.path);
      } else {
        this._api.service(AllComponentManipulatorService).updateRelationshipPath(oldPath, file.path);
      }
      if (oldBaseName !== void 0 && component !== void 0 && metadata != null) {
        yield this._replaceFileContent(file, oldBaseName, newBaseName);
        yield component.readMetadata();
        component.addReverseRelationships().then(() => {
          var _a, _b;
          if (((_a = this._api.app.workspace.getActiveFile()) == null ? void 0 : _a.path) === file.path) {
            (_b = this._api.app.workspace.getActiveViewOfType(import_obsidian37.MarkdownView)) == null ? void 0 : _b.editor.refresh();
          }
          this._api.app.workspace.trigger("rpgmanager:refresh-views");
        });
      }
    });
  }
  onSave(file) {
    return __async(this, null, function* () {
      let component = yield this.readByPath(file.path);
      try {
        const isNewComponent = component === void 0;
        if (component === void 0)
          component = yield DatabaseInitialiser.createComponent(this._api, file);
        if (component === void 0)
          return;
        const newId = yield DatabaseInitialiser.readID(file);
        if (newId !== void 0 && (component == null ? void 0 : component.index.checksum) !== newId.checksum)
          component.index = newId;
        yield component.readMetadata();
        if (!isNewComponent)
          yield component.addReverseRelationships();
        yield component.addRelationshipToRelatedElements();
        if (isNewComponent && (component.stage === 2 /* Run */ || component.stage === 0 /* Plot */)) {
          yield component.validateHierarchy();
          let error = void 0;
          try {
            const duplicate = this.readById(component.index.id);
            error = new ComponentDuplicatedError(this._api, component.index, [duplicate], component);
          } catch (e) {
          }
          if (error !== void 0) {
            throw error;
          }
        }
        yield this.create(component);
        yield component.touch();
        this._api.app.workspace.trigger("rpgmanager:refresh-views");
      } catch (e) {
        if (e instanceof AbstractRpgManagerError) {
          new DatabaseErrorModal(this._api, void 0, e, file).open();
        } else {
          throw e;
        }
        return;
      }
    });
  }
};

// src/managers/databaseManager/DatabaseManager.ts
var DatabaseManager = class {
  constructor(_api) {
    this._api = _api;
  }
  get database() {
    if (this._database === void 0)
      this._database = new Database(this._api);
    return this._database;
  }
  set database(database) {
    this._database = database;
  }
  createDatabase() {
    return new Database(this._api);
  }
};

// src/api/RpgManagerApi.ts
var RpgManagerApi = class {
  constructor(app2, _plugin) {
    this.app = app2;
    this._plugin = _plugin;
    this._version = this._plugin.version;
    this._controllers = new ControllerManager(this);
    this._components = new ComponentsManager(this);
    this._database = new DatabaseManager(this);
    this._fetchers = new FetchersManager(this);
    this._modals = new ModalsManager(this);
    this._models = new ModelsManager(this);
    this._services = new ServicesManager(this);
    this._staticViews = new StaticViewsManager(this);
    this._templates = new TemplatesManager(this);
    this._views = new ViewsManager(this);
    const file = this.app.vault.getAbstractFileByPath("/");
    this._root = this.app.vault.getResourcePath(file);
    if (this._root.includes("?"))
      this._root = this._root.substring(0, this._root.lastIndexOf("?"));
    if (!this._root.endsWith("/"))
      this._root += "/";
  }
  get controllers() {
    return this._controllers;
  }
  get components() {
    return this._components;
  }
  get database() {
    return this._database.database;
  }
  set database(database) {
    this._database.database = database;
  }
  get fetchers() {
    return this._fetchers;
  }
  get modals() {
    return this._modals;
  }
  get models() {
    return this._models;
  }
  get plugin() {
    return this._plugin;
  }
  get root() {
    return this._root;
  }
  get services() {
    return this._services;
  }
  get settings() {
    return this._plugin.settings;
  }
  get staticViews() {
    return this._staticViews;
  }
  get templates() {
    return this._templates;
  }
  get views() {
    return this._views;
  }
  get version() {
    return this._version;
  }
  bootstrap() {
    Bootstrapper.initialise(this);
  }
  createDatabase() {
    return this._database.createDatabase();
  }
  fetcher(fetcher) {
    const response = this._fetchers.get(fetcher);
    if (response === void 0) {
      this.service(LoggerService).createError(1 /* System */, "The requested fetcher (" + fetcher.name + ") does not exist");
      throw new Error("The requested fetcher (" + fetcher.name + ") does not exist");
    }
    return response;
  }
  service(service) {
    const response = this._services.get(service);
    if (response === void 0) {
      this.service(LoggerService).createError(1 /* System */, "The requested service (" + service.name + ") does not exist");
      throw new Error("The requested service (" + service.name + ") does not exist");
    }
    return response;
  }
};

// src/core/updater/abstracts/AbstractDatabaseWorker.ts
var AbstractDatabaseWorker = class {
  constructor(api) {
    this.api = api;
  }
};

// src/core/updater/workers/V3_0_to_3_1_worker.ts
var import_obsidian38 = require("obsidian");
var V3_0_to_3_1_worker = class extends AbstractDatabaseWorker {
  get from() {
    return "3.0";
  }
  get to() {
    return "3.1";
  }
  run(reporter = void 0) {
    return __async(this, null, function* () {
      var _a;
      this.api.service(LoggerService).warning(16 /* Updater */, "Updating RPG Manager from v3.0 to v3.1");
      const files = yield this.api.app.vault.getMarkdownFiles();
      if (reporter !== void 0)
        reporter.setFileCount(files.length);
      for (let filesIndex = 0; filesIndex < files.length; filesIndex++) {
        const file = files[filesIndex];
        const cachedMetadata = this.api.app.metadataCache.getFileCache(file);
        if (cachedMetadata == null) {
          if (reporter !== void 0)
            reporter.addFileUpdated();
          continue;
        }
        let fileContent = yield this.api.app.vault.read(file).catch(() => {
          return "";
        });
        const fileContentArray = fileContent.split("\n");
        if (fileContent.indexOf("```RpgManagerData") === -1) {
          if (reporter !== void 0)
            reporter.addFileUpdated();
          continue;
        }
        const codeblocks = (_a = cachedMetadata.sections) == null ? void 0 : _a.filter((section) => section.type === "code" && fileContentArray[section.position.start.line] === "```RpgManagerData");
        if (codeblocks == void 0 || codeblocks.length !== 1) {
          if (reporter !== void 0)
            reporter.addFileUpdated();
          continue;
        }
        const codeblock = codeblocks[0];
        const data = fileContentArray.slice(codeblock.position.start.line + 1, codeblock.position.end.line);
        const yaml = (0, import_obsidian38.parseYaml)(data.join("\n"));
        if (yaml == void 0) {
          if (reporter !== void 0)
            reporter.addFileUpdated();
          continue;
        }
        if (yaml.data === void 0)
          yaml.data = {};
        if (yaml.data.images === void 0)
          yaml.data.images = [];
        const imageSrc = yaml.data.image;
        let imagePath = imageSrc;
        if (imagePath == void 0 || imagePath === "") {
          const attachmentFolder = this.api.settings.imagesFolder !== void 0 && this.api.settings.imagesFolder !== "" ? this.api.settings.imagesFolder : this.api.app.vault.config.attachmentFolderPath;
          if (attachmentFolder === void 0) {
            if (reporter !== void 0)
              reporter.addFileUpdated();
            continue;
          }
          const files2 = this.api.app.vault.getFiles().filter((image) => image.path.toLowerCase().startsWith(attachmentFolder.toLowerCase()) && image.basename.toLowerCase().startsWith(file.basename.toLowerCase()));
          if (files2.length === 1)
            imagePath = files2[0].path;
        }
        if (imagePath == void 0 || imagePath === "") {
          if (reporter !== void 0)
            reporter.addFileUpdated();
          continue;
        }
        const metadataImage = {
          path: imagePath
        };
        yaml.data.images.push(metadataImage);
        delete yaml.data.image;
        const newYamlArray = this.api.service(YamlService).stringify(yaml).split("\n");
        fileContentArray.splice(codeblock.position.start.line + 1, codeblock.position.end.line - codeblock.position.start.line - 1, ...newYamlArray);
        fileContent = fileContentArray.join("\n");
        if (reporter !== void 0)
          reporter.addFileUpdated();
        this.api.app.vault.modify(file, fileContent).then(() => {
          if (reporter !== void 0)
            reporter.addFileUpdated();
        });
      }
    });
  }
};

// src/core/updater/workers/V3_1_to_3_4_worker.ts
var import_obsidian39 = require("obsidian");
var V3_1_to_3_4_worker = class extends AbstractDatabaseWorker {
  get from() {
    return "3.1";
  }
  get to() {
    return "3.4";
  }
  run(reporter = void 0) {
    return __async(this, null, function* () {
      this._elements = [];
      this._fileElements = /* @__PURE__ */ new Map();
      this.api.service(LoggerService).warning(16 /* Updater */, "Updating RPG Manager from v3.1 to v3.4");
      yield this._loadElements();
      if (reporter !== void 0) {
        reporter.refreshFileCount();
        reporter.setFileCount(this._fileElements.size);
      }
      yield this._updateCampaigns();
      for (let filesIndex = 0; filesIndex < this._files.length; filesIndex++) {
        const file = this._files[filesIndex];
        const elementInformation = this._fileElements.get(file);
        if (elementInformation === void 0) {
          yield reporter == null ? void 0 : reporter.addFileUpdated();
        } else {
          let newIndex = (0, import_obsidian39.stringifyYaml)(elementInformation.newIndex);
          newIndex = "### DO NOT EDIT MANUALLY IF NOT INSTRUCTED TO DO SO ###\n" + newIndex;
          let newFileContent = yield elementInformation.originalContent.replace(elementInformation.originalID, newIndex);
          if (elementInformation.originalDataContent !== void 0 && elementInformation.originalData != void 0)
            newFileContent = yield newFileContent.replace(elementInformation.originalDataContent, this.api.service(YamlService).stringify(elementInformation.originalData));
          if (newFileContent !== elementInformation.originalContent)
            yield this.api.app.vault.modify(file, newFileContent);
          yield reporter == null ? void 0 : reporter.addFileUpdated();
        }
      }
    });
  }
  _updateCampaigns() {
    return __async(this, null, function* () {
      const campaigns = this._elements.filter((component) => component.type === 1 /* Campaign */);
      for (let index = 0; index < campaigns.length; index++) {
        const id = v4_default();
        const newComponentId = {
          type: campaigns[index].type,
          campaignSettings: campaigns[index].campaignSettings,
          id,
          campaignId: id,
          parentId: id,
          positionInParent: 1
        };
        campaigns[index].newIndex = newComponentId;
        yield this._updateSessions(campaigns[index]);
        yield this._updateAdventures(campaigns[index]);
        yield this._updateRemaining(campaigns[index]);
        if (campaigns[index].originalData.data.currentAdventureId != void 0 && campaigns[index].originalData.data.currentAdventureId !== "" && campaigns[index].originalData.data.currentAdventureId.toString().indexOf("/") !== -1) {
          let adventureIndex = void 0;
          let currentAdventureId = campaigns[index].originalData.data.currentAdventureId;
          if (currentAdventureId.indexOf("-") !== -1) {
            currentAdventureId = currentAdventureId.substring(currentAdventureId.lastIndexOf("-") + 1);
            [, adventureIndex] = currentAdventureId.split("/");
          } else {
            [, , adventureIndex] = currentAdventureId.split("/");
          }
          if (adventureIndex !== void 0) {
            const adventureIndexId = +adventureIndex;
            const adventures = this._elements.filter((component) => component.type === 2 /* Adventure */ && component.campaignId === campaigns[index].campaignId && component.adventureId === adventureIndexId);
            if (adventures.length === 1 && adventures[0].newIndex !== void 0)
              campaigns[index].originalData.data.currentAdventureId = adventures[0].newIndex.id;
          }
        }
        if (campaigns[index].originalData.data.currentActId != void 0 && campaigns[index].originalData.data.currentActId !== "" && campaigns[index].originalData.data.currentActId.toString().indexOf("/") !== -1) {
          let adventureIndex = void 0;
          let actIndex = void 0;
          let currentActId = campaigns[index].originalData.data.currentActId;
          if (currentActId.indexOf("-") !== -1) {
            currentActId = currentActId.substring(currentActId.lastIndexOf("-") + 1);
            [, adventureIndex, actIndex] = currentActId.split("/");
          } else {
            [, , adventureIndex, actIndex] = currentActId.split("/");
          }
          if (adventureIndex !== void 0 && actIndex !== void 0) {
            const adventureIndexId = +adventureIndex;
            const actIndexId = +actIndex;
            const acts = this._elements.filter((component) => component.type === 4 /* Act */ && component.campaignId === campaigns[index].campaignId && component.adventureId === adventureIndexId && component.actId === actIndexId);
            if (acts.length === 1 && acts[0].newIndex !== void 0)
              campaigns[index].originalData.data.currentActId = acts[0].newIndex.id;
          }
        }
        if (campaigns[index].originalData.data.currentSessionId != void 0 && campaigns[index].originalData.data.currentSessionId !== "" && campaigns[index].originalData.data.currentSessionId.toString().indexOf("/") !== -1) {
          let sessionIndex = void 0;
          let currentSessionId = campaigns[index].originalData.data.currentSessionId;
          if (currentSessionId.indexOf("-") !== -1) {
            currentSessionId = currentSessionId.substring(currentSessionId.lastIndexOf("-") + 1);
            [, sessionIndex] = currentSessionId.split("/");
          } else {
            [, , sessionIndex] = currentSessionId.split("/");
          }
          if (sessionIndex !== void 0) {
            const sessionIndexId = +sessionIndex;
            const sessions = this._elements.filter((component) => component.type === 16 /* Session */ && component.campaignId === campaigns[index].campaignId && component.sessionId === sessionIndexId);
            if (sessions.length === 1 && sessions[0].newIndex !== void 0)
              campaigns[index].originalData.data.currentSessionId = sessions[0].newIndex.id;
          }
        }
      }
    });
  }
  _updateAdventures(campaign) {
    return __async(this, null, function* () {
      if (campaign.newIndex === void 0)
        return;
      const adventures = this._elements.filter((component) => component.type === 2 /* Adventure */ && component.campaignId === campaign.campaignId).sort((a, b) => {
        if (a.adventureId === void 0)
          return -1;
        if (b.adventureId === void 0)
          return 1;
        if (a.adventureId > b.adventureId)
          return 1;
        if (a.adventureId < b.adventureId)
          return -1;
        return 0;
      });
      for (let index = 0; index < adventures.length; index++) {
        const newComponentId = {
          type: adventures[index].type,
          campaignSettings: adventures[index].campaignSettings,
          id: v4_default(),
          campaignId: campaign.newIndex.campaignId,
          parentId: campaign.newIndex.campaignId,
          positionInParent: index + 1
        };
        adventures[index].newIndex = newComponentId;
        yield this._updateActs(adventures[index]);
      }
    });
  }
  _updateActs(adventure) {
    return __async(this, null, function* () {
      if (adventure.newIndex === void 0)
        return;
      const acts = this._elements.filter((component) => component.type === 4 /* Act */ && component.campaignId === adventure.campaignId && component.adventureId === adventure.adventureId).sort((a, b) => {
        if (a.actId === void 0)
          return -1;
        if (b.actId === void 0)
          return 1;
        if (a.actId > b.actId)
          return 1;
        if (a.actId < b.actId)
          return -1;
        return 0;
      });
      for (let index = 0; index < acts.length; index++) {
        const newComponentId = {
          type: acts[index].type,
          campaignSettings: acts[index].campaignSettings,
          id: v4_default(),
          campaignId: adventure.newIndex.campaignId,
          parentId: adventure.newIndex.id,
          positionInParent: index + 1
        };
        acts[index].newIndex = newComponentId;
        yield this._updateScenes(acts[index]);
      }
    });
  }
  _updateScenes(act) {
    return __async(this, null, function* () {
      if (act.newIndex === void 0)
        return;
      const scenes = this._elements.filter((component) => component.type === 8 /* Scene */ && component.campaignId === act.campaignId && component.adventureId === act.adventureId && component.actId === act.actId).sort((a, b) => {
        if (a.sceneId === void 0)
          return -1;
        if (b.sceneId === void 0)
          return 1;
        if (a.sceneId > b.sceneId)
          return 1;
        if (a.sceneId < b.sceneId)
          return -1;
        return 0;
      });
      for (let index = 0; index < scenes.length; index++) {
        if (scenes[index].originalData.data.sessionId != void 0 && scenes[index].originalData.data.sessionId !== "" && scenes[index].originalData.data.sessionId.toString().indexOf("/") !== -1) {
          const [, sessionIndex] = scenes[index].originalData.data.sessionId.split("/");
          const sessions = this._elements.filter((component) => component.type === 16 /* Session */ && component.campaignId === act.campaignId && component.sessionId === +sessionIndex);
          if (sessions.length === 1 && sessions[0].newIndex !== void 0) {
            scenes[index].originalData.data.sessionId = sessions[0].newIndex.id;
            scenes[index].originalData.data.positionInSession = index + 1;
          }
        }
        const newComponentId = {
          type: scenes[index].type,
          campaignSettings: scenes[index].campaignSettings,
          id: v4_default(),
          campaignId: act.newIndex.campaignId,
          parentId: act.newIndex.id,
          positionInParent: index + 1
        };
        scenes[index].newIndex = newComponentId;
      }
    });
  }
  _updateSessions(campaign) {
    return __async(this, null, function* () {
      if (campaign.newIndex === void 0)
        return;
      const sessions = this._elements.filter((component) => component.type === 16 /* Session */ && component.campaignId === campaign.campaignId).sort((a, b) => {
        if (a.sessionId === void 0)
          return -1;
        if (b.sessionId === void 0)
          return 1;
        if (a.sessionId > b.sessionId)
          return 1;
        if (a.sessionId < b.sessionId)
          return -1;
        return 0;
      });
      for (let index = 0; index < sessions.length; index++) {
        const newComponentId = {
          type: sessions[index].type,
          campaignSettings: sessions[index].campaignSettings,
          id: v4_default(),
          campaignId: campaign.newIndex.campaignId,
          parentId: campaign.newIndex.campaignId,
          positionInParent: index + 1
        };
        sessions[index].newIndex = newComponentId;
      }
    });
  }
  _updateRemaining(campaign) {
    return __async(this, null, function* () {
      if (campaign.newIndex === void 0)
        return;
      const elements = this._elements.filter((component) => component.type !== 1 /* Campaign */ && component.type !== 2 /* Adventure */ && component.type !== 4 /* Act */ && component.type !== 8 /* Scene */ && component.type !== 16 /* Session */ && component.campaignId === campaign.campaignId);
      for (let index = 0; index < elements.length; index++) {
        const newComponentId = {
          type: elements[index].type,
          campaignSettings: elements[index].campaignSettings,
          id: v4_default(),
          campaignId: campaign.newIndex.campaignId,
          parentId: campaign.newIndex.campaignId,
          positionInParent: 1
        };
        elements[index].newIndex = newComponentId;
      }
    });
  }
  _loadElements() {
    return __async(this, null, function* () {
      var _a;
      this._files = yield this.api.app.vault.getMarkdownFiles();
      for (let filesIndex = 0; filesIndex < this._files.length; filesIndex++) {
        const file = this._files[filesIndex];
        const cachedMetadata = this.api.app.metadataCache.getFileCache(file);
        if (cachedMetadata == null || cachedMetadata.sections == null) {
          this._fileElements.set(file, void 0);
          continue;
        }
        const fileContent = yield this.api.app.vault.read(file);
        const fileContentArray = fileContent.split("\n");
        let updaterComponent = void 0;
        let data = void 0;
        let dataContent = void 0;
        for (let index = 0; index < ((_a = cachedMetadata.sections.length) != null ? _a : 0); index++) {
          const section = cachedMetadata.sections[index];
          if (section.type === "code" && fileContentArray[section.position.start.line] === "```RpgManagerData") {
            dataContent = "";
            for (let index2 = section.position.start.line + 1; index2 < section.position.end.line; index2++) {
              dataContent += fileContentArray[index2] + "\n";
            }
            data = (0, import_obsidian39.parseYaml)(dataContent);
          }
          if (section.type === "code" && fileContentArray[section.position.start.line] === "```RpgManagerID") {
            let indexID = "";
            for (let index2 = section.position.start.line + 1; index2 < section.position.end.line; index2++) {
              indexID += fileContentArray[index2] + "\n";
            }
            const indexData = (0, import_obsidian39.parseYaml)(indexID);
            if (indexData.id === void 0 || indexData.checksum === void 0) {
              this._fileElements.set(file, void 0);
              continue;
            } else {
              const [type, campaignSettings, ids] = indexData.id.split("-");
              let campaignId = 0;
              let adventureId;
              let actId;
              let sceneId;
              let sessionId;
              switch (+type) {
                case 8 /* Scene */:
                  [campaignId, adventureId, actId, sceneId] = ids.split("/");
                  break;
                case 4 /* Act */:
                  [campaignId, adventureId, actId] = ids.split("/");
                  break;
                case 2 /* Adventure */:
                  [campaignId, adventureId] = ids.split("/");
                  break;
                case 16 /* Session */:
                  [campaignId, sessionId] = ids.split("/");
                  break;
                default:
                  campaignId = ids;
                  break;
              }
              updaterComponent = {
                originalContent: fileContent,
                originalID: indexID,
                type: +type,
                campaignSettings: +campaignSettings,
                campaignId: +campaignId,
                adventureId: adventureId !== void 0 ? +adventureId : void 0,
                actId: actId !== void 0 ? +actId : void 0,
                sceneId: sceneId !== void 0 ? +sceneId : void 0,
                sessionId: sessionId !== void 0 ? +sessionId : void 0
              };
              this._elements.push(updaterComponent);
              this._fileElements.set(file, updaterComponent);
            }
          }
        }
        if (updaterComponent !== void 0 && data !== void 0 && dataContent !== void 0) {
          updaterComponent.originalData = data;
          updaterComponent.originalDataContent = dataContent;
        }
      }
    });
  }
};

// src/core/updater/DatabaseUpdater.ts
var versionMap = {
  30: V3_0_to_3_1_worker,
  33: V3_1_to_3_4_worker
};
var DatabaseUpdater = class {
  constructor(_api, _previousVersion, _currentVersion) {
    this._api = _api;
    this._previousVersion = _previousVersion;
    this._currentVersion = _currentVersion;
    this._updaters = [];
  }
  get newVersion() {
    return this._currentVersion;
  }
  get oldVersion() {
    return this._previousVersion;
  }
  _loadUpdaters() {
    if (this._previousVersion === "")
      this._previousVersion = "3.0";
    const previousVersionMajorMinor = this._getMajorMinor(this._previousVersion);
    const currentVersionMajorMinor = this._getMajorMinor(this._currentVersion);
    if (previousVersionMajorMinor === void 0 || currentVersionMajorMinor === void 0 || previousVersionMajorMinor === currentVersionMajorMinor)
      return;
    let currentVersion = +previousVersionMajorMinor * 10;
    const maxVersion = +currentVersionMajorMinor * 10;
    while (currentVersion < maxVersion) {
      const updaterInterface = versionMap[currentVersion];
      if (updaterInterface !== void 0)
        this._updaters.push(new updaterInterface(this._api));
      currentVersion++;
    }
  }
  requiresDatabaseUpdate() {
    return __async(this, null, function* () {
      yield this._loadUpdaters();
      if (yield this._isVaultEmptyOfRpgManagerComponents()) {
        const currentVersionMajorMinor = this._getMajorMinor(this._currentVersion);
        yield this._api.plugin.updateSettings({ previousVersion: currentVersionMajorMinor });
        this._updaters = [];
        return false;
      }
      return this._updaters.length !== 0;
    });
  }
  update(reporter = void 0) {
    return __async(this, null, function* () {
      let response = false;
      if (this._updaters.length > 0) {
        response = true;
        let worker;
        for (let index = 0; index < this._updaters.length; index++) {
          worker = this._updaters[index];
          if (worker !== void 0) {
            if (reporter !== void 0)
              reporter.setUpdater(worker.from, worker.to);
            yield worker.run(reporter);
          }
        }
        if (worker !== void 0)
          yield this._api.plugin.updateSettings({ previousVersion: worker.to });
      }
      return response;
    });
  }
  _isVaultEmptyOfRpgManagerComponents() {
    return __async(this, null, function* () {
      const everyMarkdown = this._api.app.vault.getMarkdownFiles();
      for (let index = 0; index < everyMarkdown.length; index++) {
        const cache = this._api.app.metadataCache.getFileCache(everyMarkdown[index]);
        if (cache === void 0 || (cache == null ? void 0 : cache.sections) == void 0)
          continue;
        const validSections = cache.sections.filter((section) => section.type === "code");
        for (let sectionIndex = 0; sectionIndex < validSections.length; sectionIndex++) {
          const fileContent = yield this._api.app.vault.read(everyMarkdown[index]);
          const fileArray = fileContent.split("\n");
          if (fileArray[validSections[sectionIndex].position.start.line].startsWith("```RpgManager"))
            return false;
        }
      }
      return true;
    });
  }
  _getMajorMinor(version) {
    const versionParts = version.split(".");
    if (versionParts.length < 2)
      return void 0;
    return versionParts[0] + "." + versionParts[1];
  }
};

// src/core/updater/modals/UpdaterModal.ts
var import_obsidian40 = require("obsidian");
var UpdaterModal = class extends import_obsidian40.Modal {
  constructor(_api, _updater) {
    super(_api.app);
    this._api = _api;
    this._updater = _updater;
    this._currentCounter = 0;
    this.scope = new import_obsidian40.Scope();
    this.scope.register([], "Escape", (evt) => {
      evt.preventDefault();
    });
  }
  onOpen() {
    super.onOpen();
    this.contentEl.createEl("h2", { text: "RPG Manager Needs to update the data structure" });
    this._infoEl = this.contentEl.createDiv();
    const infoMessage = "RPG Manager has been updated to version **" + this._updater.newVersion + "**, that requires some updates to the structure of your notes.\n\nThe process is automatic and has been tested, but there is always the possibility for some of your customisations to have escaped what is believed to be the normal structure of the data.\n\n**To avoid any data loss, the update is not automatic, therefore RPG Manager is currently disabled.**\n\nIt is highly recommended you **create a backup copy of your vault** before you run the updater. Once you have performed a backup of your vault, you can update your data with the button below.\n\nIn case of any trouble during the update process, you can [ask for support](https://github.com/carlonicora/obsidian-rpg-manager) directly on RPG Manager GitHubpage.\n\nIf you have backed up your data (*or if you feel like a curious Kender and prefer to live on the edge*) you can run the data update clicking the button below!";
    const waitMessage = "**Updating your data in progress**.\n\nPlease be patient...";
    const successMessage = "The data structure of your notes has been updated to the latest version of RPG Manager\n\nYou can now use the plugin once more. Please don't forget to read the [release notes](https://github.com/carlonicora/obsidian-rpg-manager/blob/master/ChangeLog.md) to know what's new in RPG Manager.\n\n*...oh, and if you like to support or collaborate with us, your help wil be highly appreciated.*";
    this._updateModalDescription(infoMessage);
    const updateButtonEl = this.contentEl.createEl("button", { text: "Update the data to v" + this._updater.newVersion + " or RPG Manager" });
    updateButtonEl.addEventListener("click", () => {
      this._updateModalDescription(waitMessage, true);
      updateButtonEl.remove();
      this._updater.update(this).then(() => {
        this.app.plugins.getPlugin("rpg-manager").initialise();
        this._updateModalDescription(successMessage);
        updateButtonEl.remove();
      });
    });
  }
  _updateModalDescription(content, addCounters = void 0) {
    return __async(this, null, function* () {
      this._infoEl.empty();
      import_obsidian40.MarkdownRenderer.renderMarkdown(content, this._infoEl, "", null);
      if (addCounters) {
        const updaterInfoContainerEl = this._infoEl.createDiv();
        this._versionEl = updaterInfoContainerEl.createDiv({ text: "Updating" });
        const countersContainerEl = updaterInfoContainerEl.createDiv();
        this._currentEl = countersContainerEl.createSpan({ text: "0" });
        countersContainerEl.createSpan({ text: " out of " });
        this._countEl = countersContainerEl.createSpan({ text: "0" });
        countersContainerEl.createSpan({ text: " components updated" });
        this._currentCounter = 0;
      }
    });
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
    super.onClose();
  }
  setUpdater(startVersion, endVersion) {
    return __async(this, null, function* () {
      if (this._versionEl !== void 0)
        this._versionEl.textContent = "Updating from version " + startVersion + " to " + endVersion;
    });
  }
  setFileCount(count) {
    return __async(this, null, function* () {
      if (this._countEl !== void 0)
        this._countEl.textContent = count.toString();
    });
  }
  addFileUpdated() {
    return __async(this, null, function* () {
      this._currentCounter++;
      if (this._currentEl !== void 0)
        this._currentEl.textContent = this._currentCounter.toString();
    });
  }
  refreshFileCount() {
    return __async(this, null, function* () {
      this._currentCounter = 0;
      if (this._currentEl !== void 0)
        this._currentEl.textContent = this._currentCounter.toString();
    });
  }
};

// src/core/staticViews/rpgManagerView/RPGManagerView.ts
var import_obsidian42 = require("obsidian");

// src/managers/staticViewsManager/abstracts/AbstractStaticView.ts
var import_obsidian41 = require("obsidian");
var AbstractStaticView = class extends import_obsidian41.ItemView {
  constructor(api, leaf) {
    super(leaf);
    this.api = api;
  }
  initialise(params) {
    this.onOpenOrResize();
  }
  getViewType() {
    return this.viewType;
  }
  getDisplayText() {
    return this.displayText;
  }
  onOpen() {
    return __async(this, null, function* () {
      this.onOpenOrResize();
    });
  }
  onOpenOrResize() {
    return __async(this, null, function* () {
      const container = this.containerEl.children[1];
      container.empty();
      this.rpgmContentEl = container.createDiv({ cls: "rpgm-view" });
      this.rpgmContentEl.createEl("h2", { text: this.displayText });
    });
  }
  onClose() {
    return __async(this, null, function* () {
    });
  }
  updateInternalLinks(element) {
    if (element.children.length > 0) {
      for (let index = 0; index < element.children.length; index++) {
        const elementChild = element.children.item(index);
        if (elementChild !== null) {
          if (elementChild instanceof HTMLAnchorElement) {
            this.updateInternalLink(elementChild);
          } else {
            this.updateInternalLinks(elementChild);
          }
        }
      }
    }
  }
  updateInternalLink(element) {
    const basename = element.dataset.href;
    if (basename == void 0)
      return;
    const component = this.api.database.read((data) => data.file.basename === basename)[0];
    if (component === void 0)
      return;
    const file = component.file;
    element.addEventListener("click", (ev) => {
      ev.preventDefault();
      this.app.workspace.getLeaf(true).openFile(file);
    });
    element.href = "#";
  }
};

// src/core/staticViews/rpgManagerView/RPGManagerView.ts
var RPGManagerView = class extends AbstractStaticView {
  constructor() {
    super(...arguments);
    this.viewType = "rpgm-creator-view" /* RPGManager */.toString();
    this.displayText = "RPG Manager";
    this.icon = "d20";
  }
  onResize() {
    super.onResize();
    this.initialise([]);
    this.render();
  }
  initialise(params) {
    super.initialise([]);
    const campaigns = this.api.database.read((campaign) => campaign.index.type === 1 /* Campaign */);
    this._hasCampaigns = campaigns.length > 0;
    if (campaigns.length === 1)
      this._currentCampaign = campaigns[0];
    else
      this._currentCampaign = void 0;
    const file = this.app.workspace.getActiveFile();
    if (file != null)
      this._currentComponent = this.api.database.readByPath(file.path);
    else
      this._currentComponent = void 0;
    this.registerEvent(this.app.workspace.on("rpgmanager:refresh-views", this._addIncompleteComponents.bind(this)));
  }
  render() {
    return __async(this, null, function* () {
      this.rpgmContentEl.removeClass("rpgm-view");
      this.rpgmContentEl.addClass("rpg-manager-right-view");
      this.rpgmContentEl.empty();
      this.rpgmContentEl.createEl("h2", { text: "RPG Manager" });
      this._addCreators();
      this._incompleteListEl = this.rpgmContentEl.createDiv();
      this._addIncompleteComponents();
      this._addReleaseNotes();
      return Promise.resolve(void 0);
    });
  }
  _addTitle(containerEl, title, defaultOpen) {
    const titleElcontainerEl = containerEl.createDiv({ cls: "rpg-manager-right-view-title clearfix" });
    const response = containerEl.createDiv({ cls: "rpg-manager-right-view-container" });
    if (defaultOpen) {
      (0, import_obsidian42.setIcon)(titleElcontainerEl, "chevron-down");
      titleElcontainerEl.addClass("open");
      response.addClass("open");
    } else {
      (0, import_obsidian42.setIcon)(titleElcontainerEl, "chevron-right");
      titleElcontainerEl.addClass("closed");
      response.addClass("closed");
    }
    titleElcontainerEl.createEl("h3", { text: title });
    titleElcontainerEl.addEventListener("click", () => {
      titleElcontainerEl.empty();
      if (titleElcontainerEl.hasClass("open")) {
        titleElcontainerEl.removeClass("open");
        response.removeClass("open");
        titleElcontainerEl.addClass("closed");
        response.addClass("closed");
        (0, import_obsidian42.setIcon)(titleElcontainerEl, "chevron-right");
      } else {
        titleElcontainerEl.removeClass("closed");
        response.removeClass("closed");
        titleElcontainerEl.addClass("open");
        response.addClass("open");
        (0, import_obsidian42.setIcon)(titleElcontainerEl, "chevron-down");
      }
      titleElcontainerEl.createEl("h3", { text: title });
    });
    return response;
  }
  _addCreators() {
    const containerEl = this._addTitle(this.rpgmContentEl, "Create new...", true);
    this._createElementListItem(1 /* Campaign */, containerEl);
    if (this._hasCampaigns) {
      Object.keys(ComponentType).filter((v) => isNaN(Number(v))).forEach((typeString) => {
        const type = ComponentType[typeString];
        if (type !== 1 /* Campaign */) {
          this._createElementListItem(type, containerEl);
        }
      });
    }
  }
  _createElementListItem(type, containerEl) {
    const itemEl = containerEl.createDiv({ cls: "rpg-manager-right-view-container-element", text: ComponentType[type] });
    itemEl.addEventListener("click", () => {
      this._openCreationModal(type);
    });
  }
  _addIncompleteComponents() {
    return __async(this, null, function* () {
      this._incompleteListEl.empty();
      const containerEl = this._addTitle(this._incompleteListEl, "Incomplete elements", false);
      const components = this.api.database.read((component) => component.isComplete === false);
      components.forEach((component) => {
        const itemEl = containerEl.createDiv({ cls: "rpg-manager-right-view-container-element", text: component.file.basename });
        itemEl.addEventListener("click", () => {
          this.app.workspace.getLeaf(false).openFile(component.file);
        });
      });
    });
  }
  _addReleaseNotes() {
    return __async(this, null, function* () {
      const containerEl = this._addTitle(this.rpgmContentEl, "Help", false);
      containerEl.createDiv({ cls: "rpg-manager-right-view-container-element", text: "Release notes" }).addEventListener("click", () => {
        this.api.staticViews.create("rpgm-release-note-view" /* ReleaseNote */);
      });
    });
  }
  _openCreationModal(type) {
    var _a, _b, _c;
    let modalOpened = false;
    if (this._currentComponent !== void 0) {
      modalOpened = true;
      new CreationModal(this.api, type, true, null, (_a = this._currentComponent) == null ? void 0 : _a.index.campaignId, (_b = this._currentComponent) == null ? void 0 : _b.index.parentId).open();
    } else if (this._currentCampaign !== void 0) {
      modalOpened = true;
      new CreationModal(this.api, type, true, null, (_c = this._currentCampaign) == null ? void 0 : _c.index.campaignId).open();
    }
    if (!modalOpened) {
      new CreationModal(this.api, type).open();
    }
  }
};

// src/core/staticViews/releaseNoteView/ReleaseNoteView.ts
var import_obsidian43 = require("obsidian");
var ReleaseNoteView = class extends AbstractStaticView {
  constructor() {
    super(...arguments);
    this.viewType = "rpgm-release-note-view" /* ReleaseNote */.toString();
    this.displayText = "RPG Manager Release Notes";
    this.icon = "d20";
  }
  initialise(params) {
  }
  render() {
    return __async(this, null, function* () {
      this.rpgmContentEl.empty();
      const releaseNotes = yield this.api.fetcher(ReleaseNoteFetcher).fetchMarkdown();
      if (releaseNotes != null) {
        import_obsidian43.MarkdownRenderer.renderMarkdown(releaseNotes, this.rpgmContentEl, "", null);
      }
      const closeButtonEl = this.contentEl.createEl("button", { text: "Close the release notes" });
      closeButtonEl.addEventListener("click", () => {
        this.app.workspace.detachLeavesOfType("rpgm-release-note-view" /* ReleaseNote */.toString());
      });
    });
  }
};

// src/core/staticViews/errorView/ErrorView.ts
var import_obsidian44 = require("obsidian");
var ErrorView = class extends AbstractStaticView {
  constructor() {
    super(...arguments);
    this.viewType = "rpgm-error-view" /* Errors */.toString();
    this.displayText = "RPG Manager Errors";
    this.icon = "d20";
    this._errors = /* @__PURE__ */ new Map();
  }
  initialise(params) {
    this._errors = params[0];
  }
  render() {
    return __async(this, null, function* () {
      if (this._errors !== void 0 && this._errors.size > 0) {
        this._errors.forEach((error, file) => {
          const errorEl = this.rpgmContentEl.createEl("div");
          const errorTitle = error.getErrorTitle();
          let title;
          if (errorTitle !== void 0) {
            title = errorEl.createEl("span");
            title.textContent = errorTitle;
          } else {
            title = errorEl.createEl("a");
            this._addLink(title, file.path);
          }
          title.style.fontWeight = "bold";
          const errorDescriptionEl = errorEl.createEl("div");
          import_obsidian44.MarkdownRenderer.renderMarkdown(error.showErrorActions(), errorDescriptionEl, file.path, null);
          const errorLinksEl = errorDescriptionEl.createEl("ul");
          const errorLinkEl = errorLinksEl.createEl("li");
          errorLinkEl.createEl("a", { href: "#", text: "Fix the issue" });
        });
      }
      const closeButtonEl = this.contentEl.createEl("button", { text: "Close" });
      closeButtonEl.addEventListener("click", () => {
        this.app.workspace.detachLeavesOfType("rpgm-error-view" /* Errors */.toString());
      });
    });
  }
  _addLink(contentEl, linkOrFile) {
    let file;
    if (linkOrFile instanceof import_obsidian44.TFile) {
      file = linkOrFile;
      linkOrFile = file.basename;
    } else {
      file = this.app.vault.getAbstractFileByPath(linkOrFile);
    }
    if (file != null) {
      contentEl.textContent = file.basename;
      contentEl.style.textDecoration = "underlined";
      contentEl.addEventListener("click", () => {
        this.app.workspace.getLeaf(false).openFile(file);
      });
    }
  }
};

// src/core/staticViews/timelineView/TimelineView.ts
var import_obsidian45 = require("obsidian");

// src/core/staticViews/timelineView/TimelineElement.ts
var TimelineElement = class {
  constructor(fullDate, date, time, type, synopsis, link) {
    this.fullDate = fullDate;
    this.date = date;
    this.time = time;
    this.type = type;
    this.synopsis = synopsis;
    this.link = link;
  }
};

// src/core/staticViews/timelineView/TimelineView.ts
var TimelineView = class extends AbstractStaticView {
  constructor(api, leaf) {
    super(api, leaf);
    this.viewType = "rpgm-timeline-view" /* Timeline */.toString();
    this.displayText = "RPG Manager Timeline";
    this.icon = "d20";
  }
  initialise(params) {
    this._campaignId = params[0];
    this._campaign = this.api.database.readById(this._campaignId.id);
    super.initialise([]);
    this._elements = [];
    this.api.database.read((event) => event.index.type === 256 /* Event */ && event.index.campaignId === this._campaignId.id && event.date != null).forEach((event) => {
      var _a, _b;
      if (event.date !== void 0) {
        let time = "";
        if (!event.date.isFantasyCalendar) {
          time = event.date.date.toLocaleTimeString();
          time = time.substring(0, time.length - 3);
        }
        this._elements.push(new TimelineElement(event.date.date, (_a = this.api.service(DateService).getReadableDate(event.date, event)) != null ? _a : "", time, "event", (_b = event.synopsis) != null ? _b : "", event.file.path));
      }
    });
    this.api.database.read((clue) => clue.index.type === 512 /* Clue */ && clue.index.campaignId === this._campaignId.id && clue.found != null).forEach((clue) => {
      var _a, _b;
      if (clue.found != null) {
        const clueFound = clue.found.date;
        this._elements.push(new TimelineElement(clueFound, (_a = this.api.service(DateService).getReadableDate(clue.found, clue)) != null ? _a : "", "00:00", "clue", (_b = clue.synopsis) != null ? _b : "", clue.file.path));
      }
    });
    this.api.database.read((character) => ((32 /* Character */ | 64 /* NonPlayerCharacter */) & character.index.type) === character.index.type && character.index.campaignId === this._campaignId.id && character.death != null).forEach((character) => {
      var _a, _b;
      if (character.death !== void 0) {
        this._elements.push(new TimelineElement(character.death.date, (_a = this.api.service(DateService).getReadableDate(character.death, character)) != null ? _a : "", "00:00", "death", (_b = character.synopsis) != null ? _b : "", character.file.path));
      }
    });
    const sessions = this.api.database.read((session) => 16 /* Session */ === session.index.type && session.index.campaignId === this._campaignId.id);
    sessions.forEach((session) => {
      var _a, _b, _c;
      const scenes = this.api.database.read((scene) => {
        var _a2;
        return scene.index.type === 8 /* Scene */ && scene.index.campaignId === this._campaignId.id && ((_a2 = scene.session) == null ? void 0 : _a2.index.id) === session.index.id && scene.date != null;
      }).sort(this.api.service(SorterService).create([
        new SorterComparisonElement((scene) => scene.date)
      ]));
      const sessionDate = (_a = scenes[0]) == null ? void 0 : _a.date;
      if (sessionDate != null) {
        this._elements.push(new TimelineElement(sessionDate.date, (_b = this.api.service(DateService).getReadableDate(sessionDate, session)) != null ? _b : "", "00:00", "session", (_c = session.synopsis) != null ? _c : "", session.file.path));
      }
    });
    if (this._campaign.calendar === 0 /* Gregorian */) {
      this._elements.sort(this.api.service(SorterService).create([
        new SorterComparisonElement((data) => data.fullDate)
      ]));
    } else {
      this._elements.sort(this.api.service(SorterService).create([
        new FantasyCalendarSorterComparisonElement((data) => data.fullDate)
      ]));
    }
  }
  render() {
    return __async(this, null, function* () {
      var _a;
      this.rpgmContentEl.empty();
      if (this._campaign.images.length > 0) {
        const bannerContainer = this.rpgmContentEl.createDiv({ cls: "rpg-manager-timeline" });
        const header = bannerContainer.createDiv({ cls: "rpg-manager-timeline-header" });
        header.style.backgroundImage = "url('" + this._campaign.images[0].src + "')";
        const overlay = header.createDiv({ cls: "rpg-manager-timeline-header-overlay" });
        overlay.createDiv({ cls: "rpg-manager-timeline-header-overlay-title", text: "Timeline" });
        overlay.createDiv({ cls: "rpg-manager-timeline-header-overlay-name", text: this._campaign.file.basename });
        const campaignDate = (_a = this.api.service(DateService).getReadableDate(this._campaign.date, this._campaign)) != null ? _a : "";
        overlay.createDiv({ cls: "rpg-manager-timeline-header-overlay-date", text: campaignDate !== void 0 ? campaignDate : "" });
      } else {
        this.rpgmContentEl.createEl("h1", { text: this._campaign.file.basename });
      }
      const timelineEl = this.rpgmContentEl.createDiv({ cls: "rpg-manager-timeline-content" });
      const listEl = timelineEl.createEl("ul");
      this._elements.forEach((timeline) => {
        const itemEl = listEl.createEl("li", { cls: timeline.type });
        const contentEl = itemEl.createDiv({ cls: "rpg-manager-timeline-content-element" });
        contentEl.createEl("span", { cls: timeline.type, text: timeline.type.toString() + ": " + timeline.date + (timeline.time !== "00:00" ? " @ " + timeline.time : "") });
        const titleEl = contentEl.createEl("h3");
        const file = this.app.vault.getAbstractFileByPath(timeline.link);
        if (file !== null && file instanceof import_obsidian45.TFile) {
          titleEl.createEl("a", { text: file.basename, href: "#" }).addEventListener("click", () => {
            this.app.workspace.getLeaf(false).openFile(file);
          });
        }
        const descriptionEl = contentEl.createDiv();
        import_obsidian45.MarkdownRenderer.renderMarkdown(timeline.synopsis, descriptionEl, "", null);
        this.updateInternalLinks(descriptionEl);
      });
      return;
    });
  }
};

// src/main.ts
var RpgManager = class extends import_obsidian46.Plugin {
  constructor() {
    super(...arguments);
    this._isVersionUpdated = false;
    this.ready = false;
  }
  onload() {
    return __async(this, null, function* () {
      this.version = this.manifest.version;
      console.info("Loading RpgManager " + this.manifest.version);
      yield this.loadSettings();
      this.api = new RpgManagerApi(this.app, this);
      this.addSettingTab(new RpgManagerSettings(this.api));
      yield (0, import_obsidian46.addIcon)("d20", '<g cx="50" cy="50" r="50" fill="currentColor" g transform="translate(0.000000,0.000000) scale(0.018)" stroke="none"><path d="M1940 4358 l-612 -753 616 -3 c339 -1 893 -1 1232 0 l616 3 -612 753 c-337 413 -616 752 -620 752 -4 0 -283 -339 -620 -752z"/><path d="M1180 4389 c-399 -231 -731 -424 -739 -428 -9 -6 3 -17 40 -38 30 -17 152 -87 271 -156 l217 -126 476 585 c261 321 471 584 467 583 -4 0 -333 -189 -732 -420z"/><path d="M3676 4225 c457 -562 477 -585 498 -572 11 8 133 78 269 157 l249 143 -29 17 c-62 39 -1453 840 -1458 840 -2 0 210 -263 471 -585z"/><path d="M281 2833 c0 -472 4 -849 8 -838 24 58 520 1362 523 1373 3 12 -168 116 -474 291 l-58 32 1 -858z"/><path d="M4571 3536 c-145 -84 -264 -156 -264 -160 -1 -4 118 -320 263 -701 l265 -694 3 430 c1 237 1 621 0 854 l-3 424 -264 -153z"/><path d="M1272 3290 c7 -20 1283 -2229 1288 -2229 5 0 1281 2209 1288 2229 2 7 -451 10 -1288 10 -837 0 -1290 -3 -1288 -10z"/><path d="M1025 3079 c-2 -8 -158 -416 -345 -906 -187 -491 -340 -897 -340 -903 0 -5 4 -10 8 -10 5 0 415 -65 913 -145 497 -80 928 -149 957 -154 l52 -8 -23 41 c-85 150 -1202 2083 -1208 2090 -5 6 -10 3 -14 -5z"/><path d="M3470 2028 c-337 -585 -614 -1066 -616 -1069 -2 -3 7 -4 19 -2 12 2 445 71 962 154 517 82 941 152 943 154 3 2 -1 19 -7 37 -33 93 -675 1774 -681 1781 -4 4 -283 -471 -620 -1055z"/><path d="M955 842 c17 -11 336 -196 710 -412 374 -216 695 -401 713 -412 l32 -20 0 314 0 314 -707 113 c-390 62 -724 115 -743 118 l-35 5 30 -20z"/><path d="M3428 741 l-718 -116 0 -313 0 -314 33 20 c17 11 347 201 732 422 385 222 704 407 710 412 16 14 -22 8 -757 -111z"/></g>');
      yield (0, import_obsidian46.addIcon)("pieEighth", '<g transform="translate(3.000000,3.000000) scale(4.75)"><circle r="10" cx="10" cy="10" fill="transparent" stroke="black" stroke-width="0.5"/><circle r="5" cx="10" cy="10" fill="transparent" stroke="black" stroke-width="10" stroke-dasharray="calc(12.5 * 31.4 / 100) 31.4" transform="rotate(-90) translate(-20)" /></g>');
      yield (0, import_obsidian46.addIcon)("openClose", '<g transform="translate(40.000000,40.000000) scale(0.06)"><path d="M207,990V10L793,500.8L207,990L207,990z"/></g>');
      this.registerView("rpgm-error-view" /* Errors */.toString(), (leaf) => new ErrorView(this.api, leaf));
      this.registerView("rpgm-release-note-view" /* ReleaseNote */.toString(), (leaf) => new ReleaseNoteView(this.api, leaf));
      this.registerView("rpgm-creator-view" /* RPGManager */.toString(), (leaf) => new RPGManagerView(this.api, leaf));
      this.registerView("rpgm-timeline-view" /* Timeline */.toString(), (leaf) => new TimelineView(this.api, leaf));
      this.addRibbonIcon("d20", "RPG Manager", () => {
        this.api.staticViews.create("rpgm-creator-view" /* RPGManager */);
      });
      app.workspace.onLayoutReady(this.onLayoutReady.bind(this));
    });
  }
  onLayoutReady() {
    return __async(this, null, function* () {
      this.api.bootstrap();
      (window["RpgManagerAPI"] = this.api) && this.register(() => delete window["RpgManagerAPI"]);
      this.app.workspace.detachLeavesOfType("rpgm-error-view" /* Errors */.toString());
      this.app.workspace.detachLeavesOfType("rpgm-release-note-view" /* ReleaseNote */.toString());
      this.app.workspace.detachLeavesOfType("rpgm-creator-view" /* RPGManager */.toString());
      this.app.workspace.detachLeavesOfType("rpgm-timeline-view" /* Timeline */.toString());
      let requiresUpdate = false;
      if (this.settings.previousVersion !== this.manifest.version) {
        const databaseUpdater = yield new DatabaseUpdater(this.api, this.settings.previousVersion, this.manifest.version);
        if (yield databaseUpdater.requiresDatabaseUpdate()) {
          requiresUpdate = true;
          new UpdaterModal(this.api, databaseUpdater).open();
        }
      }
      if (!requiresUpdate)
        this.initialise();
    });
  }
  initialise() {
    return __async(this, null, function* () {
      this._registerCodeBlock();
      this._registerCommands();
      this.registerEvent(this.api.app.workspace.on("rpgmanager:database-ready", this._onDatabaseReady.bind(this)));
      DatabaseInitialiser.initialise(this.api).then((database) => {
        this.api.database = database;
        return;
      });
    });
  }
  _onDatabaseReady() {
    return __async(this, null, function* () {
      this.api.service(LoggerService).info(4 /* DatabaseInitialisation */, "Database Ready", this.api.database);
      this._registerEvents();
      this.app.workspace.trigger("rpgmanager:refresh-views");
      if (this._isVersionUpdated) {
        this.api.staticViews.create("rpgm-release-note-view" /* ReleaseNote */);
      } else {
        this.app.workspace.detachLeavesOfType("rpgm-release-note-view" /* ReleaseNote */.toString());
      }
    });
  }
  onunload() {
    return __async(this, null, function* () {
      __superGet(RpgManager.prototype, this, "onunload").call(this);
      this.app.workspace.detachLeavesOfType("rpgm-error-view" /* Errors */.toString());
      this.app.workspace.detachLeavesOfType("rpgm-release-note-view" /* ReleaseNote */.toString());
      this.app.workspace.detachLeavesOfType("rpgm-creator-view" /* RPGManager */.toString());
      this.app.workspace.off("resolved", this.refreshViews);
      this.app.workspace.off("modify", this.refreshViews);
    });
  }
  refreshViews() {
    this.app.workspace.trigger("rpgmanager:refresh-views");
  }
  createRpgView(source, el, component, sourcePath) {
    return __async(this, null, function* () {
      component.addChild(this.api.controllers.create(el, source, component, sourcePath));
    });
  }
  createRpgDataView(rpgm, el) {
    return __async(this, null, function* () {
      (0, import_obsidian46.setIcon)(el, "d20");
      el.style.cursor = "pointer";
      el.addEventListener("click", () => {
        this.api.service(CodeblockService).selectRpgManagerData();
      });
    });
  }
  loadSettings() {
    return __async(this, null, function* () {
      this.settings = Object.assign({}, rpgManagerDefaultSettings, yield this.loadData());
    });
  }
  updateSettings(settings, partial = true) {
    return __async(this, null, function* () {
      if (partial) {
        Object.assign(this.settings, settings);
      } else {
        this.settings = settings;
      }
      yield this.saveData(this.settings);
    });
  }
  _registerEvents() {
    this.registerEvent(this.app.metadataCache.on("resolved", this.refreshViews.bind(this)));
    this.registerEvent(this.app.workspace.on("file-open", this.refreshViews.bind(this)));
  }
  _registerCodeBlock() {
    this.registerMarkdownCodeBlockProcessor("RpgManager", (source, el, ctx) => __async(this, null, function* () {
      return this.createRpgView(source, el, ctx, ctx.sourcePath);
    }));
    this.registerMarkdownCodeBlockProcessor("RpgManagerData", (source, el, ctx) => __async(this, null, function* () {
      return this.createRpgDataView(this, el);
    }));
    this.registerMarkdownCodeBlockProcessor("RpgManagerID", (source, el, ctx) => __async(this, null, function* () {
    }));
  }
  _registerCommands() {
    this.registerEvent(this.app.workspace.on("editor-menu", (menu, editor, view) => {
      const cursor = editor.getCursor();
      const lineBefore = editor.getLine(cursor.line).substring(0, cursor.ch);
      const lastOpen = lineBefore.lastIndexOf("[[");
      const lastClosed = lineBefore.lastIndexOf("]]");
      if (lastOpen !== -1 && (lastClosed === -1 || lastClosed < lastOpen)) {
        const lineAfter = editor.getLine(cursor.line).substring(cursor.ch);
        const firstOpen = lineAfter.indexOf("[[");
        const firstClosed = lineAfter.indexOf("]]");
        if (firstClosed !== -1 || firstClosed < firstOpen) {
          const selectedBaseName = lineBefore.substring(lastOpen + 2) + lineAfter.substring(0, firstClosed);
          const files = this.app.vault.getMarkdownFiles();
          let fileExists = false;
          for (let index = 0; index < files.length; index++) {
            if (files[index].basename === selectedBaseName) {
              fileExists = true;
              break;
            }
          }
          if (!fileExists) {
            menu.addSeparator();
            Object.keys(ComponentType).filter((v) => isNaN(Number(v))).forEach((type, index) => {
              menu.addItem((item) => {
                item.setTitle("Create new " + type).setIcon("dice").onClick(() => __async(this, null, function* () {
                  new CreationModal(this.api, ComponentType[type], true, selectedBaseName).open();
                }));
              });
            });
          }
        }
      }
    }));
    Object.keys(ComponentType).filter((v) => isNaN(Number(v))).forEach((type, index) => {
      this.addCommand({
        id: "rpg-manager-create-" + type.toLowerCase(),
        name: "Create a new " + type,
        callback: () => {
          new CreationModal(this.api, ComponentType[type]).open();
        }
      });
      this.addCommand({
        id: "rpg-manager-fill-" + type.toLowerCase(),
        name: "Fill with " + type,
        callback: () => {
          let name = null;
          const activeFile = app.workspace.getActiveFile();
          if (activeFile != null) {
            name = activeFile.basename;
          }
          new CreationModal(this.api, ComponentType[type], false, name).open();
        }
      });
    });
  }
};
