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

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
var __commonJS = (cb, mod) => function __require() {
  try {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  } catch (e) {
    throw mod = 0, e;
  }
};
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 key2 of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key2) && key2 !== except)
        __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);

// node_modules/crypto-js/core.js
var require_core = __commonJS({
  "node_modules/crypto-js/core.js"(exports2, module2) {
    (function(root22, factory) {
      if (typeof exports2 === "object") {
        module2.exports = exports2 = factory();
      } else if (typeof define === "function" && define.amd) {
        define([], factory);
      } else {
        root22.CryptoJS = factory();
      }
    })(exports2, function() {
      var CryptoJS = CryptoJS || (function(Math2, undefined2) {
        var crypto2;
        if (typeof window !== "undefined" && window.crypto) {
          crypto2 = window.crypto;
        }
        if (typeof self !== "undefined" && self.crypto) {
          crypto2 = self.crypto;
        }
        if (typeof globalThis !== "undefined" && globalThis.crypto) {
          crypto2 = globalThis.crypto;
        }
        if (!crypto2 && typeof window !== "undefined" && window.msCrypto) {
          crypto2 = window.msCrypto;
        }
        if (!crypto2 && typeof global !== "undefined" && global.crypto) {
          crypto2 = global.crypto;
        }
        if (!crypto2 && typeof require === "function") {
          try {
            crypto2 = require("crypto");
          } catch (err) {
          }
        }
        var cryptoSecureRandomInt = function() {
          if (crypto2) {
            if (typeof crypto2.getRandomValues === "function") {
              try {
                return crypto2.getRandomValues(new Uint32Array(1))[0];
              } catch (err) {
              }
            }
            if (typeof crypto2.randomBytes === "function") {
              try {
                return crypto2.randomBytes(4).readInt32LE();
              } catch (err) {
              }
            }
          }
          throw new Error("Native crypto module could not be used to get secure random number.");
        };
        var create = Object.create || /* @__PURE__ */ (function() {
          function F() {
          }
          return function(obj) {
            var subtype;
            F.prototype = obj;
            subtype = new F();
            F.prototype = null;
            return subtype;
          };
        })();
        var C = {};
        var C_lib = C.lib = {};
        var Base2 = C_lib.Base = /* @__PURE__ */ (function() {
          return {
            /**
             * Creates a new object that inherits from this object.
             *
             * @param {Object} overrides Properties to copy into the new object.
             *
             * @return {Object} The new object.
             *
             * @static
             *
             * @example
             *
             *     var MyType = CryptoJS.lib.Base.extend({
             *         field: 'value',
             *
             *         method: function () {
             *         }
             *     });
             */
            extend: function(overrides) {
              var subtype = create(this);
              if (overrides) {
                subtype.mixIn(overrides);
              }
              if (!subtype.hasOwnProperty("init") || this.init === subtype.init) {
                subtype.init = function() {
                  subtype.$super.init.apply(this, arguments);
                };
              }
              subtype.init.prototype = subtype;
              subtype.$super = this;
              return subtype;
            },
            /**
             * Extends this object and runs the init method.
             * Arguments to create() will be passed to init().
             *
             * @return {Object} The new object.
             *
             * @static
             *
             * @example
             *
             *     var instance = MyType.create();
             */
            create: function() {
              var instance = this.extend();
              instance.init.apply(instance, arguments);
              return instance;
            },
            /**
             * Initializes a newly created object.
             * Override this method to add some logic when your objects are created.
             *
             * @example
             *
             *     var MyType = CryptoJS.lib.Base.extend({
             *         init: function () {
             *             // ...
             *         }
             *     });
             */
            init: function() {
            },
            /**
             * Copies properties into this object.
             *
             * @param {Object} properties The properties to mix in.
             *
             * @example
             *
             *     MyType.mixIn({
             *         field: 'value'
             *     });
             */
            mixIn: function(properties) {
              for (var propertyName in properties) {
                if (properties.hasOwnProperty(propertyName)) {
                  this[propertyName] = properties[propertyName];
                }
              }
              if (properties.hasOwnProperty("toString")) {
                this.toString = properties.toString;
              }
            },
            /**
             * Creates a copy of this object.
             *
             * @return {Object} The clone.
             *
             * @example
             *
             *     var clone = instance.clone();
             */
            clone: function() {
              return this.init.prototype.extend(this);
            }
          };
        })();
        var WordArray = C_lib.WordArray = Base2.extend({
          /**
           * Initializes a newly created word array.
           *
           * @param {Array} words (Optional) An array of 32-bit words.
           * @param {number} sigBytes (Optional) The number of significant bytes in the words.
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.create();
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
           */
          init: function(words, sigBytes) {
            words = this.words = words || [];
            if (sigBytes != undefined2) {
              this.sigBytes = sigBytes;
            } else {
              this.sigBytes = words.length * 4;
            }
          },
          /**
           * Converts this word array to a string.
           *
           * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
           *
           * @return {string} The stringified word array.
           *
           * @example
           *
           *     var string = wordArray + '';
           *     var string = wordArray.toString();
           *     var string = wordArray.toString(CryptoJS.enc.Utf8);
           */
          toString: function(encoder) {
            return (encoder || Hex).stringify(this);
          },
          /**
           * Concatenates a word array to this word array.
           *
           * @param {WordArray} wordArray The word array to append.
           *
           * @return {WordArray} This word array.
           *
           * @example
           *
           *     wordArray1.concat(wordArray2);
           */
          concat: function(wordArray) {
            var thisWords = this.words;
            var thatWords = wordArray.words;
            var thisSigBytes = this.sigBytes;
            var thatSigBytes = wordArray.sigBytes;
            this.clamp();
            if (thisSigBytes % 4) {
              for (var i = 0; i < thatSigBytes; i++) {
                var thatByte = thatWords[i >>> 2] >>> 24 - i % 4 * 8 & 255;
                thisWords[thisSigBytes + i >>> 2] |= thatByte << 24 - (thisSigBytes + i) % 4 * 8;
              }
            } else {
              for (var j = 0; j < thatSigBytes; j += 4) {
                thisWords[thisSigBytes + j >>> 2] = thatWords[j >>> 2];
              }
            }
            this.sigBytes += thatSigBytes;
            return this;
          },
          /**
           * Removes insignificant bits.
           *
           * @example
           *
           *     wordArray.clamp();
           */
          clamp: function() {
            var words = this.words;
            var sigBytes = this.sigBytes;
            words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8;
            words.length = Math2.ceil(sigBytes / 4);
          },
          /**
           * Creates a copy of this word array.
           *
           * @return {WordArray} The clone.
           *
           * @example
           *
           *     var clone = wordArray.clone();
           */
          clone: function() {
            var clone = Base2.clone.call(this);
            clone.words = this.words.slice(0);
            return clone;
          },
          /**
           * Creates a word array filled with random bytes.
           *
           * @param {number} nBytes The number of random bytes to generate.
           *
           * @return {WordArray} The random word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.random(16);
           */
          random: function(nBytes) {
            var words = [];
            for (var i = 0; i < nBytes; i += 4) {
              words.push(cryptoSecureRandomInt());
            }
            return new WordArray.init(words, nBytes);
          }
        });
        var C_enc = C.enc = {};
        var Hex = C_enc.Hex = {
          /**
           * Converts a word array to a hex string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The hex string.
           *
           * @static
           *
           * @example
           *
           *     var hexString = CryptoJS.enc.Hex.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var hexChars = [];
            for (var i = 0; i < sigBytes; i++) {
              var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
              hexChars.push((bite >>> 4).toString(16));
              hexChars.push((bite & 15).toString(16));
            }
            return hexChars.join("");
          },
          /**
           * Converts a hex string to a word array.
           *
           * @param {string} hexStr The hex string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Hex.parse(hexString);
           */
          parse: function(hexStr) {
            var hexStrLength = hexStr.length;
            var words = [];
            for (var i = 0; i < hexStrLength; i += 2) {
              words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << 24 - i % 8 * 4;
            }
            return new WordArray.init(words, hexStrLength / 2);
          }
        };
        var Latin1 = C_enc.Latin1 = {
          /**
           * Converts a word array to a Latin1 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Latin1 string.
           *
           * @static
           *
           * @example
           *
           *     var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var latin1Chars = [];
            for (var i = 0; i < sigBytes; i++) {
              var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
              latin1Chars.push(String.fromCharCode(bite));
            }
            return latin1Chars.join("");
          },
          /**
           * Converts a Latin1 string to a word array.
           *
           * @param {string} latin1Str The Latin1 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
           */
          parse: function(latin1Str) {
            var latin1StrLength = latin1Str.length;
            var words = [];
            for (var i = 0; i < latin1StrLength; i++) {
              words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8;
            }
            return new WordArray.init(words, latin1StrLength);
          }
        };
        var Utf8 = C_enc.Utf8 = {
          /**
           * Converts a word array to a UTF-8 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-8 string.
           *
           * @static
           *
           * @example
           *
           *     var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
           */
          stringify: function(wordArray) {
            try {
              return decodeURIComponent(escape(Latin1.stringify(wordArray)));
            } catch (e) {
              throw new Error("Malformed UTF-8 data");
            }
          },
          /**
           * Converts a UTF-8 string to a word array.
           *
           * @param {string} utf8Str The UTF-8 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
           */
          parse: function(utf8Str) {
            return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
          }
        };
        var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base2.extend({
          /**
           * Resets this block algorithm's data buffer to its initial state.
           *
           * @example
           *
           *     bufferedBlockAlgorithm.reset();
           */
          reset: function() {
            this._data = new WordArray.init();
            this._nDataBytes = 0;
          },
          /**
           * Adds new data to this block algorithm's buffer.
           *
           * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
           *
           * @example
           *
           *     bufferedBlockAlgorithm._append('data');
           *     bufferedBlockAlgorithm._append(wordArray);
           */
          _append: function(data) {
            if (typeof data == "string") {
              data = Utf8.parse(data);
            }
            this._data.concat(data);
            this._nDataBytes += data.sigBytes;
          },
          /**
           * Processes available data blocks.
           *
           * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
           *
           * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
           *
           * @return {WordArray} The processed data.
           *
           * @example
           *
           *     var processedData = bufferedBlockAlgorithm._process();
           *     var processedData = bufferedBlockAlgorithm._process(!!'flush');
           */
          _process: function(doFlush) {
            var processedWords;
            var data = this._data;
            var dataWords = data.words;
            var dataSigBytes = data.sigBytes;
            var blockSize = this.blockSize;
            var blockSizeBytes = blockSize * 4;
            var nBlocksReady = dataSigBytes / blockSizeBytes;
            if (doFlush) {
              nBlocksReady = Math2.ceil(nBlocksReady);
            } else {
              nBlocksReady = Math2.max((nBlocksReady | 0) - this._minBufferSize, 0);
            }
            var nWordsReady = nBlocksReady * blockSize;
            var nBytesReady = Math2.min(nWordsReady * 4, dataSigBytes);
            if (nWordsReady) {
              for (var offset3 = 0; offset3 < nWordsReady; offset3 += blockSize) {
                this._doProcessBlock(dataWords, offset3);
              }
              processedWords = dataWords.splice(0, nWordsReady);
              data.sigBytes -= nBytesReady;
            }
            return new WordArray.init(processedWords, nBytesReady);
          },
          /**
           * Creates a copy of this object.
           *
           * @return {Object} The clone.
           *
           * @example
           *
           *     var clone = bufferedBlockAlgorithm.clone();
           */
          clone: function() {
            var clone = Base2.clone.call(this);
            clone._data = this._data.clone();
            return clone;
          },
          _minBufferSize: 0
        });
        var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
          /**
           * Configuration options.
           */
          cfg: Base2.extend(),
          /**
           * Initializes a newly created hasher.
           *
           * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
           *
           * @example
           *
           *     var hasher = CryptoJS.algo.SHA256.create();
           */
          init: function(cfg) {
            this.cfg = this.cfg.extend(cfg);
            this.reset();
          },
          /**
           * Resets this hasher to its initial state.
           *
           * @example
           *
           *     hasher.reset();
           */
          reset: function() {
            BufferedBlockAlgorithm.reset.call(this);
            this._doReset();
          },
          /**
           * Updates this hasher with a message.
           *
           * @param {WordArray|string} messageUpdate The message to append.
           *
           * @return {Hasher} This hasher.
           *
           * @example
           *
           *     hasher.update('message');
           *     hasher.update(wordArray);
           */
          update: function(messageUpdate) {
            this._append(messageUpdate);
            this._process();
            return this;
          },
          /**
           * Finalizes the hash computation.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} messageUpdate (Optional) A final message update.
           *
           * @return {WordArray} The hash.
           *
           * @example
           *
           *     var hash = hasher.finalize();
           *     var hash = hasher.finalize('message');
           *     var hash = hasher.finalize(wordArray);
           */
          finalize: function(messageUpdate) {
            if (messageUpdate) {
              this._append(messageUpdate);
            }
            var hash2 = this._doFinalize();
            return hash2;
          },
          blockSize: 512 / 32,
          /**
           * Creates a shortcut function to a hasher's object interface.
           *
           * @param {Hasher} hasher The hasher to create a helper for.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
           */
          _createHelper: function(hasher) {
            return function(message, cfg) {
              return new hasher.init(cfg).finalize(message);
            };
          },
          /**
           * Creates a shortcut function to the HMAC's object interface.
           *
           * @param {Hasher} hasher The hasher to use in this HMAC helper.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
           */
          _createHmacHelper: function(hasher) {
            return function(message, key2) {
              return new C_algo.HMAC.init(hasher, key2).finalize(message);
            };
          }
        });
        var C_algo = C.algo = {};
        return C;
      })(Math);
      return CryptoJS;
    });
  }
});

// node_modules/crypto-js/sha256.js
var require_sha256 = __commonJS({
  "node_modules/crypto-js/sha256.js"(exports2, module2) {
    (function(root22, factory) {
      if (typeof exports2 === "object") {
        module2.exports = exports2 = factory(require_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root22.CryptoJS);
      }
    })(exports2, function(CryptoJS) {
      (function(Math2) {
        var C = CryptoJS;
        var C_lib = C.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C.algo;
        var H = [];
        var K = [];
        (function() {
          function isPrime(n2) {
            var sqrtN = Math2.sqrt(n2);
            for (var factor = 2; factor <= sqrtN; factor++) {
              if (!(n2 % factor)) {
                return false;
              }
            }
            return true;
          }
          function getFractionalBits(n2) {
            return (n2 - (n2 | 0)) * 4294967296 | 0;
          }
          var n = 2;
          var nPrime = 0;
          while (nPrime < 64) {
            if (isPrime(n)) {
              if (nPrime < 8) {
                H[nPrime] = getFractionalBits(Math2.pow(n, 1 / 2));
              }
              K[nPrime] = getFractionalBits(Math2.pow(n, 1 / 3));
              nPrime++;
            }
            n++;
          }
        })();
        var W = [];
        var SHA256 = C_algo.SHA256 = Hasher.extend({
          _doReset: function() {
            this._hash = new WordArray.init(H.slice(0));
          },
          _doProcessBlock: function(M, offset3) {
            var H2 = this._hash.words;
            var a = H2[0];
            var b = H2[1];
            var c = H2[2];
            var d = H2[3];
            var e = H2[4];
            var f = H2[5];
            var g = H2[6];
            var h = H2[7];
            for (var i = 0; i < 64; i++) {
              if (i < 16) {
                W[i] = M[offset3 + i] | 0;
              } else {
                var gamma0x = W[i - 15];
                var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
                var gamma1x = W[i - 2];
                var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
                W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
              }
              var ch = e & f ^ ~e & g;
              var maj = a & b ^ a & c ^ b & c;
              var sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22);
              var sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25);
              var t1 = h + sigma1 + ch + K[i] + W[i];
              var t2 = sigma0 + maj;
              h = g;
              g = f;
              f = e;
              e = d + t1 | 0;
              d = c;
              c = b;
              b = a;
              a = t1 + t2 | 0;
            }
            H2[0] = H2[0] + a | 0;
            H2[1] = H2[1] + b | 0;
            H2[2] = H2[2] + c | 0;
            H2[3] = H2[3] + d | 0;
            H2[4] = H2[4] + e | 0;
            H2[5] = H2[5] + f | 0;
            H2[6] = H2[6] + g | 0;
            H2[7] = H2[7] + h | 0;
          },
          _doFinalize: function() {
            var data = this._data;
            var dataWords = data.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math2.floor(nBitsTotal / 4294967296);
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
            data.sigBytes = dataWords.length * 4;
            this._process();
            return this._hash;
          },
          clone: function() {
            var clone = Hasher.clone.call(this);
            clone._hash = this._hash.clone();
            return clone;
          }
        });
        C.SHA256 = Hasher._createHelper(SHA256);
        C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
      })(Math);
      return CryptoJS.SHA256;
    });
  }
});

// node_modules/kind-of/index.js
var require_kind_of = __commonJS({
  "node_modules/kind-of/index.js"(exports2, module2) {
    var toString = Object.prototype.toString;
    module2.exports = function kindOf(val) {
      if (val === void 0) return "undefined";
      if (val === null) return "null";
      var type = typeof val;
      if (type === "boolean") return "boolean";
      if (type === "string") return "string";
      if (type === "number") return "number";
      if (type === "symbol") return "symbol";
      if (type === "function") {
        return isGeneratorFn(val) ? "generatorfunction" : "function";
      }
      if (isArray(val)) return "array";
      if (isBuffer(val)) return "buffer";
      if (isArguments(val)) return "arguments";
      if (isDate(val)) return "date";
      if (isError(val)) return "error";
      if (isRegexp(val)) return "regexp";
      switch (ctorName(val)) {
        case "Symbol":
          return "symbol";
        case "Promise":
          return "promise";
        // Set, Map, WeakSet, WeakMap
        case "WeakMap":
          return "weakmap";
        case "WeakSet":
          return "weakset";
        case "Map":
          return "map";
        case "Set":
          return "set";
        // 8-bit typed arrays
        case "Int8Array":
          return "int8array";
        case "Uint8Array":
          return "uint8array";
        case "Uint8ClampedArray":
          return "uint8clampedarray";
        // 16-bit typed arrays
        case "Int16Array":
          return "int16array";
        case "Uint16Array":
          return "uint16array";
        // 32-bit typed arrays
        case "Int32Array":
          return "int32array";
        case "Uint32Array":
          return "uint32array";
        case "Float32Array":
          return "float32array";
        case "Float64Array":
          return "float64array";
      }
      if (isGeneratorObj(val)) {
        return "generator";
      }
      type = toString.call(val);
      switch (type) {
        case "[object Object]":
          return "object";
        // iterators
        case "[object Map Iterator]":
          return "mapiterator";
        case "[object Set Iterator]":
          return "setiterator";
        case "[object String Iterator]":
          return "stringiterator";
        case "[object Array Iterator]":
          return "arrayiterator";
      }
      return type.slice(8, -1).toLowerCase().replace(/\s/g, "");
    };
    function ctorName(val) {
      return typeof val.constructor === "function" ? val.constructor.name : null;
    }
    function isArray(val) {
      if (Array.isArray) return Array.isArray(val);
      return val instanceof Array;
    }
    function isError(val) {
      return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
    }
    function isDate(val) {
      if (val instanceof Date) return true;
      return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
    }
    function isRegexp(val) {
      if (val instanceof RegExp) return true;
      return typeof val.flags === "string" && typeof val.ignoreCase === "boolean" && typeof val.multiline === "boolean" && typeof val.global === "boolean";
    }
    function isGeneratorFn(name, val) {
      return ctorName(name) === "GeneratorFunction";
    }
    function isGeneratorObj(val) {
      return typeof val.throw === "function" && typeof val.return === "function" && typeof val.next === "function";
    }
    function isArguments(val) {
      try {
        if (typeof val.length === "number" && typeof val.callee === "function") {
          return true;
        }
      } catch (err) {
        if (err.message.indexOf("callee") !== -1) {
          return true;
        }
      }
      return false;
    }
    function isBuffer(val) {
      if (val.constructor && typeof val.constructor.isBuffer === "function") {
        return val.constructor.isBuffer(val);
      }
      return false;
    }
  }
});

// node_modules/is-extendable/index.js
var require_is_extendable = __commonJS({
  "node_modules/is-extendable/index.js"(exports2, module2) {
    "use strict";
    module2.exports = function isExtendable(val) {
      return typeof val !== "undefined" && val !== null && (typeof val === "object" || typeof val === "function");
    };
  }
});

// node_modules/extend-shallow/index.js
var require_extend_shallow = __commonJS({
  "node_modules/extend-shallow/index.js"(exports2, module2) {
    "use strict";
    var isObject = require_is_extendable();
    module2.exports = function extend(o) {
      if (!isObject(o)) {
        o = {};
      }
      var len = arguments.length;
      for (var i = 1; i < len; i++) {
        var obj = arguments[i];
        if (isObject(obj)) {
          assign2(o, obj);
        }
      }
      return o;
    };
    function assign2(a, b) {
      for (var key2 in b) {
        if (hasOwn(b, key2)) {
          a[key2] = b[key2];
        }
      }
    }
    function hasOwn(obj, key2) {
      return Object.prototype.hasOwnProperty.call(obj, key2);
    }
  }
});

// node_modules/section-matter/index.js
var require_section_matter = __commonJS({
  "node_modules/section-matter/index.js"(exports2, module2) {
    "use strict";
    var typeOf = require_kind_of();
    var extend = require_extend_shallow();
    module2.exports = function(input, options2) {
      if (typeof options2 === "function") {
        options2 = { parse: options2 };
      }
      var file = toObject(input);
      var defaults = { section_delimiter: "---", parse: identity };
      var opts = extend({}, defaults, options2);
      var delim = opts.section_delimiter;
      var lines = file.content.split(/\r?\n/);
      var sections = null;
      var section = createSection();
      var content = [];
      var stack2 = [];
      function initSections(val) {
        file.content = val;
        sections = [];
        content = [];
      }
      function closeSection(val) {
        if (stack2.length) {
          section.key = getKey(stack2[0], delim);
          section.content = val;
          opts.parse(section, sections);
          sections.push(section);
          section = createSection();
          content = [];
          stack2 = [];
        }
      }
      for (var i = 0; i < lines.length; i++) {
        var line = lines[i];
        var len = stack2.length;
        var ln = line.trim();
        if (isDelimiter(ln, delim)) {
          if (ln.length === 3 && i !== 0) {
            if (len === 0 || len === 2) {
              content.push(line);
              continue;
            }
            stack2.push(ln);
            section.data = content.join("\n");
            content = [];
            continue;
          }
          if (sections === null) {
            initSections(content.join("\n"));
          }
          if (len === 2) {
            closeSection(content.join("\n"));
          }
          stack2.push(ln);
          continue;
        }
        content.push(line);
      }
      if (sections === null) {
        initSections(content.join("\n"));
      } else {
        closeSection(content.join("\n"));
      }
      file.sections = sections;
      return file;
    };
    function isDelimiter(line, delim) {
      if (line.slice(0, delim.length) !== delim) {
        return false;
      }
      if (line.charAt(delim.length + 1) === delim.slice(-1)) {
        return false;
      }
      return true;
    }
    function toObject(input) {
      if (typeOf(input) !== "object") {
        input = { content: input };
      }
      if (typeof input.content !== "string" && !isBuffer(input.content)) {
        throw new TypeError("expected a buffer or string");
      }
      input.content = input.content.toString();
      input.sections = [];
      return input;
    }
    function getKey(val, delim) {
      return val ? val.slice(delim.length).trim() : "";
    }
    function createSection() {
      return { key: "", data: "", content: "" };
    }
    function identity(val) {
      return val;
    }
    function isBuffer(val) {
      if (val && val.constructor && typeof val.constructor.isBuffer === "function") {
        return val.constructor.isBuffer(val);
      }
      return false;
    }
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/common.js
var require_common = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/common.js"(exports2, module2) {
    "use strict";
    function isNothing(subject) {
      return typeof subject === "undefined" || subject === null;
    }
    function isObject(subject) {
      return typeof subject === "object" && subject !== null;
    }
    function toArray(sequence) {
      if (Array.isArray(sequence)) return sequence;
      else if (isNothing(sequence)) return [];
      return [sequence];
    }
    function extend(target, source2) {
      var index2, length, key2, sourceKeys;
      if (source2) {
        sourceKeys = Object.keys(source2);
        for (index2 = 0, length = sourceKeys.length; index2 < length; index2 += 1) {
          key2 = sourceKeys[index2];
          target[key2] = source2[key2];
        }
      }
      return target;
    }
    function repeat(string, count) {
      var result = "", cycle;
      for (cycle = 0; cycle < count; cycle += 1) {
        result += string;
      }
      return result;
    }
    function isNegativeZero(number) {
      return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
    }
    module2.exports.isNothing = isNothing;
    module2.exports.isObject = isObject;
    module2.exports.toArray = toArray;
    module2.exports.repeat = repeat;
    module2.exports.isNegativeZero = isNegativeZero;
    module2.exports.extend = extend;
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/exception.js
var require_exception = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2, module2) {
    "use strict";
    function YAMLException(reason, mark) {
      Error.call(this);
      this.name = "YAMLException";
      this.reason = reason;
      this.mark = mark;
      this.message = (this.reason || "(unknown reason)") + (this.mark ? " " + this.mark.toString() : "");
      if (Error.captureStackTrace) {
        Error.captureStackTrace(this, this.constructor);
      } else {
        this.stack = new Error().stack || "";
      }
    }
    YAMLException.prototype = Object.create(Error.prototype);
    YAMLException.prototype.constructor = YAMLException;
    YAMLException.prototype.toString = function toString(compact) {
      var result = this.name + ": ";
      result += this.reason || "(unknown reason)";
      if (!compact && this.mark) {
        result += " " + this.mark.toString();
      }
      return result;
    };
    module2.exports = YAMLException;
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/mark.js
var require_mark = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2, module2) {
    "use strict";
    var common = require_common();
    function Mark(name, buffer, position, line, column) {
      this.name = name;
      this.buffer = buffer;
      this.position = position;
      this.line = line;
      this.column = column;
    }
    Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
      var head2, start, tail, end, snippet2;
      if (!this.buffer) return null;
      indent = indent || 4;
      maxLength = maxLength || 75;
      head2 = "";
      start = this.position;
      while (start > 0 && "\0\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(start - 1)) === -1) {
        start -= 1;
        if (this.position - start > maxLength / 2 - 1) {
          head2 = " ... ";
          start += 5;
          break;
        }
      }
      tail = "";
      end = this.position;
      while (end < this.buffer.length && "\0\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(end)) === -1) {
        end += 1;
        if (end - this.position > maxLength / 2 - 1) {
          tail = " ... ";
          end -= 5;
          break;
        }
      }
      snippet2 = this.buffer.slice(start, end);
      return common.repeat(" ", indent) + head2 + snippet2 + tail + "\n" + common.repeat(" ", indent + this.position - start + head2.length) + "^";
    };
    Mark.prototype.toString = function toString(compact) {
      var snippet2, where = "";
      if (this.name) {
        where += 'in "' + this.name + '" ';
      }
      where += "at line " + (this.line + 1) + ", column " + (this.column + 1);
      if (!compact) {
        snippet2 = this.getSnippet();
        if (snippet2) {
          where += ":\n" + snippet2;
        }
      }
      return where;
    };
    module2.exports = Mark;
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type.js
var require_type = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type.js"(exports2, module2) {
    "use strict";
    var YAMLException = require_exception();
    var TYPE_CONSTRUCTOR_OPTIONS = [
      "kind",
      "resolve",
      "construct",
      "instanceOf",
      "predicate",
      "represent",
      "defaultStyle",
      "styleAliases"
    ];
    var YAML_NODE_KINDS = [
      "scalar",
      "sequence",
      "mapping"
    ];
    function compileStyleAliases(map) {
      var result = {};
      if (map !== null) {
        Object.keys(map).forEach(function(style) {
          map[style].forEach(function(alias) {
            result[String(alias)] = style;
          });
        });
      }
      return result;
    }
    function Type(tag2, options2) {
      options2 = options2 || {};
      Object.keys(options2).forEach(function(name) {
        if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
          throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag2 + '" YAML type.');
        }
      });
      this.tag = tag2;
      this.kind = options2["kind"] || null;
      this.resolve = options2["resolve"] || function() {
        return true;
      };
      this.construct = options2["construct"] || function(data) {
        return data;
      };
      this.instanceOf = options2["instanceOf"] || null;
      this.predicate = options2["predicate"] || null;
      this.represent = options2["represent"] || null;
      this.defaultStyle = options2["defaultStyle"] || null;
      this.styleAliases = compileStyleAliases(options2["styleAliases"] || null);
      if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
        throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag2 + '" YAML type.');
      }
    }
    module2.exports = Type;
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema.js
var require_schema = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema.js"(exports2, module2) {
    "use strict";
    var common = require_common();
    var YAMLException = require_exception();
    var Type = require_type();
    function compileList(schema, name, result) {
      var exclude = [];
      schema.include.forEach(function(includedSchema) {
        result = compileList(includedSchema, name, result);
      });
      schema[name].forEach(function(currentType) {
        result.forEach(function(previousType, previousIndex) {
          if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
            exclude.push(previousIndex);
          }
        });
        result.push(currentType);
      });
      return result.filter(function(type, index2) {
        return exclude.indexOf(index2) === -1;
      });
    }
    function compileMap() {
      var result = {
        scalar: {},
        sequence: {},
        mapping: {},
        fallback: {}
      }, index2, length;
      function collectType(type) {
        result[type.kind][type.tag] = result["fallback"][type.tag] = type;
      }
      for (index2 = 0, length = arguments.length; index2 < length; index2 += 1) {
        arguments[index2].forEach(collectType);
      }
      return result;
    }
    function Schema(definition) {
      this.include = definition.include || [];
      this.implicit = definition.implicit || [];
      this.explicit = definition.explicit || [];
      this.implicit.forEach(function(type) {
        if (type.loadKind && type.loadKind !== "scalar") {
          throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
        }
      });
      this.compiledImplicit = compileList(this, "implicit", []);
      this.compiledExplicit = compileList(this, "explicit", []);
      this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
    }
    Schema.DEFAULT = null;
    Schema.create = function createSchema() {
      var schemas, types;
      switch (arguments.length) {
        case 1:
          schemas = Schema.DEFAULT;
          types = arguments[0];
          break;
        case 2:
          schemas = arguments[0];
          types = arguments[1];
          break;
        default:
          throw new YAMLException("Wrong number of arguments for Schema.create function");
      }
      schemas = common.toArray(schemas);
      types = common.toArray(types);
      if (!schemas.every(function(schema) {
        return schema instanceof Schema;
      })) {
        throw new YAMLException("Specified list of super schemas (or a single Schema object) contains a non-Schema object.");
      }
      if (!types.every(function(type) {
        return type instanceof Type;
      })) {
        throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");
      }
      return new Schema({
        include: schemas,
        explicit: types
      });
    };
    module2.exports = Schema;
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/str.js
var require_str = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/str.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    module2.exports = new Type("tag:yaml.org,2002:str", {
      kind: "scalar",
      construct: function(data) {
        return data !== null ? data : "";
      }
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/seq.js
var require_seq = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/seq.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    module2.exports = new Type("tag:yaml.org,2002:seq", {
      kind: "sequence",
      construct: function(data) {
        return data !== null ? data : [];
      }
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/map.js
var require_map = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/map.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    module2.exports = new Type("tag:yaml.org,2002:map", {
      kind: "mapping",
      construct: function(data) {
        return data !== null ? data : {};
      }
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js
var require_failsafe = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js"(exports2, module2) {
    "use strict";
    var Schema = require_schema();
    module2.exports = new Schema({
      explicit: [
        require_str(),
        require_seq(),
        require_map()
      ]
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/null.js
var require_null = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/null.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    function resolveYamlNull(data) {
      if (data === null) return true;
      var max2 = data.length;
      return max2 === 1 && data === "~" || max2 === 4 && (data === "null" || data === "Null" || data === "NULL");
    }
    function constructYamlNull() {
      return null;
    }
    function isNull(object) {
      return object === null;
    }
    module2.exports = new Type("tag:yaml.org,2002:null", {
      kind: "scalar",
      resolve: resolveYamlNull,
      construct: constructYamlNull,
      predicate: isNull,
      represent: {
        canonical: function() {
          return "~";
        },
        lowercase: function() {
          return "null";
        },
        uppercase: function() {
          return "NULL";
        },
        camelcase: function() {
          return "Null";
        }
      },
      defaultStyle: "lowercase"
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/bool.js
var require_bool = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/bool.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    function resolveYamlBoolean(data) {
      if (data === null) return false;
      var max2 = data.length;
      return max2 === 4 && (data === "true" || data === "True" || data === "TRUE") || max2 === 5 && (data === "false" || data === "False" || data === "FALSE");
    }
    function constructYamlBoolean(data) {
      return data === "true" || data === "True" || data === "TRUE";
    }
    function isBoolean(object) {
      return Object.prototype.toString.call(object) === "[object Boolean]";
    }
    module2.exports = new Type("tag:yaml.org,2002:bool", {
      kind: "scalar",
      resolve: resolveYamlBoolean,
      construct: constructYamlBoolean,
      predicate: isBoolean,
      represent: {
        lowercase: function(object) {
          return object ? "true" : "false";
        },
        uppercase: function(object) {
          return object ? "TRUE" : "FALSE";
        },
        camelcase: function(object) {
          return object ? "True" : "False";
        }
      },
      defaultStyle: "lowercase"
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/int.js
var require_int = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/int.js"(exports2, module2) {
    "use strict";
    var common = require_common();
    var Type = require_type();
    function isHexCode(c) {
      return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
    }
    function isOctCode(c) {
      return 48 <= c && c <= 55;
    }
    function isDecCode(c) {
      return 48 <= c && c <= 57;
    }
    function resolveYamlInteger(data) {
      if (data === null) return false;
      var max2 = data.length, index2 = 0, hasDigits = false, ch;
      if (!max2) return false;
      ch = data[index2];
      if (ch === "-" || ch === "+") {
        ch = data[++index2];
      }
      if (ch === "0") {
        if (index2 + 1 === max2) return true;
        ch = data[++index2];
        if (ch === "b") {
          index2++;
          for (; index2 < max2; index2++) {
            ch = data[index2];
            if (ch === "_") continue;
            if (ch !== "0" && ch !== "1") return false;
            hasDigits = true;
          }
          return hasDigits && ch !== "_";
        }
        if (ch === "x") {
          index2++;
          for (; index2 < max2; index2++) {
            ch = data[index2];
            if (ch === "_") continue;
            if (!isHexCode(data.charCodeAt(index2))) return false;
            hasDigits = true;
          }
          return hasDigits && ch !== "_";
        }
        for (; index2 < max2; index2++) {
          ch = data[index2];
          if (ch === "_") continue;
          if (!isOctCode(data.charCodeAt(index2))) return false;
          hasDigits = true;
        }
        return hasDigits && ch !== "_";
      }
      if (ch === "_") return false;
      for (; index2 < max2; index2++) {
        ch = data[index2];
        if (ch === "_") continue;
        if (ch === ":") break;
        if (!isDecCode(data.charCodeAt(index2))) {
          return false;
        }
        hasDigits = true;
      }
      if (!hasDigits || ch === "_") return false;
      if (ch !== ":") return true;
      return /^(:[0-5]?[0-9])+$/.test(data.slice(index2));
    }
    function constructYamlInteger(data) {
      var value = data, sign = 1, ch, base, digits = [];
      if (value.indexOf("_") !== -1) {
        value = value.replace(/_/g, "");
      }
      ch = value[0];
      if (ch === "-" || ch === "+") {
        if (ch === "-") sign = -1;
        value = value.slice(1);
        ch = value[0];
      }
      if (value === "0") return 0;
      if (ch === "0") {
        if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
        if (value[1] === "x") return sign * parseInt(value, 16);
        return sign * parseInt(value, 8);
      }
      if (value.indexOf(":") !== -1) {
        value.split(":").forEach(function(v) {
          digits.unshift(parseInt(v, 10));
        });
        value = 0;
        base = 1;
        digits.forEach(function(d) {
          value += d * base;
          base *= 60;
        });
        return sign * value;
      }
      return sign * parseInt(value, 10);
    }
    function isInteger(object) {
      return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));
    }
    module2.exports = new Type("tag:yaml.org,2002:int", {
      kind: "scalar",
      resolve: resolveYamlInteger,
      construct: constructYamlInteger,
      predicate: isInteger,
      represent: {
        binary: function(obj) {
          return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
        },
        octal: function(obj) {
          return obj >= 0 ? "0" + obj.toString(8) : "-0" + obj.toString(8).slice(1);
        },
        decimal: function(obj) {
          return obj.toString(10);
        },
        /* eslint-disable max-len */
        hexadecimal: function(obj) {
          return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
        }
      },
      defaultStyle: "decimal",
      styleAliases: {
        binary: [2, "bin"],
        octal: [8, "oct"],
        decimal: [10, "dec"],
        hexadecimal: [16, "hex"]
      }
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/float.js
var require_float = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/float.js"(exports2, module2) {
    "use strict";
    var common = require_common();
    var Type = require_type();
    var YAML_FLOAT_PATTERN = new RegExp(
      // 2.5e4, 2.5 and integers
      "^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
    );
    function resolveYamlFloat(data) {
      if (data === null) return false;
      if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
      // Probably should update regexp & check speed
      data[data.length - 1] === "_") {
        return false;
      }
      return true;
    }
    function constructYamlFloat(data) {
      var value, sign, base, digits;
      value = data.replace(/_/g, "").toLowerCase();
      sign = value[0] === "-" ? -1 : 1;
      digits = [];
      if ("+-".indexOf(value[0]) >= 0) {
        value = value.slice(1);
      }
      if (value === ".inf") {
        return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
      } else if (value === ".nan") {
        return NaN;
      } else if (value.indexOf(":") >= 0) {
        value.split(":").forEach(function(v) {
          digits.unshift(parseFloat(v, 10));
        });
        value = 0;
        base = 1;
        digits.forEach(function(d) {
          value += d * base;
          base *= 60;
        });
        return sign * value;
      }
      return sign * parseFloat(value, 10);
    }
    var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
    function representYamlFloat(object, style) {
      var res;
      if (isNaN(object)) {
        switch (style) {
          case "lowercase":
            return ".nan";
          case "uppercase":
            return ".NAN";
          case "camelcase":
            return ".NaN";
        }
      } else if (Number.POSITIVE_INFINITY === object) {
        switch (style) {
          case "lowercase":
            return ".inf";
          case "uppercase":
            return ".INF";
          case "camelcase":
            return ".Inf";
        }
      } else if (Number.NEGATIVE_INFINITY === object) {
        switch (style) {
          case "lowercase":
            return "-.inf";
          case "uppercase":
            return "-.INF";
          case "camelcase":
            return "-.Inf";
        }
      } else if (common.isNegativeZero(object)) {
        return "-0.0";
      }
      res = object.toString(10);
      return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
    }
    function isFloat(object) {
      return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));
    }
    module2.exports = new Type("tag:yaml.org,2002:float", {
      kind: "scalar",
      resolve: resolveYamlFloat,
      construct: constructYamlFloat,
      predicate: isFloat,
      represent: representYamlFloat,
      defaultStyle: "lowercase"
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/json.js
var require_json = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/json.js"(exports2, module2) {
    "use strict";
    var Schema = require_schema();
    module2.exports = new Schema({
      include: [
        require_failsafe()
      ],
      implicit: [
        require_null(),
        require_bool(),
        require_int(),
        require_float()
      ]
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/core.js
var require_core2 = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/core.js"(exports2, module2) {
    "use strict";
    var Schema = require_schema();
    module2.exports = new Schema({
      include: [
        require_json()
      ]
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/timestamp.js
var require_timestamp = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/timestamp.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    var YAML_DATE_REGEXP = new RegExp(
      "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
    );
    var YAML_TIMESTAMP_REGEXP = new RegExp(
      "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
    );
    function resolveYamlTimestamp(data) {
      if (data === null) return false;
      if (YAML_DATE_REGEXP.exec(data) !== null) return true;
      if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
      return false;
    }
    function constructYamlTimestamp(data) {
      var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
      match = YAML_DATE_REGEXP.exec(data);
      if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
      if (match === null) throw new Error("Date resolve error");
      year = +match[1];
      month = +match[2] - 1;
      day = +match[3];
      if (!match[4]) {
        return new Date(Date.UTC(year, month, day));
      }
      hour = +match[4];
      minute = +match[5];
      second = +match[6];
      if (match[7]) {
        fraction = match[7].slice(0, 3);
        while (fraction.length < 3) {
          fraction += "0";
        }
        fraction = +fraction;
      }
      if (match[9]) {
        tz_hour = +match[10];
        tz_minute = +(match[11] || 0);
        delta = (tz_hour * 60 + tz_minute) * 6e4;
        if (match[9] === "-") delta = -delta;
      }
      date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
      if (delta) date.setTime(date.getTime() - delta);
      return date;
    }
    function representYamlTimestamp(object) {
      return object.toISOString();
    }
    module2.exports = new Type("tag:yaml.org,2002:timestamp", {
      kind: "scalar",
      resolve: resolveYamlTimestamp,
      construct: constructYamlTimestamp,
      instanceOf: Date,
      represent: representYamlTimestamp
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/merge.js
var require_merge = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/merge.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    function resolveYamlMerge(data) {
      return data === "<<" || data === null;
    }
    module2.exports = new Type("tag:yaml.org,2002:merge", {
      kind: "scalar",
      resolve: resolveYamlMerge
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/binary.js
var require_binary = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/binary.js"(exports2, module2) {
    "use strict";
    var NodeBuffer;
    try {
      _require = require;
      NodeBuffer = _require("buffer").Buffer;
    } catch (__) {
    }
    var _require;
    var Type = require_type();
    var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
    function resolveYamlBinary(data) {
      if (data === null) return false;
      var code, idx, bitlen = 0, max2 = data.length, map = BASE64_MAP;
      for (idx = 0; idx < max2; idx++) {
        code = map.indexOf(data.charAt(idx));
        if (code > 64) continue;
        if (code < 0) return false;
        bitlen += 6;
      }
      return bitlen % 8 === 0;
    }
    function constructYamlBinary(data) {
      var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max2 = input.length, map = BASE64_MAP, bits = 0, result = [];
      for (idx = 0; idx < max2; idx++) {
        if (idx % 4 === 0 && idx) {
          result.push(bits >> 16 & 255);
          result.push(bits >> 8 & 255);
          result.push(bits & 255);
        }
        bits = bits << 6 | map.indexOf(input.charAt(idx));
      }
      tailbits = max2 % 4 * 6;
      if (tailbits === 0) {
        result.push(bits >> 16 & 255);
        result.push(bits >> 8 & 255);
        result.push(bits & 255);
      } else if (tailbits === 18) {
        result.push(bits >> 10 & 255);
        result.push(bits >> 2 & 255);
      } else if (tailbits === 12) {
        result.push(bits >> 4 & 255);
      }
      if (NodeBuffer) {
        return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
      }
      return result;
    }
    function representYamlBinary(object) {
      var result = "", bits = 0, idx, tail, max2 = object.length, map = BASE64_MAP;
      for (idx = 0; idx < max2; idx++) {
        if (idx % 3 === 0 && idx) {
          result += map[bits >> 18 & 63];
          result += map[bits >> 12 & 63];
          result += map[bits >> 6 & 63];
          result += map[bits & 63];
        }
        bits = (bits << 8) + object[idx];
      }
      tail = max2 % 3;
      if (tail === 0) {
        result += map[bits >> 18 & 63];
        result += map[bits >> 12 & 63];
        result += map[bits >> 6 & 63];
        result += map[bits & 63];
      } else if (tail === 2) {
        result += map[bits >> 10 & 63];
        result += map[bits >> 4 & 63];
        result += map[bits << 2 & 63];
        result += map[64];
      } else if (tail === 1) {
        result += map[bits >> 2 & 63];
        result += map[bits << 4 & 63];
        result += map[64];
        result += map[64];
      }
      return result;
    }
    function isBinary(object) {
      return NodeBuffer && NodeBuffer.isBuffer(object);
    }
    module2.exports = new Type("tag:yaml.org,2002:binary", {
      kind: "scalar",
      resolve: resolveYamlBinary,
      construct: constructYamlBinary,
      predicate: isBinary,
      represent: representYamlBinary
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/omap.js
var require_omap = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/omap.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    var _hasOwnProperty = Object.prototype.hasOwnProperty;
    var _toString = Object.prototype.toString;
    function resolveYamlOmap(data) {
      if (data === null) return true;
      var objectKeys = [], index2, length, pair, pairKey, pairHasKey, object = data;
      for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
        pair = object[index2];
        pairHasKey = false;
        if (_toString.call(pair) !== "[object Object]") return false;
        for (pairKey in pair) {
          if (_hasOwnProperty.call(pair, pairKey)) {
            if (!pairHasKey) pairHasKey = true;
            else return false;
          }
        }
        if (!pairHasKey) return false;
        if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
        else return false;
      }
      return true;
    }
    function constructYamlOmap(data) {
      return data !== null ? data : [];
    }
    module2.exports = new Type("tag:yaml.org,2002:omap", {
      kind: "sequence",
      resolve: resolveYamlOmap,
      construct: constructYamlOmap
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/pairs.js
var require_pairs = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/pairs.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    var _toString = Object.prototype.toString;
    function resolveYamlPairs(data) {
      if (data === null) return true;
      var index2, length, pair, keys, result, object = data;
      result = new Array(object.length);
      for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
        pair = object[index2];
        if (_toString.call(pair) !== "[object Object]") return false;
        keys = Object.keys(pair);
        if (keys.length !== 1) return false;
        result[index2] = [keys[0], pair[keys[0]]];
      }
      return true;
    }
    function constructYamlPairs(data) {
      if (data === null) return [];
      var index2, length, pair, keys, result, object = data;
      result = new Array(object.length);
      for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
        pair = object[index2];
        keys = Object.keys(pair);
        result[index2] = [keys[0], pair[keys[0]]];
      }
      return result;
    }
    module2.exports = new Type("tag:yaml.org,2002:pairs", {
      kind: "sequence",
      resolve: resolveYamlPairs,
      construct: constructYamlPairs
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/set.js
var require_set = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/set.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    var _hasOwnProperty = Object.prototype.hasOwnProperty;
    function resolveYamlSet(data) {
      if (data === null) return true;
      var key2, object = data;
      for (key2 in object) {
        if (_hasOwnProperty.call(object, key2)) {
          if (object[key2] !== null) return false;
        }
      }
      return true;
    }
    function constructYamlSet(data) {
      return data !== null ? data : {};
    }
    module2.exports = new Type("tag:yaml.org,2002:set", {
      kind: "mapping",
      resolve: resolveYamlSet,
      construct: constructYamlSet
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js
var require_default_safe = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js"(exports2, module2) {
    "use strict";
    var Schema = require_schema();
    module2.exports = new Schema({
      include: [
        require_core2()
      ],
      implicit: [
        require_timestamp(),
        require_merge()
      ],
      explicit: [
        require_binary(),
        require_omap(),
        require_pairs(),
        require_set()
      ]
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js
var require_undefined = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    function resolveJavascriptUndefined() {
      return true;
    }
    function constructJavascriptUndefined() {
      return void 0;
    }
    function representJavascriptUndefined() {
      return "";
    }
    function isUndefined(object) {
      return typeof object === "undefined";
    }
    module2.exports = new Type("tag:yaml.org,2002:js/undefined", {
      kind: "scalar",
      resolve: resolveJavascriptUndefined,
      construct: constructJavascriptUndefined,
      predicate: isUndefined,
      represent: representJavascriptUndefined
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js
var require_regexp = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js"(exports2, module2) {
    "use strict";
    var Type = require_type();
    function resolveJavascriptRegExp(data) {
      if (data === null) return false;
      if (data.length === 0) return false;
      var regexp = data, tail = /\/([gim]*)$/.exec(data), modifiers = "";
      if (regexp[0] === "/") {
        if (tail) modifiers = tail[1];
        if (modifiers.length > 3) return false;
        if (regexp[regexp.length - modifiers.length - 1] !== "/") return false;
      }
      return true;
    }
    function constructJavascriptRegExp(data) {
      var regexp = data, tail = /\/([gim]*)$/.exec(data), modifiers = "";
      if (regexp[0] === "/") {
        if (tail) modifiers = tail[1];
        regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
      }
      return new RegExp(regexp, modifiers);
    }
    function representJavascriptRegExp(object) {
      var result = "/" + object.source + "/";
      if (object.global) result += "g";
      if (object.multiline) result += "m";
      if (object.ignoreCase) result += "i";
      return result;
    }
    function isRegExp(object) {
      return Object.prototype.toString.call(object) === "[object RegExp]";
    }
    module2.exports = new Type("tag:yaml.org,2002:js/regexp", {
      kind: "scalar",
      resolve: resolveJavascriptRegExp,
      construct: constructJavascriptRegExp,
      predicate: isRegExp,
      represent: representJavascriptRegExp
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/function.js
var require_function = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/function.js"(exports2, module2) {
    "use strict";
    var esprima;
    try {
      _require = require;
      esprima = _require("esprima");
    } catch (_) {
      if (typeof window !== "undefined") esprima = window.esprima;
    }
    var _require;
    var Type = require_type();
    function resolveJavascriptFunction(data) {
      if (data === null) return false;
      try {
        var source2 = "(" + data + ")", ast = esprima.parse(source2, { range: true });
        if (ast.type !== "Program" || ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement" || ast.body[0].expression.type !== "ArrowFunctionExpression" && ast.body[0].expression.type !== "FunctionExpression") {
          return false;
        }
        return true;
      } catch (err) {
        return false;
      }
    }
    function constructJavascriptFunction(data) {
      var source2 = "(" + data + ")", ast = esprima.parse(source2, { range: true }), params = [], body;
      if (ast.type !== "Program" || ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement" || ast.body[0].expression.type !== "ArrowFunctionExpression" && ast.body[0].expression.type !== "FunctionExpression") {
        throw new Error("Failed to resolve function");
      }
      ast.body[0].expression.params.forEach(function(param) {
        params.push(param.name);
      });
      body = ast.body[0].expression.body.range;
      if (ast.body[0].expression.body.type === "BlockStatement") {
        return new Function(params, source2.slice(body[0] + 1, body[1] - 1));
      }
      return new Function(params, "return " + source2.slice(body[0], body[1]));
    }
    function representJavascriptFunction(object) {
      return object.toString();
    }
    function isFunction(object) {
      return Object.prototype.toString.call(object) === "[object Function]";
    }
    module2.exports = new Type("tag:yaml.org,2002:js/function", {
      kind: "scalar",
      resolve: resolveJavascriptFunction,
      construct: constructJavascriptFunction,
      predicate: isFunction,
      represent: representJavascriptFunction
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/default_full.js
var require_default_full = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/default_full.js"(exports2, module2) {
    "use strict";
    var Schema = require_schema();
    module2.exports = Schema.DEFAULT = new Schema({
      include: [
        require_default_safe()
      ],
      explicit: [
        require_undefined(),
        require_regexp(),
        require_function()
      ]
    });
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/loader.js
var require_loader = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/loader.js"(exports2, module2) {
    "use strict";
    var common = require_common();
    var YAMLException = require_exception();
    var Mark = require_mark();
    var DEFAULT_SAFE_SCHEMA = require_default_safe();
    var DEFAULT_FULL_SCHEMA = require_default_full();
    var _hasOwnProperty = Object.prototype.hasOwnProperty;
    var CONTEXT_FLOW_IN = 1;
    var CONTEXT_FLOW_OUT = 2;
    var CONTEXT_BLOCK_IN = 3;
    var CONTEXT_BLOCK_OUT = 4;
    var CHOMPING_CLIP = 1;
    var CHOMPING_STRIP = 2;
    var CHOMPING_KEEP = 3;
    var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
    var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
    var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
    var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
    var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
    function _class(obj) {
      return Object.prototype.toString.call(obj);
    }
    function is_EOL(c) {
      return c === 10 || c === 13;
    }
    function is_WHITE_SPACE(c) {
      return c === 9 || c === 32;
    }
    function is_WS_OR_EOL(c) {
      return c === 9 || c === 32 || c === 10 || c === 13;
    }
    function is_FLOW_INDICATOR(c) {
      return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
    }
    function fromHexCode(c) {
      var lc;
      if (48 <= c && c <= 57) {
        return c - 48;
      }
      lc = c | 32;
      if (97 <= lc && lc <= 102) {
        return lc - 97 + 10;
      }
      return -1;
    }
    function escapedHexLen(c) {
      if (c === 120) {
        return 2;
      }
      if (c === 117) {
        return 4;
      }
      if (c === 85) {
        return 8;
      }
      return 0;
    }
    function fromDecimalCode(c) {
      if (48 <= c && c <= 57) {
        return c - 48;
      }
      return -1;
    }
    function simpleEscapeSequence(c) {
      return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? "	" : c === 9 ? "	" : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : "";
    }
    function charFromCodepoint(c) {
      if (c <= 65535) {
        return String.fromCharCode(c);
      }
      return String.fromCharCode(
        (c - 65536 >> 10) + 55296,
        (c - 65536 & 1023) + 56320
      );
    }
    function setProperty(object, key2, value) {
      if (key2 === "__proto__") {
        Object.defineProperty(object, key2, {
          configurable: true,
          enumerable: true,
          writable: true,
          value
        });
      } else {
        object[key2] = value;
      }
    }
    var simpleEscapeCheck = new Array(256);
    var simpleEscapeMap = new Array(256);
    for (i = 0; i < 256; i++) {
      simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
      simpleEscapeMap[i] = simpleEscapeSequence(i);
    }
    var i;
    function State(input, options2) {
      this.input = input;
      this.filename = options2["filename"] || null;
      this.schema = options2["schema"] || DEFAULT_FULL_SCHEMA;
      this.onWarning = options2["onWarning"] || null;
      this.legacy = options2["legacy"] || false;
      this.json = options2["json"] || false;
      this.listener = options2["listener"] || null;
      this.implicitTypes = this.schema.compiledImplicit;
      this.typeMap = this.schema.compiledTypeMap;
      this.length = input.length;
      this.position = 0;
      this.line = 0;
      this.lineStart = 0;
      this.lineIndent = 0;
      this.documents = [];
    }
    function generateError(state2, message) {
      return new YAMLException(
        message,
        new Mark(state2.filename, state2.input, state2.position, state2.line, state2.position - state2.lineStart)
      );
    }
    function throwError(state2, message) {
      throw generateError(state2, message);
    }
    function throwWarning(state2, message) {
      if (state2.onWarning) {
        state2.onWarning.call(null, generateError(state2, message));
      }
    }
    var directiveHandlers = {
      YAML: function handleYamlDirective(state2, name, args) {
        var match, major, minor;
        if (state2.version !== null) {
          throwError(state2, "duplication of %YAML directive");
        }
        if (args.length !== 1) {
          throwError(state2, "YAML directive accepts exactly one argument");
        }
        match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
        if (match === null) {
          throwError(state2, "ill-formed argument of the YAML directive");
        }
        major = parseInt(match[1], 10);
        minor = parseInt(match[2], 10);
        if (major !== 1) {
          throwError(state2, "unacceptable YAML version of the document");
        }
        state2.version = args[0];
        state2.checkLineBreaks = minor < 2;
        if (minor !== 1 && minor !== 2) {
          throwWarning(state2, "unsupported YAML version of the document");
        }
      },
      TAG: function handleTagDirective(state2, name, args) {
        var handle, prefix;
        if (args.length !== 2) {
          throwError(state2, "TAG directive accepts exactly two arguments");
        }
        handle = args[0];
        prefix = args[1];
        if (!PATTERN_TAG_HANDLE.test(handle)) {
          throwError(state2, "ill-formed tag handle (first argument) of the TAG directive");
        }
        if (_hasOwnProperty.call(state2.tagMap, handle)) {
          throwError(state2, 'there is a previously declared suffix for "' + handle + '" tag handle');
        }
        if (!PATTERN_TAG_URI.test(prefix)) {
          throwError(state2, "ill-formed tag prefix (second argument) of the TAG directive");
        }
        state2.tagMap[handle] = prefix;
      }
    };
    function captureSegment(state2, start, end, checkJson) {
      var _position, _length, _character, _result;
      if (start < end) {
        _result = state2.input.slice(start, end);
        if (checkJson) {
          for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
            _character = _result.charCodeAt(_position);
            if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
              throwError(state2, "expected valid JSON character");
            }
          }
        } else if (PATTERN_NON_PRINTABLE.test(_result)) {
          throwError(state2, "the stream contains non-printable characters");
        }
        state2.result += _result;
      }
    }
    function mergeMappings(state2, destination, source2, overridableKeys) {
      var sourceKeys, key2, index2, quantity;
      if (!common.isObject(source2)) {
        throwError(state2, "cannot merge mappings; the provided source object is unacceptable");
      }
      sourceKeys = Object.keys(source2);
      for (index2 = 0, quantity = sourceKeys.length; index2 < quantity; index2 += 1) {
        key2 = sourceKeys[index2];
        if (!_hasOwnProperty.call(destination, key2)) {
          setProperty(destination, key2, source2[key2]);
          overridableKeys[key2] = true;
        }
      }
    }
    function storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
      var index2, quantity;
      if (Array.isArray(keyNode)) {
        keyNode = Array.prototype.slice.call(keyNode);
        for (index2 = 0, quantity = keyNode.length; index2 < quantity; index2 += 1) {
          if (Array.isArray(keyNode[index2])) {
            throwError(state2, "nested arrays are not supported inside keys");
          }
          if (typeof keyNode === "object" && _class(keyNode[index2]) === "[object Object]") {
            keyNode[index2] = "[object Object]";
          }
        }
      }
      if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
        keyNode = "[object Object]";
      }
      keyNode = String(keyNode);
      if (_result === null) {
        _result = {};
      }
      if (keyTag === "tag:yaml.org,2002:merge") {
        if (Array.isArray(valueNode)) {
          for (index2 = 0, quantity = valueNode.length; index2 < quantity; index2 += 1) {
            mergeMappings(state2, _result, valueNode[index2], overridableKeys);
          }
        } else {
          mergeMappings(state2, _result, valueNode, overridableKeys);
        }
      } else {
        if (!state2.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {
          state2.line = startLine || state2.line;
          state2.position = startPos || state2.position;
          throwError(state2, "duplicated mapping key");
        }
        setProperty(_result, keyNode, valueNode);
        delete overridableKeys[keyNode];
      }
      return _result;
    }
    function readLineBreak(state2) {
      var ch;
      ch = state2.input.charCodeAt(state2.position);
      if (ch === 10) {
        state2.position++;
      } else if (ch === 13) {
        state2.position++;
        if (state2.input.charCodeAt(state2.position) === 10) {
          state2.position++;
        }
      } else {
        throwError(state2, "a line break is expected");
      }
      state2.line += 1;
      state2.lineStart = state2.position;
    }
    function skipSeparationSpace(state2, allowComments, checkIndent) {
      var lineBreaks = 0, ch = state2.input.charCodeAt(state2.position);
      while (ch !== 0) {
        while (is_WHITE_SPACE(ch)) {
          ch = state2.input.charCodeAt(++state2.position);
        }
        if (allowComments && ch === 35) {
          do {
            ch = state2.input.charCodeAt(++state2.position);
          } while (ch !== 10 && ch !== 13 && ch !== 0);
        }
        if (is_EOL(ch)) {
          readLineBreak(state2);
          ch = state2.input.charCodeAt(state2.position);
          lineBreaks++;
          state2.lineIndent = 0;
          while (ch === 32) {
            state2.lineIndent++;
            ch = state2.input.charCodeAt(++state2.position);
          }
        } else {
          break;
        }
      }
      if (checkIndent !== -1 && lineBreaks !== 0 && state2.lineIndent < checkIndent) {
        throwWarning(state2, "deficient indentation");
      }
      return lineBreaks;
    }
    function testDocumentSeparator(state2) {
      var _position = state2.position, ch;
      ch = state2.input.charCodeAt(_position);
      if ((ch === 45 || ch === 46) && ch === state2.input.charCodeAt(_position + 1) && ch === state2.input.charCodeAt(_position + 2)) {
        _position += 3;
        ch = state2.input.charCodeAt(_position);
        if (ch === 0 || is_WS_OR_EOL(ch)) {
          return true;
        }
      }
      return false;
    }
    function writeFoldedLines(state2, count) {
      if (count === 1) {
        state2.result += " ";
      } else if (count > 1) {
        state2.result += common.repeat("\n", count - 1);
      }
    }
    function readPlainScalar(state2, nodeIndent, withinFlowCollection) {
      var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state2.kind, _result = state2.result, ch;
      ch = state2.input.charCodeAt(state2.position);
      if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
        return false;
      }
      if (ch === 63 || ch === 45) {
        following = state2.input.charCodeAt(state2.position + 1);
        if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
          return false;
        }
      }
      state2.kind = "scalar";
      state2.result = "";
      captureStart = captureEnd = state2.position;
      hasPendingContent = false;
      while (ch !== 0) {
        if (ch === 58) {
          following = state2.input.charCodeAt(state2.position + 1);
          if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
            break;
          }
        } else if (ch === 35) {
          preceding = state2.input.charCodeAt(state2.position - 1);
          if (is_WS_OR_EOL(preceding)) {
            break;
          }
        } else if (state2.position === state2.lineStart && testDocumentSeparator(state2) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
          break;
        } else if (is_EOL(ch)) {
          _line = state2.line;
          _lineStart = state2.lineStart;
          _lineIndent = state2.lineIndent;
          skipSeparationSpace(state2, false, -1);
          if (state2.lineIndent >= nodeIndent) {
            hasPendingContent = true;
            ch = state2.input.charCodeAt(state2.position);
            continue;
          } else {
            state2.position = captureEnd;
            state2.line = _line;
            state2.lineStart = _lineStart;
            state2.lineIndent = _lineIndent;
            break;
          }
        }
        if (hasPendingContent) {
          captureSegment(state2, captureStart, captureEnd, false);
          writeFoldedLines(state2, state2.line - _line);
          captureStart = captureEnd = state2.position;
          hasPendingContent = false;
        }
        if (!is_WHITE_SPACE(ch)) {
          captureEnd = state2.position + 1;
        }
        ch = state2.input.charCodeAt(++state2.position);
      }
      captureSegment(state2, captureStart, captureEnd, false);
      if (state2.result) {
        return true;
      }
      state2.kind = _kind;
      state2.result = _result;
      return false;
    }
    function readSingleQuotedScalar(state2, nodeIndent) {
      var ch, captureStart, captureEnd;
      ch = state2.input.charCodeAt(state2.position);
      if (ch !== 39) {
        return false;
      }
      state2.kind = "scalar";
      state2.result = "";
      state2.position++;
      captureStart = captureEnd = state2.position;
      while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
        if (ch === 39) {
          captureSegment(state2, captureStart, state2.position, true);
          ch = state2.input.charCodeAt(++state2.position);
          if (ch === 39) {
            captureStart = state2.position;
            state2.position++;
            captureEnd = state2.position;
          } else {
            return true;
          }
        } else if (is_EOL(ch)) {
          captureSegment(state2, captureStart, captureEnd, true);
          writeFoldedLines(state2, skipSeparationSpace(state2, false, nodeIndent));
          captureStart = captureEnd = state2.position;
        } else if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
          throwError(state2, "unexpected end of the document within a single quoted scalar");
        } else {
          state2.position++;
          captureEnd = state2.position;
        }
      }
      throwError(state2, "unexpected end of the stream within a single quoted scalar");
    }
    function readDoubleQuotedScalar(state2, nodeIndent) {
      var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
      ch = state2.input.charCodeAt(state2.position);
      if (ch !== 34) {
        return false;
      }
      state2.kind = "scalar";
      state2.result = "";
      state2.position++;
      captureStart = captureEnd = state2.position;
      while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
        if (ch === 34) {
          captureSegment(state2, captureStart, state2.position, true);
          state2.position++;
          return true;
        } else if (ch === 92) {
          captureSegment(state2, captureStart, state2.position, true);
          ch = state2.input.charCodeAt(++state2.position);
          if (is_EOL(ch)) {
            skipSeparationSpace(state2, false, nodeIndent);
          } else if (ch < 256 && simpleEscapeCheck[ch]) {
            state2.result += simpleEscapeMap[ch];
            state2.position++;
          } else if ((tmp = escapedHexLen(ch)) > 0) {
            hexLength = tmp;
            hexResult = 0;
            for (; hexLength > 0; hexLength--) {
              ch = state2.input.charCodeAt(++state2.position);
              if ((tmp = fromHexCode(ch)) >= 0) {
                hexResult = (hexResult << 4) + tmp;
              } else {
                throwError(state2, "expected hexadecimal character");
              }
            }
            state2.result += charFromCodepoint(hexResult);
            state2.position++;
          } else {
            throwError(state2, "unknown escape sequence");
          }
          captureStart = captureEnd = state2.position;
        } else if (is_EOL(ch)) {
          captureSegment(state2, captureStart, captureEnd, true);
          writeFoldedLines(state2, skipSeparationSpace(state2, false, nodeIndent));
          captureStart = captureEnd = state2.position;
        } else if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
          throwError(state2, "unexpected end of the document within a double quoted scalar");
        } else {
          state2.position++;
          captureEnd = state2.position;
        }
      }
      throwError(state2, "unexpected end of the stream within a double quoted scalar");
    }
    function readFlowCollection(state2, nodeIndent) {
      var readNext = true, _line, _tag = state2.tag, _result, _anchor2 = state2.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = {}, keyNode, keyTag, valueNode, ch;
      ch = state2.input.charCodeAt(state2.position);
      if (ch === 91) {
        terminator = 93;
        isMapping = false;
        _result = [];
      } else if (ch === 123) {
        terminator = 125;
        isMapping = true;
        _result = {};
      } else {
        return false;
      }
      if (state2.anchor !== null) {
        state2.anchorMap[state2.anchor] = _result;
      }
      ch = state2.input.charCodeAt(++state2.position);
      while (ch !== 0) {
        skipSeparationSpace(state2, true, nodeIndent);
        ch = state2.input.charCodeAt(state2.position);
        if (ch === terminator) {
          state2.position++;
          state2.tag = _tag;
          state2.anchor = _anchor2;
          state2.kind = isMapping ? "mapping" : "sequence";
          state2.result = _result;
          return true;
        } else if (!readNext) {
          throwError(state2, "missed comma between flow collection entries");
        }
        keyTag = keyNode = valueNode = null;
        isPair = isExplicitPair = false;
        if (ch === 63) {
          following = state2.input.charCodeAt(state2.position + 1);
          if (is_WS_OR_EOL(following)) {
            isPair = isExplicitPair = true;
            state2.position++;
            skipSeparationSpace(state2, true, nodeIndent);
          }
        }
        _line = state2.line;
        composeNode(state2, nodeIndent, CONTEXT_FLOW_IN, false, true);
        keyTag = state2.tag;
        keyNode = state2.result;
        skipSeparationSpace(state2, true, nodeIndent);
        ch = state2.input.charCodeAt(state2.position);
        if ((isExplicitPair || state2.line === _line) && ch === 58) {
          isPair = true;
          ch = state2.input.charCodeAt(++state2.position);
          skipSeparationSpace(state2, true, nodeIndent);
          composeNode(state2, nodeIndent, CONTEXT_FLOW_IN, false, true);
          valueNode = state2.result;
        }
        if (isMapping) {
          storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, valueNode);
        } else if (isPair) {
          _result.push(storeMappingPair(state2, null, overridableKeys, keyTag, keyNode, valueNode));
        } else {
          _result.push(keyNode);
        }
        skipSeparationSpace(state2, true, nodeIndent);
        ch = state2.input.charCodeAt(state2.position);
        if (ch === 44) {
          readNext = true;
          ch = state2.input.charCodeAt(++state2.position);
        } else {
          readNext = false;
        }
      }
      throwError(state2, "unexpected end of the stream within a flow collection");
    }
    function readBlockScalar(state2, nodeIndent) {
      var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
      ch = state2.input.charCodeAt(state2.position);
      if (ch === 124) {
        folding = false;
      } else if (ch === 62) {
        folding = true;
      } else {
        return false;
      }
      state2.kind = "scalar";
      state2.result = "";
      while (ch !== 0) {
        ch = state2.input.charCodeAt(++state2.position);
        if (ch === 43 || ch === 45) {
          if (CHOMPING_CLIP === chomping) {
            chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
          } else {
            throwError(state2, "repeat of a chomping mode identifier");
          }
        } else if ((tmp = fromDecimalCode(ch)) >= 0) {
          if (tmp === 0) {
            throwError(state2, "bad explicit indentation width of a block scalar; it cannot be less than one");
          } else if (!detectedIndent) {
            textIndent = nodeIndent + tmp - 1;
            detectedIndent = true;
          } else {
            throwError(state2, "repeat of an indentation width identifier");
          }
        } else {
          break;
        }
      }
      if (is_WHITE_SPACE(ch)) {
        do {
          ch = state2.input.charCodeAt(++state2.position);
        } while (is_WHITE_SPACE(ch));
        if (ch === 35) {
          do {
            ch = state2.input.charCodeAt(++state2.position);
          } while (!is_EOL(ch) && ch !== 0);
        }
      }
      while (ch !== 0) {
        readLineBreak(state2);
        state2.lineIndent = 0;
        ch = state2.input.charCodeAt(state2.position);
        while ((!detectedIndent || state2.lineIndent < textIndent) && ch === 32) {
          state2.lineIndent++;
          ch = state2.input.charCodeAt(++state2.position);
        }
        if (!detectedIndent && state2.lineIndent > textIndent) {
          textIndent = state2.lineIndent;
        }
        if (is_EOL(ch)) {
          emptyLines++;
          continue;
        }
        if (state2.lineIndent < textIndent) {
          if (chomping === CHOMPING_KEEP) {
            state2.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
          } else if (chomping === CHOMPING_CLIP) {
            if (didReadContent) {
              state2.result += "\n";
            }
          }
          break;
        }
        if (folding) {
          if (is_WHITE_SPACE(ch)) {
            atMoreIndented = true;
            state2.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
          } else if (atMoreIndented) {
            atMoreIndented = false;
            state2.result += common.repeat("\n", emptyLines + 1);
          } else if (emptyLines === 0) {
            if (didReadContent) {
              state2.result += " ";
            }
          } else {
            state2.result += common.repeat("\n", emptyLines);
          }
        } else {
          state2.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
        }
        didReadContent = true;
        detectedIndent = true;
        emptyLines = 0;
        captureStart = state2.position;
        while (!is_EOL(ch) && ch !== 0) {
          ch = state2.input.charCodeAt(++state2.position);
        }
        captureSegment(state2, captureStart, state2.position, false);
      }
      return true;
    }
    function readBlockSequence(state2, nodeIndent) {
      var _line, _tag = state2.tag, _anchor2 = state2.anchor, _result = [], following, detected = false, ch;
      if (state2.anchor !== null) {
        state2.anchorMap[state2.anchor] = _result;
      }
      ch = state2.input.charCodeAt(state2.position);
      while (ch !== 0) {
        if (ch !== 45) {
          break;
        }
        following = state2.input.charCodeAt(state2.position + 1);
        if (!is_WS_OR_EOL(following)) {
          break;
        }
        detected = true;
        state2.position++;
        if (skipSeparationSpace(state2, true, -1)) {
          if (state2.lineIndent <= nodeIndent) {
            _result.push(null);
            ch = state2.input.charCodeAt(state2.position);
            continue;
          }
        }
        _line = state2.line;
        composeNode(state2, nodeIndent, CONTEXT_BLOCK_IN, false, true);
        _result.push(state2.result);
        skipSeparationSpace(state2, true, -1);
        ch = state2.input.charCodeAt(state2.position);
        if ((state2.line === _line || state2.lineIndent > nodeIndent) && ch !== 0) {
          throwError(state2, "bad indentation of a sequence entry");
        } else if (state2.lineIndent < nodeIndent) {
          break;
        }
      }
      if (detected) {
        state2.tag = _tag;
        state2.anchor = _anchor2;
        state2.kind = "sequence";
        state2.result = _result;
        return true;
      }
      return false;
    }
    function readBlockMapping(state2, nodeIndent, flowIndent) {
      var following, allowCompact, _line, _pos, _tag = state2.tag, _anchor2 = state2.anchor, _result = {}, overridableKeys = {}, keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
      if (state2.anchor !== null) {
        state2.anchorMap[state2.anchor] = _result;
      }
      ch = state2.input.charCodeAt(state2.position);
      while (ch !== 0) {
        following = state2.input.charCodeAt(state2.position + 1);
        _line = state2.line;
        _pos = state2.position;
        if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
          if (ch === 63) {
            if (atExplicitKey) {
              storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, null);
              keyTag = keyNode = valueNode = null;
            }
            detected = true;
            atExplicitKey = true;
            allowCompact = true;
          } else if (atExplicitKey) {
            atExplicitKey = false;
            allowCompact = true;
          } else {
            throwError(state2, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
          }
          state2.position += 1;
          ch = following;
        } else if (composeNode(state2, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
          if (state2.line === _line) {
            ch = state2.input.charCodeAt(state2.position);
            while (is_WHITE_SPACE(ch)) {
              ch = state2.input.charCodeAt(++state2.position);
            }
            if (ch === 58) {
              ch = state2.input.charCodeAt(++state2.position);
              if (!is_WS_OR_EOL(ch)) {
                throwError(state2, "a whitespace character is expected after the key-value separator within a block mapping");
              }
              if (atExplicitKey) {
                storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, null);
                keyTag = keyNode = valueNode = null;
              }
              detected = true;
              atExplicitKey = false;
              allowCompact = false;
              keyTag = state2.tag;
              keyNode = state2.result;
            } else if (detected) {
              throwError(state2, "can not read an implicit mapping pair; a colon is missed");
            } else {
              state2.tag = _tag;
              state2.anchor = _anchor2;
              return true;
            }
          } else if (detected) {
            throwError(state2, "can not read a block mapping entry; a multiline key may not be an implicit key");
          } else {
            state2.tag = _tag;
            state2.anchor = _anchor2;
            return true;
          }
        } else {
          break;
        }
        if (state2.line === _line || state2.lineIndent > nodeIndent) {
          if (composeNode(state2, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
            if (atExplicitKey) {
              keyNode = state2.result;
            } else {
              valueNode = state2.result;
            }
          }
          if (!atExplicitKey) {
            storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
            keyTag = keyNode = valueNode = null;
          }
          skipSeparationSpace(state2, true, -1);
          ch = state2.input.charCodeAt(state2.position);
        }
        if (state2.lineIndent > nodeIndent && ch !== 0) {
          throwError(state2, "bad indentation of a mapping entry");
        } else if (state2.lineIndent < nodeIndent) {
          break;
        }
      }
      if (atExplicitKey) {
        storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, null);
      }
      if (detected) {
        state2.tag = _tag;
        state2.anchor = _anchor2;
        state2.kind = "mapping";
        state2.result = _result;
      }
      return detected;
    }
    function readTagProperty(state2) {
      var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
      ch = state2.input.charCodeAt(state2.position);
      if (ch !== 33) return false;
      if (state2.tag !== null) {
        throwError(state2, "duplication of a tag property");
      }
      ch = state2.input.charCodeAt(++state2.position);
      if (ch === 60) {
        isVerbatim = true;
        ch = state2.input.charCodeAt(++state2.position);
      } else if (ch === 33) {
        isNamed = true;
        tagHandle = "!!";
        ch = state2.input.charCodeAt(++state2.position);
      } else {
        tagHandle = "!";
      }
      _position = state2.position;
      if (isVerbatim) {
        do {
          ch = state2.input.charCodeAt(++state2.position);
        } while (ch !== 0 && ch !== 62);
        if (state2.position < state2.length) {
          tagName = state2.input.slice(_position, state2.position);
          ch = state2.input.charCodeAt(++state2.position);
        } else {
          throwError(state2, "unexpected end of the stream within a verbatim tag");
        }
      } else {
        while (ch !== 0 && !is_WS_OR_EOL(ch)) {
          if (ch === 33) {
            if (!isNamed) {
              tagHandle = state2.input.slice(_position - 1, state2.position + 1);
              if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
                throwError(state2, "named tag handle cannot contain such characters");
              }
              isNamed = true;
              _position = state2.position + 1;
            } else {
              throwError(state2, "tag suffix cannot contain exclamation marks");
            }
          }
          ch = state2.input.charCodeAt(++state2.position);
        }
        tagName = state2.input.slice(_position, state2.position);
        if (PATTERN_FLOW_INDICATORS.test(tagName)) {
          throwError(state2, "tag suffix cannot contain flow indicator characters");
        }
      }
      if (tagName && !PATTERN_TAG_URI.test(tagName)) {
        throwError(state2, "tag name cannot contain such characters: " + tagName);
      }
      if (isVerbatim) {
        state2.tag = tagName;
      } else if (_hasOwnProperty.call(state2.tagMap, tagHandle)) {
        state2.tag = state2.tagMap[tagHandle] + tagName;
      } else if (tagHandle === "!") {
        state2.tag = "!" + tagName;
      } else if (tagHandle === "!!") {
        state2.tag = "tag:yaml.org,2002:" + tagName;
      } else {
        throwError(state2, 'undeclared tag handle "' + tagHandle + '"');
      }
      return true;
    }
    function readAnchorProperty(state2) {
      var _position, ch;
      ch = state2.input.charCodeAt(state2.position);
      if (ch !== 38) return false;
      if (state2.anchor !== null) {
        throwError(state2, "duplication of an anchor property");
      }
      ch = state2.input.charCodeAt(++state2.position);
      _position = state2.position;
      while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
        ch = state2.input.charCodeAt(++state2.position);
      }
      if (state2.position === _position) {
        throwError(state2, "name of an anchor node must contain at least one character");
      }
      state2.anchor = state2.input.slice(_position, state2.position);
      return true;
    }
    function readAlias(state2) {
      var _position, alias, ch;
      ch = state2.input.charCodeAt(state2.position);
      if (ch !== 42) return false;
      ch = state2.input.charCodeAt(++state2.position);
      _position = state2.position;
      while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
        ch = state2.input.charCodeAt(++state2.position);
      }
      if (state2.position === _position) {
        throwError(state2, "name of an alias node must contain at least one character");
      }
      alias = state2.input.slice(_position, state2.position);
      if (!_hasOwnProperty.call(state2.anchorMap, alias)) {
        throwError(state2, 'unidentified alias "' + alias + '"');
      }
      state2.result = state2.anchorMap[alias];
      skipSeparationSpace(state2, true, -1);
      return true;
    }
    function composeNode(state2, parentIndent, nodeContext, allowToSeek, allowCompact) {
      var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, type, flowIndent, blockIndent;
      if (state2.listener !== null) {
        state2.listener("open", state2);
      }
      state2.tag = null;
      state2.anchor = null;
      state2.kind = null;
      state2.result = null;
      allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
      if (allowToSeek) {
        if (skipSeparationSpace(state2, true, -1)) {
          atNewLine = true;
          if (state2.lineIndent > parentIndent) {
            indentStatus = 1;
          } else if (state2.lineIndent === parentIndent) {
            indentStatus = 0;
          } else if (state2.lineIndent < parentIndent) {
            indentStatus = -1;
          }
        }
      }
      if (indentStatus === 1) {
        while (readTagProperty(state2) || readAnchorProperty(state2)) {
          if (skipSeparationSpace(state2, true, -1)) {
            atNewLine = true;
            allowBlockCollections = allowBlockStyles;
            if (state2.lineIndent > parentIndent) {
              indentStatus = 1;
            } else if (state2.lineIndent === parentIndent) {
              indentStatus = 0;
            } else if (state2.lineIndent < parentIndent) {
              indentStatus = -1;
            }
          } else {
            allowBlockCollections = false;
          }
        }
      }
      if (allowBlockCollections) {
        allowBlockCollections = atNewLine || allowCompact;
      }
      if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
        if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
          flowIndent = parentIndent;
        } else {
          flowIndent = parentIndent + 1;
        }
        blockIndent = state2.position - state2.lineStart;
        if (indentStatus === 1) {
          if (allowBlockCollections && (readBlockSequence(state2, blockIndent) || readBlockMapping(state2, blockIndent, flowIndent)) || readFlowCollection(state2, flowIndent)) {
            hasContent = true;
          } else {
            if (allowBlockScalars && readBlockScalar(state2, flowIndent) || readSingleQuotedScalar(state2, flowIndent) || readDoubleQuotedScalar(state2, flowIndent)) {
              hasContent = true;
            } else if (readAlias(state2)) {
              hasContent = true;
              if (state2.tag !== null || state2.anchor !== null) {
                throwError(state2, "alias node should not have any properties");
              }
            } else if (readPlainScalar(state2, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
              hasContent = true;
              if (state2.tag === null) {
                state2.tag = "?";
              }
            }
            if (state2.anchor !== null) {
              state2.anchorMap[state2.anchor] = state2.result;
            }
          }
        } else if (indentStatus === 0) {
          hasContent = allowBlockCollections && readBlockSequence(state2, blockIndent);
        }
      }
      if (state2.tag !== null && state2.tag !== "!") {
        if (state2.tag === "?") {
          if (state2.result !== null && state2.kind !== "scalar") {
            throwError(state2, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state2.kind + '"');
          }
          for (typeIndex = 0, typeQuantity = state2.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
            type = state2.implicitTypes[typeIndex];
            if (type.resolve(state2.result)) {
              state2.result = type.construct(state2.result);
              state2.tag = type.tag;
              if (state2.anchor !== null) {
                state2.anchorMap[state2.anchor] = state2.result;
              }
              break;
            }
          }
        } else if (_hasOwnProperty.call(state2.typeMap[state2.kind || "fallback"], state2.tag)) {
          type = state2.typeMap[state2.kind || "fallback"][state2.tag];
          if (state2.result !== null && type.kind !== state2.kind) {
            throwError(state2, "unacceptable node kind for !<" + state2.tag + '> tag; it should be "' + type.kind + '", not "' + state2.kind + '"');
          }
          if (!type.resolve(state2.result)) {
            throwError(state2, "cannot resolve a node with !<" + state2.tag + "> explicit tag");
          } else {
            state2.result = type.construct(state2.result);
            if (state2.anchor !== null) {
              state2.anchorMap[state2.anchor] = state2.result;
            }
          }
        } else {
          throwError(state2, "unknown tag !<" + state2.tag + ">");
        }
      }
      if (state2.listener !== null) {
        state2.listener("close", state2);
      }
      return state2.tag !== null || state2.anchor !== null || hasContent;
    }
    function readDocument(state2) {
      var documentStart = state2.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
      state2.version = null;
      state2.checkLineBreaks = state2.legacy;
      state2.tagMap = {};
      state2.anchorMap = {};
      while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
        skipSeparationSpace(state2, true, -1);
        ch = state2.input.charCodeAt(state2.position);
        if (state2.lineIndent > 0 || ch !== 37) {
          break;
        }
        hasDirectives = true;
        ch = state2.input.charCodeAt(++state2.position);
        _position = state2.position;
        while (ch !== 0 && !is_WS_OR_EOL(ch)) {
          ch = state2.input.charCodeAt(++state2.position);
        }
        directiveName = state2.input.slice(_position, state2.position);
        directiveArgs = [];
        if (directiveName.length < 1) {
          throwError(state2, "directive name must not be less than one character in length");
        }
        while (ch !== 0) {
          while (is_WHITE_SPACE(ch)) {
            ch = state2.input.charCodeAt(++state2.position);
          }
          if (ch === 35) {
            do {
              ch = state2.input.charCodeAt(++state2.position);
            } while (ch !== 0 && !is_EOL(ch));
            break;
          }
          if (is_EOL(ch)) break;
          _position = state2.position;
          while (ch !== 0 && !is_WS_OR_EOL(ch)) {
            ch = state2.input.charCodeAt(++state2.position);
          }
          directiveArgs.push(state2.input.slice(_position, state2.position));
        }
        if (ch !== 0) readLineBreak(state2);
        if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
          directiveHandlers[directiveName](state2, directiveName, directiveArgs);
        } else {
          throwWarning(state2, 'unknown document directive "' + directiveName + '"');
        }
      }
      skipSeparationSpace(state2, true, -1);
      if (state2.lineIndent === 0 && state2.input.charCodeAt(state2.position) === 45 && state2.input.charCodeAt(state2.position + 1) === 45 && state2.input.charCodeAt(state2.position + 2) === 45) {
        state2.position += 3;
        skipSeparationSpace(state2, true, -1);
      } else if (hasDirectives) {
        throwError(state2, "directives end mark is expected");
      }
      composeNode(state2, state2.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
      skipSeparationSpace(state2, true, -1);
      if (state2.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state2.input.slice(documentStart, state2.position))) {
        throwWarning(state2, "non-ASCII line breaks are interpreted as content");
      }
      state2.documents.push(state2.result);
      if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
        if (state2.input.charCodeAt(state2.position) === 46) {
          state2.position += 3;
          skipSeparationSpace(state2, true, -1);
        }
        return;
      }
      if (state2.position < state2.length - 1) {
        throwError(state2, "end of the stream or a document separator is expected");
      } else {
        return;
      }
    }
    function loadDocuments(input, options2) {
      input = String(input);
      options2 = options2 || {};
      if (input.length !== 0) {
        if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
          input += "\n";
        }
        if (input.charCodeAt(0) === 65279) {
          input = input.slice(1);
        }
      }
      var state2 = new State(input, options2);
      var nullpos = input.indexOf("\0");
      if (nullpos !== -1) {
        state2.position = nullpos;
        throwError(state2, "null byte is not allowed in input");
      }
      state2.input += "\0";
      while (state2.input.charCodeAt(state2.position) === 32) {
        state2.lineIndent += 1;
        state2.position += 1;
      }
      while (state2.position < state2.length - 1) {
        readDocument(state2);
      }
      return state2.documents;
    }
    function loadAll(input, iterator, options2) {
      if (iterator !== null && typeof iterator === "object" && typeof options2 === "undefined") {
        options2 = iterator;
        iterator = null;
      }
      var documents = loadDocuments(input, options2);
      if (typeof iterator !== "function") {
        return documents;
      }
      for (var index2 = 0, length = documents.length; index2 < length; index2 += 1) {
        iterator(documents[index2]);
      }
    }
    function load(input, options2) {
      var documents = loadDocuments(input, options2);
      if (documents.length === 0) {
        return void 0;
      } else if (documents.length === 1) {
        return documents[0];
      }
      throw new YAMLException("expected a single document in the stream, but found more");
    }
    function safeLoadAll(input, iterator, options2) {
      if (typeof iterator === "object" && iterator !== null && typeof options2 === "undefined") {
        options2 = iterator;
        iterator = null;
      }
      return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options2));
    }
    function safeLoad(input, options2) {
      return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options2));
    }
    module2.exports.loadAll = loadAll;
    module2.exports.load = load;
    module2.exports.safeLoadAll = safeLoadAll;
    module2.exports.safeLoad = safeLoad;
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/dumper.js
var require_dumper = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/dumper.js"(exports2, module2) {
    "use strict";
    var common = require_common();
    var YAMLException = require_exception();
    var DEFAULT_FULL_SCHEMA = require_default_full();
    var DEFAULT_SAFE_SCHEMA = require_default_safe();
    var _toString = Object.prototype.toString;
    var _hasOwnProperty = Object.prototype.hasOwnProperty;
    var CHAR_TAB = 9;
    var CHAR_LINE_FEED = 10;
    var CHAR_CARRIAGE_RETURN = 13;
    var CHAR_SPACE = 32;
    var CHAR_EXCLAMATION = 33;
    var CHAR_DOUBLE_QUOTE = 34;
    var CHAR_SHARP = 35;
    var CHAR_PERCENT = 37;
    var CHAR_AMPERSAND = 38;
    var CHAR_SINGLE_QUOTE = 39;
    var CHAR_ASTERISK = 42;
    var CHAR_COMMA = 44;
    var CHAR_MINUS = 45;
    var CHAR_COLON = 58;
    var CHAR_EQUALS = 61;
    var CHAR_GREATER_THAN = 62;
    var CHAR_QUESTION = 63;
    var CHAR_COMMERCIAL_AT = 64;
    var CHAR_LEFT_SQUARE_BRACKET = 91;
    var CHAR_RIGHT_SQUARE_BRACKET = 93;
    var CHAR_GRAVE_ACCENT = 96;
    var CHAR_LEFT_CURLY_BRACKET = 123;
    var CHAR_VERTICAL_LINE = 124;
    var CHAR_RIGHT_CURLY_BRACKET = 125;
    var ESCAPE_SEQUENCES = {};
    ESCAPE_SEQUENCES[0] = "\\0";
    ESCAPE_SEQUENCES[7] = "\\a";
    ESCAPE_SEQUENCES[8] = "\\b";
    ESCAPE_SEQUENCES[9] = "\\t";
    ESCAPE_SEQUENCES[10] = "\\n";
    ESCAPE_SEQUENCES[11] = "\\v";
    ESCAPE_SEQUENCES[12] = "\\f";
    ESCAPE_SEQUENCES[13] = "\\r";
    ESCAPE_SEQUENCES[27] = "\\e";
    ESCAPE_SEQUENCES[34] = '\\"';
    ESCAPE_SEQUENCES[92] = "\\\\";
    ESCAPE_SEQUENCES[133] = "\\N";
    ESCAPE_SEQUENCES[160] = "\\_";
    ESCAPE_SEQUENCES[8232] = "\\L";
    ESCAPE_SEQUENCES[8233] = "\\P";
    var DEPRECATED_BOOLEANS_SYNTAX = [
      "y",
      "Y",
      "yes",
      "Yes",
      "YES",
      "on",
      "On",
      "ON",
      "n",
      "N",
      "no",
      "No",
      "NO",
      "off",
      "Off",
      "OFF"
    ];
    function compileStyleMap(schema, map) {
      var result, keys, index2, length, tag2, style, type;
      if (map === null) return {};
      result = {};
      keys = Object.keys(map);
      for (index2 = 0, length = keys.length; index2 < length; index2 += 1) {
        tag2 = keys[index2];
        style = String(map[tag2]);
        if (tag2.slice(0, 2) === "!!") {
          tag2 = "tag:yaml.org,2002:" + tag2.slice(2);
        }
        type = schema.compiledTypeMap["fallback"][tag2];
        if (type && _hasOwnProperty.call(type.styleAliases, style)) {
          style = type.styleAliases[style];
        }
        result[tag2] = style;
      }
      return result;
    }
    function encodeHex(character) {
      var string, handle, length;
      string = character.toString(16).toUpperCase();
      if (character <= 255) {
        handle = "x";
        length = 2;
      } else if (character <= 65535) {
        handle = "u";
        length = 4;
      } else if (character <= 4294967295) {
        handle = "U";
        length = 8;
      } else {
        throw new YAMLException("code point within a string may not be greater than 0xFFFFFFFF");
      }
      return "\\" + handle + common.repeat("0", length - string.length) + string;
    }
    function State(options2) {
      this.schema = options2["schema"] || DEFAULT_FULL_SCHEMA;
      this.indent = Math.max(1, options2["indent"] || 2);
      this.noArrayIndent = options2["noArrayIndent"] || false;
      this.skipInvalid = options2["skipInvalid"] || false;
      this.flowLevel = common.isNothing(options2["flowLevel"]) ? -1 : options2["flowLevel"];
      this.styleMap = compileStyleMap(this.schema, options2["styles"] || null);
      this.sortKeys = options2["sortKeys"] || false;
      this.lineWidth = options2["lineWidth"] || 80;
      this.noRefs = options2["noRefs"] || false;
      this.noCompatMode = options2["noCompatMode"] || false;
      this.condenseFlow = options2["condenseFlow"] || false;
      this.implicitTypes = this.schema.compiledImplicit;
      this.explicitTypes = this.schema.compiledExplicit;
      this.tag = null;
      this.result = "";
      this.duplicates = [];
      this.usedDuplicates = null;
    }
    function indentString(string, spaces) {
      var ind = common.repeat(" ", spaces), position = 0, next2 = -1, result = "", line, length = string.length;
      while (position < length) {
        next2 = string.indexOf("\n", position);
        if (next2 === -1) {
          line = string.slice(position);
          position = length;
        } else {
          line = string.slice(position, next2 + 1);
          position = next2 + 1;
        }
        if (line.length && line !== "\n") result += ind;
        result += line;
      }
      return result;
    }
    function generateNextLine(state2, level) {
      return "\n" + common.repeat(" ", state2.indent * level);
    }
    function testImplicitResolving(state2, str2) {
      var index2, length, type;
      for (index2 = 0, length = state2.implicitTypes.length; index2 < length; index2 += 1) {
        type = state2.implicitTypes[index2];
        if (type.resolve(str2)) {
          return true;
        }
      }
      return false;
    }
    function isWhitespace(c) {
      return c === CHAR_SPACE || c === CHAR_TAB;
    }
    function isPrintable(c) {
      return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== 65279 || 65536 <= c && c <= 1114111;
    }
    function isNsChar(c) {
      return isPrintable(c) && !isWhitespace(c) && c !== 65279 && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
    }
    function isPlainSafe(c, prev) {
      return isPrintable(c) && c !== 65279 && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_COLON && (c !== CHAR_SHARP || prev && isNsChar(prev));
    }
    function isPlainSafeFirst(c) {
      return isPrintable(c) && c !== 65279 && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
    }
    function needIndentIndicator(string) {
      var leadingSpaceRe = /^\n* /;
      return leadingSpaceRe.test(string);
    }
    var STYLE_PLAIN = 1;
    var STYLE_SINGLE = 2;
    var STYLE_LITERAL = 3;
    var STYLE_FOLDED = 4;
    var STYLE_DOUBLE = 5;
    function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
      var i;
      var char, prev_char;
      var hasLineBreak = false;
      var hasFoldableLine = false;
      var shouldTrackWidth = lineWidth !== -1;
      var previousLineBreak = -1;
      var plain = isPlainSafeFirst(string.charCodeAt(0)) && !isWhitespace(string.charCodeAt(string.length - 1));
      if (singleLineOnly) {
        for (i = 0; i < string.length; i++) {
          char = string.charCodeAt(i);
          if (!isPrintable(char)) {
            return STYLE_DOUBLE;
          }
          prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
          plain = plain && isPlainSafe(char, prev_char);
        }
      } else {
        for (i = 0; i < string.length; i++) {
          char = string.charCodeAt(i);
          if (char === CHAR_LINE_FEED) {
            hasLineBreak = true;
            if (shouldTrackWidth) {
              hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
              i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
              previousLineBreak = i;
            }
          } else if (!isPrintable(char)) {
            return STYLE_DOUBLE;
          }
          prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
          plain = plain && isPlainSafe(char, prev_char);
        }
        hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
      }
      if (!hasLineBreak && !hasFoldableLine) {
        return plain && !testAmbiguousType(string) ? STYLE_PLAIN : STYLE_SINGLE;
      }
      if (indentPerLevel > 9 && needIndentIndicator(string)) {
        return STYLE_DOUBLE;
      }
      return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
    }
    function writeScalar(state2, string, level, iskey) {
      state2.dump = (function() {
        if (string.length === 0) {
          return "''";
        }
        if (!state2.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
          return "'" + string + "'";
        }
        var indent = state2.indent * Math.max(1, level);
        var lineWidth = state2.lineWidth === -1 ? -1 : Math.max(Math.min(state2.lineWidth, 40), state2.lineWidth - indent);
        var singleLineOnly = iskey || state2.flowLevel > -1 && level >= state2.flowLevel;
        function testAmbiguity(string2) {
          return testImplicitResolving(state2, string2);
        }
        switch (chooseScalarStyle(string, singleLineOnly, state2.indent, lineWidth, testAmbiguity)) {
          case STYLE_PLAIN:
            return string;
          case STYLE_SINGLE:
            return "'" + string.replace(/'/g, "''") + "'";
          case STYLE_LITERAL:
            return "|" + blockHeader(string, state2.indent) + dropEndingNewline(indentString(string, indent));
          case STYLE_FOLDED:
            return ">" + blockHeader(string, state2.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
          case STYLE_DOUBLE:
            return '"' + escapeString(string, lineWidth) + '"';
          default:
            throw new YAMLException("impossible error: invalid scalar style");
        }
      })();
    }
    function blockHeader(string, indentPerLevel) {
      var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
      var clip = string[string.length - 1] === "\n";
      var keep = clip && (string[string.length - 2] === "\n" || string === "\n");
      var chomp = keep ? "+" : clip ? "" : "-";
      return indentIndicator + chomp + "\n";
    }
    function dropEndingNewline(string) {
      return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
    }
    function foldString(string, width) {
      var lineRe = /(\n+)([^\n]*)/g;
      var result = (function() {
        var nextLF = string.indexOf("\n");
        nextLF = nextLF !== -1 ? nextLF : string.length;
        lineRe.lastIndex = nextLF;
        return foldLine(string.slice(0, nextLF), width);
      })();
      var prevMoreIndented = string[0] === "\n" || string[0] === " ";
      var moreIndented;
      var match;
      while (match = lineRe.exec(string)) {
        var prefix = match[1], line = match[2];
        moreIndented = line[0] === " ";
        result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
        prevMoreIndented = moreIndented;
      }
      return result;
    }
    function foldLine(line, width) {
      if (line === "" || line[0] === " ") return line;
      var breakRe = / [^ ]/g;
      var match;
      var start = 0, end, curr = 0, next2 = 0;
      var result = "";
      while (match = breakRe.exec(line)) {
        next2 = match.index;
        if (next2 - start > width) {
          end = curr > start ? curr : next2;
          result += "\n" + line.slice(start, end);
          start = end + 1;
        }
        curr = next2;
      }
      result += "\n";
      if (line.length - start > width && curr > start) {
        result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
      } else {
        result += line.slice(start);
      }
      return result.slice(1);
    }
    function escapeString(string) {
      var result = "";
      var char, nextChar;
      var escapeSeq;
      for (var i = 0; i < string.length; i++) {
        char = string.charCodeAt(i);
        if (char >= 55296 && char <= 56319) {
          nextChar = string.charCodeAt(i + 1);
          if (nextChar >= 56320 && nextChar <= 57343) {
            result += encodeHex((char - 55296) * 1024 + nextChar - 56320 + 65536);
            i++;
            continue;
          }
        }
        escapeSeq = ESCAPE_SEQUENCES[char];
        result += !escapeSeq && isPrintable(char) ? string[i] : escapeSeq || encodeHex(char);
      }
      return result;
    }
    function writeFlowSequence(state2, level, object) {
      var _result = "", _tag = state2.tag, index2, length;
      for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
        if (writeNode(state2, level, object[index2], false, false)) {
          if (index2 !== 0) _result += "," + (!state2.condenseFlow ? " " : "");
          _result += state2.dump;
        }
      }
      state2.tag = _tag;
      state2.dump = "[" + _result + "]";
    }
    function writeBlockSequence(state2, level, object, compact) {
      var _result = "", _tag = state2.tag, index2, length;
      for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
        if (writeNode(state2, level + 1, object[index2], true, true)) {
          if (!compact || index2 !== 0) {
            _result += generateNextLine(state2, level);
          }
          if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
            _result += "-";
          } else {
            _result += "- ";
          }
          _result += state2.dump;
        }
      }
      state2.tag = _tag;
      state2.dump = _result || "[]";
    }
    function writeFlowMapping(state2, level, object) {
      var _result = "", _tag = state2.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, pairBuffer;
      for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
        pairBuffer = "";
        if (index2 !== 0) pairBuffer += ", ";
        if (state2.condenseFlow) pairBuffer += '"';
        objectKey = objectKeyList[index2];
        objectValue = object[objectKey];
        if (!writeNode(state2, level, objectKey, false, false)) {
          continue;
        }
        if (state2.dump.length > 1024) pairBuffer += "? ";
        pairBuffer += state2.dump + (state2.condenseFlow ? '"' : "") + ":" + (state2.condenseFlow ? "" : " ");
        if (!writeNode(state2, level, objectValue, false, false)) {
          continue;
        }
        pairBuffer += state2.dump;
        _result += pairBuffer;
      }
      state2.tag = _tag;
      state2.dump = "{" + _result + "}";
    }
    function writeBlockMapping(state2, level, object, compact) {
      var _result = "", _tag = state2.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, explicitPair, pairBuffer;
      if (state2.sortKeys === true) {
        objectKeyList.sort();
      } else if (typeof state2.sortKeys === "function") {
        objectKeyList.sort(state2.sortKeys);
      } else if (state2.sortKeys) {
        throw new YAMLException("sortKeys must be a boolean or a function");
      }
      for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
        pairBuffer = "";
        if (!compact || index2 !== 0) {
          pairBuffer += generateNextLine(state2, level);
        }
        objectKey = objectKeyList[index2];
        objectValue = object[objectKey];
        if (!writeNode(state2, level + 1, objectKey, true, true, true)) {
          continue;
        }
        explicitPair = state2.tag !== null && state2.tag !== "?" || state2.dump && state2.dump.length > 1024;
        if (explicitPair) {
          if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
            pairBuffer += "?";
          } else {
            pairBuffer += "? ";
          }
        }
        pairBuffer += state2.dump;
        if (explicitPair) {
          pairBuffer += generateNextLine(state2, level);
        }
        if (!writeNode(state2, level + 1, objectValue, true, explicitPair)) {
          continue;
        }
        if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
          pairBuffer += ":";
        } else {
          pairBuffer += ": ";
        }
        pairBuffer += state2.dump;
        _result += pairBuffer;
      }
      state2.tag = _tag;
      state2.dump = _result || "{}";
    }
    function detectType(state2, object, explicit) {
      var _result, typeList, index2, length, type, style;
      typeList = explicit ? state2.explicitTypes : state2.implicitTypes;
      for (index2 = 0, length = typeList.length; index2 < length; index2 += 1) {
        type = typeList[index2];
        if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === "object" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {
          state2.tag = explicit ? type.tag : "?";
          if (type.represent) {
            style = state2.styleMap[type.tag] || type.defaultStyle;
            if (_toString.call(type.represent) === "[object Function]") {
              _result = type.represent(object, style);
            } else if (_hasOwnProperty.call(type.represent, style)) {
              _result = type.represent[style](object, style);
            } else {
              throw new YAMLException("!<" + type.tag + '> tag resolver accepts not "' + style + '" style');
            }
            state2.dump = _result;
          }
          return true;
        }
      }
      return false;
    }
    function writeNode(state2, level, object, block2, compact, iskey) {
      state2.tag = null;
      state2.dump = object;
      if (!detectType(state2, object, false)) {
        detectType(state2, object, true);
      }
      var type = _toString.call(state2.dump);
      if (block2) {
        block2 = state2.flowLevel < 0 || state2.flowLevel > level;
      }
      var objectOrArray = type === "[object Object]" || type === "[object Array]", duplicateIndex, duplicate;
      if (objectOrArray) {
        duplicateIndex = state2.duplicates.indexOf(object);
        duplicate = duplicateIndex !== -1;
      }
      if (state2.tag !== null && state2.tag !== "?" || duplicate || state2.indent !== 2 && level > 0) {
        compact = false;
      }
      if (duplicate && state2.usedDuplicates[duplicateIndex]) {
        state2.dump = "*ref_" + duplicateIndex;
      } else {
        if (objectOrArray && duplicate && !state2.usedDuplicates[duplicateIndex]) {
          state2.usedDuplicates[duplicateIndex] = true;
        }
        if (type === "[object Object]") {
          if (block2 && Object.keys(state2.dump).length !== 0) {
            writeBlockMapping(state2, level, state2.dump, compact);
            if (duplicate) {
              state2.dump = "&ref_" + duplicateIndex + state2.dump;
            }
          } else {
            writeFlowMapping(state2, level, state2.dump);
            if (duplicate) {
              state2.dump = "&ref_" + duplicateIndex + " " + state2.dump;
            }
          }
        } else if (type === "[object Array]") {
          var arrayLevel = state2.noArrayIndent && level > 0 ? level - 1 : level;
          if (block2 && state2.dump.length !== 0) {
            writeBlockSequence(state2, arrayLevel, state2.dump, compact);
            if (duplicate) {
              state2.dump = "&ref_" + duplicateIndex + state2.dump;
            }
          } else {
            writeFlowSequence(state2, arrayLevel, state2.dump);
            if (duplicate) {
              state2.dump = "&ref_" + duplicateIndex + " " + state2.dump;
            }
          }
        } else if (type === "[object String]") {
          if (state2.tag !== "?") {
            writeScalar(state2, state2.dump, level, iskey);
          }
        } else {
          if (state2.skipInvalid) return false;
          throw new YAMLException("unacceptable kind of an object to dump " + type);
        }
        if (state2.tag !== null && state2.tag !== "?") {
          state2.dump = "!<" + state2.tag + "> " + state2.dump;
        }
      }
      return true;
    }
    function getDuplicateReferences(object, state2) {
      var objects = [], duplicatesIndexes = [], index2, length;
      inspectNode(object, objects, duplicatesIndexes);
      for (index2 = 0, length = duplicatesIndexes.length; index2 < length; index2 += 1) {
        state2.duplicates.push(objects[duplicatesIndexes[index2]]);
      }
      state2.usedDuplicates = new Array(length);
    }
    function inspectNode(object, objects, duplicatesIndexes) {
      var objectKeyList, index2, length;
      if (object !== null && typeof object === "object") {
        index2 = objects.indexOf(object);
        if (index2 !== -1) {
          if (duplicatesIndexes.indexOf(index2) === -1) {
            duplicatesIndexes.push(index2);
          }
        } else {
          objects.push(object);
          if (Array.isArray(object)) {
            for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
              inspectNode(object[index2], objects, duplicatesIndexes);
            }
          } else {
            objectKeyList = Object.keys(object);
            for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
              inspectNode(object[objectKeyList[index2]], objects, duplicatesIndexes);
            }
          }
        }
      }
    }
    function dump(input, options2) {
      options2 = options2 || {};
      var state2 = new State(options2);
      if (!state2.noRefs) getDuplicateReferences(input, state2);
      if (writeNode(state2, 0, input, true, true)) return state2.dump + "\n";
      return "";
    }
    function safeDump(input, options2) {
      return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options2));
    }
    module2.exports.dump = dump;
    module2.exports.safeDump = safeDump;
  }
});

// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml.js
var require_js_yaml = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml.js"(exports2, module2) {
    "use strict";
    var loader = require_loader();
    var dumper = require_dumper();
    function deprecated(name) {
      return function() {
        throw new Error("Function " + name + " is deprecated and cannot be used.");
      };
    }
    module2.exports.Type = require_type();
    module2.exports.Schema = require_schema();
    module2.exports.FAILSAFE_SCHEMA = require_failsafe();
    module2.exports.JSON_SCHEMA = require_json();
    module2.exports.CORE_SCHEMA = require_core2();
    module2.exports.DEFAULT_SAFE_SCHEMA = require_default_safe();
    module2.exports.DEFAULT_FULL_SCHEMA = require_default_full();
    module2.exports.load = loader.load;
    module2.exports.loadAll = loader.loadAll;
    module2.exports.safeLoad = loader.safeLoad;
    module2.exports.safeLoadAll = loader.safeLoadAll;
    module2.exports.dump = dumper.dump;
    module2.exports.safeDump = dumper.safeDump;
    module2.exports.YAMLException = require_exception();
    module2.exports.MINIMAL_SCHEMA = require_failsafe();
    module2.exports.SAFE_SCHEMA = require_default_safe();
    module2.exports.DEFAULT_SCHEMA = require_default_full();
    module2.exports.scan = deprecated("scan");
    module2.exports.parse = deprecated("parse");
    module2.exports.compose = deprecated("compose");
    module2.exports.addConstructor = deprecated("addConstructor");
  }
});

// node_modules/gray-matter/node_modules/js-yaml/index.js
var require_js_yaml2 = __commonJS({
  "node_modules/gray-matter/node_modules/js-yaml/index.js"(exports2, module2) {
    "use strict";
    var yaml2 = require_js_yaml();
    module2.exports = yaml2;
  }
});

// node_modules/gray-matter/lib/engines.js
var require_engines = __commonJS({
  "node_modules/gray-matter/lib/engines.js"(exports, module) {
    "use strict";
    var yaml = require_js_yaml2();
    var engines = exports = module.exports;
    engines.yaml = {
      parse: yaml.safeLoad.bind(yaml),
      stringify: yaml.safeDump.bind(yaml)
    };
    engines.json = {
      parse: JSON.parse.bind(JSON),
      stringify: function(obj, options2) {
        const opts = Object.assign({ replacer: null, space: 2 }, options2);
        return JSON.stringify(obj, opts.replacer, opts.space);
      }
    };
    engines.javascript = {
      parse: function parse(str, options, wrap) {
        try {
          if (wrap !== false) {
            str = "(function() {\nreturn " + str.trim() + ";\n}());";
          }
          return eval(str) || {};
        } catch (err) {
          if (wrap !== false && /(unexpected|identifier)/i.test(err.message)) {
            return parse(str, options, false);
          }
          throw new SyntaxError(err);
        }
      },
      stringify: function() {
        throw new Error("stringifying JavaScript is not supported");
      }
    };
  }
});

// node_modules/strip-bom-string/index.js
var require_strip_bom_string = __commonJS({
  "node_modules/strip-bom-string/index.js"(exports2, module2) {
    "use strict";
    module2.exports = function(str2) {
      if (typeof str2 === "string" && str2.charAt(0) === "\uFEFF") {
        return str2.slice(1);
      }
      return str2;
    };
  }
});

// node_modules/gray-matter/lib/utils.js
var require_utils = __commonJS({
  "node_modules/gray-matter/lib/utils.js"(exports2) {
    "use strict";
    var stripBom = require_strip_bom_string();
    var typeOf = require_kind_of();
    exports2.define = function(obj, key2, val) {
      Reflect.defineProperty(obj, key2, {
        enumerable: false,
        configurable: true,
        writable: true,
        value: val
      });
    };
    exports2.isBuffer = function(val) {
      return typeOf(val) === "buffer";
    };
    exports2.isObject = function(val) {
      return typeOf(val) === "object";
    };
    exports2.toBuffer = function(input) {
      return typeof input === "string" ? Buffer.from(input) : input;
    };
    exports2.toString = function(input) {
      if (exports2.isBuffer(input)) return stripBom(String(input));
      if (typeof input !== "string") {
        throw new TypeError("expected input to be a string or buffer");
      }
      return stripBom(input);
    };
    exports2.arrayify = function(val) {
      return val ? Array.isArray(val) ? val : [val] : [];
    };
    exports2.startsWith = function(str2, substr, len) {
      if (typeof len !== "number") len = substr.length;
      return str2.slice(0, len) === substr;
    };
  }
});

// node_modules/gray-matter/lib/defaults.js
var require_defaults = __commonJS({
  "node_modules/gray-matter/lib/defaults.js"(exports2, module2) {
    "use strict";
    var engines2 = require_engines();
    var utils = require_utils();
    module2.exports = function(options2) {
      const opts = Object.assign({}, options2);
      opts.delimiters = utils.arrayify(opts.delims || opts.delimiters || "---");
      if (opts.delimiters.length === 1) {
        opts.delimiters.push(opts.delimiters[0]);
      }
      opts.language = (opts.language || opts.lang || "yaml").toLowerCase();
      opts.engines = Object.assign({}, engines2, opts.parsers, opts.engines);
      return opts;
    };
  }
});

// node_modules/gray-matter/lib/engine.js
var require_engine = __commonJS({
  "node_modules/gray-matter/lib/engine.js"(exports2, module2) {
    "use strict";
    module2.exports = function(name, options2) {
      let engine = options2.engines[name] || options2.engines[aliase(name)];
      if (typeof engine === "undefined") {
        throw new Error('gray-matter engine "' + name + '" is not registered');
      }
      if (typeof engine === "function") {
        engine = { parse: engine };
      }
      return engine;
    };
    function aliase(name) {
      switch (name.toLowerCase()) {
        case "js":
        case "javascript":
          return "javascript";
        case "coffee":
        case "coffeescript":
        case "cson":
          return "coffee";
        case "yaml":
        case "yml":
          return "yaml";
        default: {
          return name;
        }
      }
    }
  }
});

// node_modules/gray-matter/lib/stringify.js
var require_stringify = __commonJS({
  "node_modules/gray-matter/lib/stringify.js"(exports2, module2) {
    "use strict";
    var typeOf = require_kind_of();
    var getEngine = require_engine();
    var defaults = require_defaults();
    module2.exports = function(file, data, options2) {
      if (data == null && options2 == null) {
        switch (typeOf(file)) {
          case "object":
            data = file.data;
            options2 = {};
            break;
          case "string":
            return file;
          default: {
            throw new TypeError("expected file to be a string or object");
          }
        }
      }
      const str2 = file.content;
      const opts = defaults(options2);
      if (data == null) {
        if (!opts.data) return file;
        data = opts.data;
      }
      const language = file.language || opts.language;
      const engine = getEngine(language, opts);
      if (typeof engine.stringify !== "function") {
        throw new TypeError('expected "' + language + '.stringify" to be a function');
      }
      data = Object.assign({}, file.data, data);
      const open = opts.delimiters[0];
      const close = opts.delimiters[1];
      const matter2 = engine.stringify(data, options2).trim();
      let buf = "";
      if (matter2 !== "{}") {
        buf = newline(open) + newline(matter2) + newline(close);
      }
      if (typeof file.excerpt === "string" && file.excerpt !== "") {
        if (str2.indexOf(file.excerpt.trim()) === -1) {
          buf += newline(file.excerpt) + newline(close);
        }
      }
      return buf + newline(str2);
    };
    function newline(str2) {
      return str2.slice(-1) !== "\n" ? str2 + "\n" : str2;
    }
  }
});

// node_modules/gray-matter/lib/excerpt.js
var require_excerpt = __commonJS({
  "node_modules/gray-matter/lib/excerpt.js"(exports2, module2) {
    "use strict";
    var defaults = require_defaults();
    module2.exports = function(file, options2) {
      const opts = defaults(options2);
      if (file.data == null) {
        file.data = {};
      }
      if (typeof opts.excerpt === "function") {
        return opts.excerpt(file, opts);
      }
      const sep = file.data.excerpt_separator || opts.excerpt_separator;
      if (sep == null && (opts.excerpt === false || opts.excerpt == null)) {
        return file;
      }
      const delimiter = typeof opts.excerpt === "string" ? opts.excerpt : sep || opts.delimiters[0];
      const idx = file.content.indexOf(delimiter);
      if (idx !== -1) {
        file.excerpt = file.content.slice(0, idx);
      }
      return file;
    };
  }
});

// node_modules/gray-matter/lib/to-file.js
var require_to_file = __commonJS({
  "node_modules/gray-matter/lib/to-file.js"(exports2, module2) {
    "use strict";
    var typeOf = require_kind_of();
    var stringify = require_stringify();
    var utils = require_utils();
    module2.exports = function(file) {
      if (typeOf(file) !== "object") {
        file = { content: file };
      }
      if (typeOf(file.data) !== "object") {
        file.data = {};
      }
      if (file.contents && file.content == null) {
        file.content = file.contents;
      }
      utils.define(file, "orig", utils.toBuffer(file.content));
      utils.define(file, "language", file.language || "");
      utils.define(file, "matter", file.matter || "");
      utils.define(file, "stringify", function(data, options2) {
        if (options2 && options2.language) {
          file.language = options2.language;
        }
        return stringify(file, data, options2);
      });
      file.content = utils.toString(file.content);
      file.isEmpty = false;
      file.excerpt = "";
      return file;
    };
  }
});

// node_modules/gray-matter/lib/parse.js
var require_parse = __commonJS({
  "node_modules/gray-matter/lib/parse.js"(exports2, module2) {
    "use strict";
    var getEngine = require_engine();
    var defaults = require_defaults();
    module2.exports = function(language, str2, options2) {
      const opts = defaults(options2);
      const engine = getEngine(language, opts);
      if (typeof engine.parse !== "function") {
        throw new TypeError('expected "' + language + '.parse" to be a function');
      }
      return engine.parse(str2, opts);
    };
  }
});

// node_modules/gray-matter/index.js
var require_gray_matter = __commonJS({
  "node_modules/gray-matter/index.js"(exports2, module2) {
    "use strict";
    var fs = require("fs");
    var sections = require_section_matter();
    var defaults = require_defaults();
    var stringify = require_stringify();
    var excerpt = require_excerpt();
    var engines2 = require_engines();
    var toFile = require_to_file();
    var parse2 = require_parse();
    var utils = require_utils();
    function matter2(input, options2) {
      if (input === "") {
        return { data: {}, content: input, excerpt: "", orig: input };
      }
      let file = toFile(input);
      const cached = matter2.cache[file.content];
      if (!options2) {
        if (cached) {
          file = Object.assign({}, cached);
          file.orig = cached.orig;
          return file;
        }
        matter2.cache[file.content] = file;
      }
      return parseMatter(file, options2);
    }
    function parseMatter(file, options2) {
      const opts = defaults(options2);
      const open = opts.delimiters[0];
      const close = "\n" + opts.delimiters[1];
      let str2 = file.content;
      if (opts.language) {
        file.language = opts.language;
      }
      const openLen = open.length;
      if (!utils.startsWith(str2, open, openLen)) {
        excerpt(file, opts);
        return file;
      }
      if (str2.charAt(openLen) === open.slice(-1)) {
        return file;
      }
      str2 = str2.slice(openLen);
      const len = str2.length;
      const language = matter2.language(str2, opts);
      if (language.name) {
        file.language = language.name;
        str2 = str2.slice(language.raw.length);
      }
      let closeIndex = str2.indexOf(close);
      if (closeIndex === -1) {
        closeIndex = len;
      }
      file.matter = str2.slice(0, closeIndex);
      const block2 = file.matter.replace(/^\s*#[^\n]+/gm, "").trim();
      if (block2 === "") {
        file.isEmpty = true;
        file.empty = file.content;
        file.data = {};
      } else {
        file.data = parse2(file.language, file.matter, opts);
      }
      if (closeIndex === len) {
        file.content = "";
      } else {
        file.content = str2.slice(closeIndex + close.length);
        if (file.content[0] === "\r") {
          file.content = file.content.slice(1);
        }
        if (file.content[0] === "\n") {
          file.content = file.content.slice(1);
        }
      }
      excerpt(file, opts);
      if (opts.sections === true || typeof opts.section === "function") {
        sections(file, opts.section);
      }
      return file;
    }
    matter2.engines = engines2;
    matter2.stringify = function(file, data, options2) {
      if (typeof file === "string") file = matter2(file, options2);
      return stringify(file, data, options2);
    };
    matter2.read = function(filepath, options2) {
      const str2 = fs.readFileSync(filepath, "utf8");
      const file = matter2(str2, options2);
      file.path = filepath;
      return file;
    };
    matter2.test = function(str2, options2) {
      return utils.startsWith(str2, defaults(options2).delimiters[0]);
    };
    matter2.language = function(str2, options2) {
      const opts = defaults(options2);
      const open = opts.delimiters[0];
      if (matter2.test(str2)) {
        str2 = str2.slice(open.length);
      }
      const language = str2.slice(0, str2.search(/\r?\n/));
      return {
        raw: language,
        name: language ? language.trim() : ""
      };
    };
    matter2.cache = {};
    matter2.clearCache = function() {
      matter2.cache = {};
    };
    module2.exports = matter2;
  }
});

// src/entry.ts
var entry_exports = {};
__export(entry_exports, {
  default: () => Base
});
module.exports = __toCommonJS(entry_exports);
var import_obsidian13 = require("obsidian");

// src/ui/text_view.ts
var import_obsidian12 = require("obsidian");

// node_modules/svelte/src/internal/client/constants.js
var DERIVED = 1 << 1;
var EFFECT = 1 << 2;
var RENDER_EFFECT = 1 << 3;
var MANAGED_EFFECT = 1 << 24;
var BLOCK_EFFECT = 1 << 4;
var BRANCH_EFFECT = 1 << 5;
var ROOT_EFFECT = 1 << 6;
var BOUNDARY_EFFECT = 1 << 7;
var CONNECTED = 1 << 9;
var CLEAN = 1 << 10;
var DIRTY = 1 << 11;
var MAYBE_DIRTY = 1 << 12;
var INERT = 1 << 13;
var DESTROYED = 1 << 14;
var REACTION_RAN = 1 << 15;
var DESTROYING = 1 << 25;
var EFFECT_TRANSPARENT = 1 << 16;
var EAGER_EFFECT = 1 << 17;
var HEAD_EFFECT = 1 << 18;
var EFFECT_PRESERVED = 1 << 19;
var USER_EFFECT = 1 << 20;
var EFFECT_OFFSCREEN = 1 << 25;
var WAS_MARKED = 1 << 16;
var REACTION_IS_UPDATING = 1 << 21;
var ASYNC = 1 << 22;
var ERROR_VALUE = 1 << 23;
var STATE_SYMBOL = /* @__PURE__ */ Symbol("$state");
var LEGACY_PROPS = /* @__PURE__ */ Symbol("legacy props");
var LOADING_ATTR_SYMBOL = /* @__PURE__ */ Symbol("");
var PROXY_PATH_SYMBOL = /* @__PURE__ */ Symbol("proxy path");
var ATTRIBUTES_CACHE = /* @__PURE__ */ Symbol("attributes");
var CLASS_CACHE = /* @__PURE__ */ Symbol("class");
var STYLE_CACHE = /* @__PURE__ */ Symbol("style");
var TEXT_CACHE = /* @__PURE__ */ Symbol("text");
var FORM_RESET_HANDLER = /* @__PURE__ */ Symbol("form reset");
var HMR_ANCHOR = /* @__PURE__ */ Symbol("hmr anchor");
var STALE_REACTION = new class StaleReactionError extends Error {
  constructor() {
    super(...arguments);
    __publicField(this, "name", "StaleReactionError");
    __publicField(this, "message", "The reaction that called `getAbortSignal()` was re-run or destroyed");
  }
}();
var _a;
var IS_XHTML = (
  // We gotta write it like this because after downleveling the pure comment may end up in the wrong location
  !!((_a = globalThis.document) == null ? void 0 : _a.contentType) && /* @__PURE__ */ globalThis.document.contentType.includes("xml")
);
var TEXT_NODE = 3;
var COMMENT_NODE = 8;

// node_modules/esm-env/dev-fallback.js
var _a2, _b;
var node_env = (_b = (_a2 = globalThis.process) == null ? void 0 : _a2.env) == null ? void 0 : _b.NODE_ENV;
var dev_fallback_default = node_env && !node_env.toLowerCase().startsWith("prod");

// node_modules/svelte/src/internal/shared/utils.js
var is_array = Array.isArray;
var index_of = Array.prototype.indexOf;
var includes = Array.prototype.includes;
var array_from = Array.from;
var object_keys = Object.keys;
var define_property = Object.defineProperty;
var get_descriptor = Object.getOwnPropertyDescriptor;
var get_descriptors = Object.getOwnPropertyDescriptors;
var object_prototype = Object.prototype;
var array_prototype = Array.prototype;
var get_prototype_of = Object.getPrototypeOf;
var is_extensible = Object.isExtensible;
var noop = () => {
};
function run(fn) {
  return fn();
}
function run_all(arr) {
  for (var i = 0; i < arr.length; i++) {
    arr[i]();
  }
}
function deferred() {
  var resolve;
  var reject;
  var promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}
function fallback(value, fallback2, lazy = false) {
  return value === void 0 ? lazy ? (
    /** @type {() => V} */
    fallback2()
  ) : (
    /** @type {V} */
    fallback2
  ) : value;
}

// node_modules/svelte/src/internal/client/reactivity/equality.js
function equals(value) {
  return value === this.v;
}
function safe_not_equal(a, b) {
  return a != a ? b == b : a !== b || a !== null && typeof a === "object" || typeof a === "function";
}
function safe_equals(value) {
  return !safe_not_equal(value, this.v);
}

// node_modules/svelte/src/internal/shared/errors.js
function invariant_violation(message) {
  if (dev_fallback_default) {
    const error = new Error(`invariant_violation
An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app \u2014 please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${message}"
https://svelte.dev/e/invariant_violation`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/invariant_violation`);
  }
}
function lifecycle_outside_component(name) {
  if (dev_fallback_default) {
    const error = new Error(`lifecycle_outside_component
\`${name}(...)\` can only be used during component initialisation
https://svelte.dev/e/lifecycle_outside_component`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/lifecycle_outside_component`);
  }
}

// node_modules/svelte/src/internal/client/errors.js
function async_derived_orphan() {
  if (dev_fallback_default) {
    const error = new Error(`async_derived_orphan
Cannot create a \`$derived(...)\` with an \`await\` expression outside of an effect tree
https://svelte.dev/e/async_derived_orphan`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/async_derived_orphan`);
  }
}
function bind_invalid_checkbox_value() {
  if (dev_fallback_default) {
    const error = new Error(`bind_invalid_checkbox_value
Using \`bind:value\` together with a checkbox input is not allowed. Use \`bind:checked\` instead
https://svelte.dev/e/bind_invalid_checkbox_value`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/bind_invalid_checkbox_value`);
  }
}
function derived_references_self() {
  if (dev_fallback_default) {
    const error = new Error(`derived_references_self
A derived value cannot reference itself recursively
https://svelte.dev/e/derived_references_self`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/derived_references_self`);
  }
}
function each_key_duplicate(a, b, value) {
  if (dev_fallback_default) {
    const error = new Error(`each_key_duplicate
${value ? `Keyed each block has duplicate key \`${value}\` at indexes ${a} and ${b}` : `Keyed each block has duplicate key at indexes ${a} and ${b}`}
https://svelte.dev/e/each_key_duplicate`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/each_key_duplicate`);
  }
}
function each_key_volatile(index2, a, b) {
  if (dev_fallback_default) {
    const error = new Error(`each_key_volatile
Keyed each block has key that is not idempotent \u2014 the key for item at index ${index2} was \`${a}\` but is now \`${b}\`. Keys must be the same each time for a given item
https://svelte.dev/e/each_key_volatile`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/each_key_volatile`);
  }
}
function effect_in_teardown(rune) {
  if (dev_fallback_default) {
    const error = new Error(`effect_in_teardown
\`${rune}\` cannot be used inside an effect cleanup function
https://svelte.dev/e/effect_in_teardown`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/effect_in_teardown`);
  }
}
function effect_in_unowned_derived() {
  if (dev_fallback_default) {
    const error = new Error(`effect_in_unowned_derived
Effect cannot be created inside a \`$derived\` value that was not itself created inside an effect
https://svelte.dev/e/effect_in_unowned_derived`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/effect_in_unowned_derived`);
  }
}
function effect_orphan(rune) {
  if (dev_fallback_default) {
    const error = new Error(`effect_orphan
\`${rune}\` can only be used inside an effect (e.g. during component initialisation)
https://svelte.dev/e/effect_orphan`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/effect_orphan`);
  }
}
function effect_update_depth_exceeded() {
  if (dev_fallback_default) {
    const error = new Error(`effect_update_depth_exceeded
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state
https://svelte.dev/e/effect_update_depth_exceeded`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);
  }
}
function hydration_failed() {
  if (dev_fallback_default) {
    const error = new Error(`hydration_failed
Failed to hydrate the application
https://svelte.dev/e/hydration_failed`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/hydration_failed`);
  }
}
function lifecycle_legacy_only(name) {
  if (dev_fallback_default) {
    const error = new Error(`lifecycle_legacy_only
\`${name}(...)\` cannot be used in runes mode
https://svelte.dev/e/lifecycle_legacy_only`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/lifecycle_legacy_only`);
  }
}
function props_invalid_value(key2) {
  if (dev_fallback_default) {
    const error = new Error(`props_invalid_value
Cannot do \`bind:${key2}={undefined}\` when \`${key2}\` has a fallback value
https://svelte.dev/e/props_invalid_value`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/props_invalid_value`);
  }
}
function rune_outside_svelte(rune) {
  if (dev_fallback_default) {
    const error = new Error(`rune_outside_svelte
The \`${rune}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files
https://svelte.dev/e/rune_outside_svelte`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/rune_outside_svelte`);
  }
}
function state_descriptors_fixed() {
  if (dev_fallback_default) {
    const error = new Error(`state_descriptors_fixed
Property descriptors defined on \`$state\` objects must contain \`value\` and always be \`enumerable\`, \`configurable\` and \`writable\`.
https://svelte.dev/e/state_descriptors_fixed`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/state_descriptors_fixed`);
  }
}
function state_prototype_fixed() {
  if (dev_fallback_default) {
    const error = new Error(`state_prototype_fixed
Cannot set prototype of \`$state\` object
https://svelte.dev/e/state_prototype_fixed`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/state_prototype_fixed`);
  }
}
function state_unsafe_mutation() {
  if (dev_fallback_default) {
    const error = new Error(`state_unsafe_mutation
Updating state inside \`$derived(...)\`, \`$inspect(...)\` or a template expression is forbidden. If the value should not be reactive, declare it without \`$state\`
https://svelte.dev/e/state_unsafe_mutation`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/state_unsafe_mutation`);
  }
}
function svelte_boundary_reset_onerror() {
  if (dev_fallback_default) {
    const error = new Error(`svelte_boundary_reset_onerror
A \`<svelte:boundary>\` \`reset\` function cannot be called while an error is still being handled
https://svelte.dev/e/svelte_boundary_reset_onerror`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`);
  }
}

// node_modules/svelte/src/internal/flags/index.js
var async_mode_flag = false;
var legacy_mode_flag = false;
var tracing_mode_flag = false;
function enable_legacy_mode_flag() {
  legacy_mode_flag = true;
}

// node_modules/svelte/src/constants.js
var EACH_ITEM_REACTIVE = 1;
var EACH_INDEX_REACTIVE = 1 << 1;
var EACH_IS_CONTROLLED = 1 << 2;
var EACH_IS_ANIMATED = 1 << 3;
var EACH_ITEM_IMMUTABLE = 1 << 4;
var PROPS_IS_IMMUTABLE = 1;
var PROPS_IS_RUNES = 1 << 1;
var PROPS_IS_UPDATED = 1 << 2;
var PROPS_IS_BINDABLE = 1 << 3;
var PROPS_IS_LAZY_INITIAL = 1 << 4;
var TRANSITION_OUT = 1 << 1;
var TRANSITION_GLOBAL = 1 << 2;
var TEMPLATE_FRAGMENT = 1;
var TEMPLATE_USE_IMPORT_NODE = 1 << 1;
var TEMPLATE_USE_SVG = 1 << 2;
var TEMPLATE_USE_MATHML = 1 << 3;
var HYDRATION_START = "[";
var HYDRATION_START_ELSE = "[!";
var HYDRATION_START_FAILED = "[?";
var HYDRATION_END = "]";
var HYDRATION_ERROR = {};
var ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1;
var ELEMENT_IS_INPUT = 1 << 2;
var UNINITIALIZED = /* @__PURE__ */ Symbol("uninitialized");
var FILENAME = /* @__PURE__ */ Symbol("filename");
var NAMESPACE_HTML = "http://www.w3.org/1999/xhtml";
var ATTACHMENT_KEY = "@attach";

// node_modules/svelte/src/internal/client/dev/tracing.js
var tracing_expressions = null;
function tag(source2, label) {
  source2.label = label;
  tag_proxy(source2.v, label);
  return source2;
}
function tag_proxy(value, label) {
  var _a5;
  (_a5 = value == null ? void 0 : value[PROXY_PATH_SYMBOL]) == null ? void 0 : _a5.call(value, label);
  return value;
}

// node_modules/svelte/src/internal/shared/dev.js
function get_error(label) {
  const error = new Error();
  const stack2 = get_stack();
  if (stack2.length === 0) {
    return null;
  }
  stack2.unshift("\n");
  define_property(error, "stack", {
    value: stack2.join("\n")
  });
  define_property(error, "name", {
    value: label
  });
  return (
    /** @type {Error & { stack: string }} */
    error
  );
}
function get_stack() {
  const limit = Error.stackTraceLimit;
  Error.stackTraceLimit = Infinity;
  const stack2 = new Error().stack;
  Error.stackTraceLimit = limit;
  if (!stack2) return [];
  const lines = stack2.split("\n");
  const new_lines = [];
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const posixified = line.replaceAll("\\", "/");
    if (line.trim() === "Error") {
      continue;
    }
    if (line.includes("validate_each_keys")) {
      return [];
    }
    if (posixified.includes("svelte/src/internal") || posixified.includes("node_modules/.vite")) {
      continue;
    }
    new_lines.push(line);
  }
  return new_lines;
}
function invariant(condition, message) {
  if (!dev_fallback_default) {
    throw new Error("invariant(...) was not guarded by if (DEV)");
  }
  if (!condition) invariant_violation(message);
}

// node_modules/svelte/src/internal/client/context.js
var component_context = null;
function set_component_context(context) {
  component_context = context;
}
var dev_stack = null;
function set_dev_stack(stack2) {
  dev_stack = stack2;
}
var dev_current_component_function = null;
function set_dev_current_component_function(fn) {
  dev_current_component_function = fn;
}
function push(props, runes = false, fn) {
  component_context = {
    p: component_context,
    i: false,
    c: null,
    e: null,
    s: props,
    x: null,
    r: (
      /** @type {Effect} */
      active_effect
    ),
    l: legacy_mode_flag && !runes ? { s: null, u: null, $: [] } : null
  };
  if (dev_fallback_default) {
    component_context.function = fn;
    dev_current_component_function = fn;
  }
}
function pop(component2) {
  var _a5;
  var context = (
    /** @type {ComponentContext} */
    component_context
  );
  var effects = context.e;
  if (effects !== null) {
    context.e = null;
    for (var fn of effects) {
      create_user_effect(fn);
    }
  }
  if (component2 !== void 0) {
    context.x = component2;
  }
  context.i = true;
  component_context = context.p;
  if (dev_fallback_default) {
    dev_current_component_function = (_a5 = component_context == null ? void 0 : component_context.function) != null ? _a5 : null;
  }
  return component2 != null ? component2 : (
    /** @type {T} */
    {}
  );
}
function is_runes() {
  return !legacy_mode_flag || component_context !== null && component_context.l === null;
}

// node_modules/svelte/src/internal/client/dom/task.js
var micro_tasks = [];
function run_micro_tasks() {
  var tasks = micro_tasks;
  micro_tasks = [];
  run_all(tasks);
}
function queue_micro_task(fn) {
  if (micro_tasks.length === 0 && !is_flushing_sync) {
    var tasks = micro_tasks;
    queueMicrotask(() => {
      if (tasks === micro_tasks) run_micro_tasks();
    });
  }
  micro_tasks.push(fn);
}
function flush_tasks() {
  while (micro_tasks.length > 0) {
    run_micro_tasks();
  }
}

// node_modules/svelte/src/internal/client/warnings.js
var bold = "font-weight: bold";
var normal = "font-weight: normal";
function await_reactivity_loss(name) {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] await_reactivity_loss
%cDetected reactivity loss when reading \`${name}\`. This happens when state is read in an async function after an earlier \`await\`
https://svelte.dev/e/await_reactivity_loss`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/await_reactivity_loss`);
  }
}
function await_waterfall(name, location) {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] await_waterfall
%cAn async derived, \`${name}\` (${location}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app
https://svelte.dev/e/await_waterfall`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/await_waterfall`);
  }
}
function derived_inert() {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] derived_inert
%cReading a derived belonging to a now-destroyed effect may result in stale values
https://svelte.dev/e/derived_inert`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/derived_inert`);
  }
}
function hydration_attribute_changed(attribute, html2, value) {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] hydration_attribute_changed
%cThe \`${attribute}\` attribute on \`${html2}\` changed its value between server and client renders. The client value, \`${value}\`, will be ignored in favour of the server value
https://svelte.dev/e/hydration_attribute_changed`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/hydration_attribute_changed`);
  }
}
function hydration_mismatch(location) {
  if (dev_fallback_default) {
    console.warn(
      `%c[svelte] hydration_mismatch
%c${location ? `Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}` : "Hydration failed because the initial UI does not match what was rendered on the server"}
https://svelte.dev/e/hydration_mismatch`,
      bold,
      normal
    );
  } else {
    console.warn(`https://svelte.dev/e/hydration_mismatch`);
  }
}
function lifecycle_double_unmount() {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] lifecycle_double_unmount
%cTried to unmount a component that was not mounted
https://svelte.dev/e/lifecycle_double_unmount`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/lifecycle_double_unmount`);
  }
}
function select_multiple_invalid_value() {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] select_multiple_invalid_value
%cThe \`value\` property of a \`<select multiple>\` element should be an array, but it received a non-array value. The selection will be kept as is.
https://svelte.dev/e/select_multiple_invalid_value`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/select_multiple_invalid_value`);
  }
}
function state_proxy_equality_mismatch(operator) {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] state_proxy_equality_mismatch
%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${operator}\` will produce unexpected results
https://svelte.dev/e/state_proxy_equality_mismatch`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/state_proxy_equality_mismatch`);
  }
}
function state_proxy_unmount() {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] state_proxy_unmount
%cTried to unmount a state proxy, rather than a component
https://svelte.dev/e/state_proxy_unmount`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/state_proxy_unmount`);
  }
}
function svelte_boundary_reset_noop() {
  if (dev_fallback_default) {
    console.warn(`%c[svelte] svelte_boundary_reset_noop
%cA \`<svelte:boundary>\` \`reset\` function only resets the boundary the first time it is called
https://svelte.dev/e/svelte_boundary_reset_noop`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`);
  }
}

// node_modules/svelte/src/internal/client/dom/hydration.js
var hydrating = false;
function set_hydrating(value) {
  hydrating = value;
}
var hydrate_node;
function set_hydrate_node(node) {
  if (node === null) {
    hydration_mismatch();
    throw HYDRATION_ERROR;
  }
  return hydrate_node = node;
}
function hydrate_next() {
  return set_hydrate_node(get_next_sibling(hydrate_node));
}
function reset(node) {
  if (!hydrating) return;
  if (get_next_sibling(hydrate_node) !== null) {
    hydration_mismatch();
    throw HYDRATION_ERROR;
  }
  hydrate_node = node;
}
function next(count = 1) {
  if (hydrating) {
    var i = count;
    var node = hydrate_node;
    while (i--) {
      node = /** @type {TemplateNode} */
      get_next_sibling(node);
    }
    hydrate_node = node;
  }
}
function skip_nodes(remove = true) {
  var depth = 0;
  var node = hydrate_node;
  while (true) {
    if (node.nodeType === COMMENT_NODE) {
      var data = (
        /** @type {Comment} */
        node.data
      );
      if (data === HYDRATION_END) {
        if (depth === 0) return node;
        depth -= 1;
      } else if (data === HYDRATION_START || data === HYDRATION_START_ELSE || // "[1", "[2", etc. for if blocks
      data[0] === "[" && !isNaN(Number(data.slice(1)))) {
        depth += 1;
      }
    }
    var next2 = (
      /** @type {TemplateNode} */
      get_next_sibling(node)
    );
    if (remove) node.remove();
    node = next2;
  }
}
function read_hydration_instruction(node) {
  if (!node || node.nodeType !== COMMENT_NODE) {
    hydration_mismatch();
    throw HYDRATION_ERROR;
  }
  return (
    /** @type {Comment} */
    node.data
  );
}

// node_modules/svelte/src/internal/client/proxy.js
var regex_is_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
function proxy(value) {
  if (typeof value !== "object" || value === null || STATE_SYMBOL in value) {
    return value;
  }
  const prototype = get_prototype_of(value);
  if (prototype !== object_prototype && prototype !== array_prototype) {
    return value;
  }
  var sources = /* @__PURE__ */ new Map();
  var is_proxied_array = is_array(value);
  var version = state(0);
  var stack2 = dev_fallback_default && tracing_mode_flag ? get_error("created at") : null;
  var parent_version = update_version;
  var with_parent = (fn) => {
    if (update_version === parent_version) {
      return fn();
    }
    var reaction = active_reaction;
    var version2 = update_version;
    set_active_reaction(null);
    set_update_version(parent_version);
    var result = fn();
    set_active_reaction(reaction);
    set_update_version(version2);
    return result;
  };
  if (is_proxied_array) {
    sources.set("length", state(
      /** @type {any[]} */
      value.length,
      stack2
    ));
    if (dev_fallback_default) {
      value = /** @type {any} */
      inspectable_array(
        /** @type {any[]} */
        value
      );
    }
  }
  var path = "";
  let updating = false;
  function update_path(new_path) {
    if (updating) return;
    updating = true;
    path = new_path;
    tag(version, `${path} version`);
    for (const [prop2, source2] of sources) {
      tag(source2, get_label(path, prop2));
    }
    updating = false;
  }
  return new Proxy(
    /** @type {any} */
    value,
    {
      defineProperty(_, prop2, descriptor) {
        if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) {
          state_descriptors_fixed();
        }
        var s = sources.get(prop2);
        if (s === void 0) {
          with_parent(() => {
            var s2 = state(descriptor.value, stack2);
            sources.set(prop2, s2);
            if (dev_fallback_default && typeof prop2 === "string") {
              tag(s2, get_label(path, prop2));
            }
            return s2;
          });
        } else {
          set(s, descriptor.value, true);
        }
        return true;
      },
      deleteProperty(target, prop2) {
        var s = sources.get(prop2);
        if (s === void 0) {
          if (prop2 in target) {
            const s2 = with_parent(() => state(UNINITIALIZED, stack2));
            sources.set(prop2, s2);
            increment(version);
            if (dev_fallback_default) {
              tag(s2, get_label(path, prop2));
            }
          }
        } else {
          set(s, UNINITIALIZED);
          increment(version);
        }
        return true;
      },
      get(target, prop2, receiver) {
        var _a5;
        if (prop2 === STATE_SYMBOL) {
          return value;
        }
        if (dev_fallback_default && prop2 === PROXY_PATH_SYMBOL) {
          return update_path;
        }
        var s = sources.get(prop2);
        var exists = prop2 in target;
        if (s === void 0 && (!exists || ((_a5 = get_descriptor(target, prop2)) == null ? void 0 : _a5.writable))) {
          s = with_parent(() => {
            var p = proxy(exists ? target[prop2] : UNINITIALIZED);
            var s2 = state(p, stack2);
            if (dev_fallback_default) {
              tag(s2, get_label(path, prop2));
            }
            return s2;
          });
          sources.set(prop2, s);
        }
        if (s !== void 0) {
          var v = get(s);
          return v === UNINITIALIZED ? void 0 : v;
        }
        return Reflect.get(target, prop2, receiver);
      },
      getOwnPropertyDescriptor(target, prop2) {
        var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
        if (descriptor && "value" in descriptor) {
          var s = sources.get(prop2);
          if (s) descriptor.value = get(s);
        } else if (descriptor === void 0) {
          var source2 = sources.get(prop2);
          var value2 = source2 == null ? void 0 : source2.v;
          if (source2 !== void 0 && value2 !== UNINITIALIZED) {
            return {
              enumerable: true,
              configurable: true,
              value: value2,
              writable: true
            };
          }
        }
        return descriptor;
      },
      has(target, prop2) {
        var _a5;
        if (prop2 === STATE_SYMBOL) {
          return true;
        }
        var s = sources.get(prop2);
        var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop2);
        if (s !== void 0 || active_effect !== null && (!has || ((_a5 = get_descriptor(target, prop2)) == null ? void 0 : _a5.writable))) {
          if (s === void 0) {
            s = with_parent(() => {
              var p = has ? proxy(target[prop2]) : UNINITIALIZED;
              var s2 = state(p, stack2);
              if (dev_fallback_default) {
                tag(s2, get_label(path, prop2));
              }
              return s2;
            });
            sources.set(prop2, s);
          }
          var value2 = get(s);
          if (value2 === UNINITIALIZED) {
            return false;
          }
        }
        return has;
      },
      set(target, prop2, value2, receiver) {
        var _a5;
        var s = sources.get(prop2);
        var has = prop2 in target;
        if (is_proxied_array && prop2 === "length") {
          for (var i = value2; i < /** @type {Source<number>} */
          s.v; i += 1) {
            var other_s = sources.get(i + "");
            if (other_s !== void 0) {
              set(other_s, UNINITIALIZED);
            } else if (i in target) {
              other_s = with_parent(() => state(UNINITIALIZED, stack2));
              sources.set(i + "", other_s);
              if (dev_fallback_default) {
                tag(other_s, get_label(path, i));
              }
            }
          }
        }
        if (s === void 0) {
          if (!has || ((_a5 = get_descriptor(target, prop2)) == null ? void 0 : _a5.writable)) {
            s = with_parent(() => state(void 0, stack2));
            if (dev_fallback_default) {
              tag(s, get_label(path, prop2));
            }
            set(s, proxy(value2));
            sources.set(prop2, s);
          }
        } else {
          has = s.v !== UNINITIALIZED;
          var p = with_parent(() => proxy(value2));
          set(s, p);
        }
        var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
        if (descriptor == null ? void 0 : descriptor.set) {
          descriptor.set.call(receiver, value2);
        }
        if (!has) {
          if (is_proxied_array && typeof prop2 === "string") {
            var ls = (
              /** @type {Source<number>} */
              sources.get("length")
            );
            var n = Number(prop2);
            if (Number.isInteger(n) && n >= ls.v) {
              set(ls, n + 1);
            }
          }
          increment(version);
        }
        return true;
      },
      ownKeys(target) {
        get(version);
        var own_keys = Reflect.ownKeys(target).filter((key3) => {
          var source3 = sources.get(key3);
          return source3 === void 0 || source3.v !== UNINITIALIZED;
        });
        for (var [key2, source2] of sources) {
          if (source2.v !== UNINITIALIZED && !(key2 in target)) {
            own_keys.push(key2);
          }
        }
        return own_keys;
      },
      setPrototypeOf() {
        state_prototype_fixed();
      }
    }
  );
}
function get_label(path, prop2) {
  var _a5;
  if (typeof prop2 === "symbol") return `${path}[Symbol(${(_a5 = prop2.description) != null ? _a5 : ""})]`;
  if (regex_is_valid_identifier.test(prop2)) return `${path}.${prop2}`;
  return /^\d+$/.test(prop2) ? `${path}[${prop2}]` : `${path}['${prop2}']`;
}
function get_proxied_value(value) {
  try {
    if (value !== null && typeof value === "object" && STATE_SYMBOL in value) {
      return value[STATE_SYMBOL];
    }
  } catch (e) {
  }
  return value;
}
function is(a, b) {
  return Object.is(get_proxied_value(a), get_proxied_value(b));
}
var ARRAY_MUTATING_METHODS = /* @__PURE__ */ new Set([
  "copyWithin",
  "fill",
  "pop",
  "push",
  "reverse",
  "shift",
  "sort",
  "splice",
  "unshift"
]);
function inspectable_array(array) {
  return new Proxy(array, {
    get(target, prop2, receiver) {
      var value = Reflect.get(target, prop2, receiver);
      if (!ARRAY_MUTATING_METHODS.has(
        /** @type {string} */
        prop2
      )) {
        return value;
      }
      return function(...args) {
        set_eager_effects_deferred();
        var result = value.apply(this, args);
        flush_eager_effects();
        return result;
      };
    }
  });
}

// node_modules/svelte/src/internal/client/dev/equality.js
function init_array_prototype_warnings() {
  const array_prototype2 = Array.prototype;
  const cleanup = Array.__svelte_cleanup;
  if (cleanup) {
    cleanup();
  }
  const { indexOf, lastIndexOf, includes: includes2 } = array_prototype2;
  array_prototype2.indexOf = function(item, from_index) {
    const index2 = indexOf.call(this, item, from_index);
    if (index2 === -1) {
      for (let i = from_index != null ? from_index : 0; i < this.length; i += 1) {
        if (get_proxied_value(this[i]) === item) {
          state_proxy_equality_mismatch("array.indexOf(...)");
          break;
        }
      }
    }
    return index2;
  };
  array_prototype2.lastIndexOf = function(item, from_index) {
    const index2 = lastIndexOf.call(this, item, from_index != null ? from_index : this.length - 1);
    if (index2 === -1) {
      for (let i = 0; i <= (from_index != null ? from_index : this.length - 1); i += 1) {
        if (get_proxied_value(this[i]) === item) {
          state_proxy_equality_mismatch("array.lastIndexOf(...)");
          break;
        }
      }
    }
    return index2;
  };
  array_prototype2.includes = function(item, from_index) {
    const has = includes2.call(this, item, from_index);
    if (!has) {
      for (let i = 0; i < this.length; i += 1) {
        if (get_proxied_value(this[i]) === item) {
          state_proxy_equality_mismatch("array.includes(...)");
          break;
        }
      }
    }
    return has;
  };
  Array.__svelte_cleanup = () => {
    array_prototype2.indexOf = indexOf;
    array_prototype2.lastIndexOf = lastIndexOf;
    array_prototype2.includes = includes2;
  };
}

// node_modules/svelte/src/internal/client/dom/operations.js
var $window;
var $document;
var is_firefox;
var first_child_getter;
var next_sibling_getter;
function init_operations() {
  if ($window !== void 0) {
    return;
  }
  $window = window;
  $document = document;
  is_firefox = /Firefox/.test(navigator.userAgent);
  var element_prototype = Element.prototype;
  var node_prototype = Node.prototype;
  var text_prototype = Text.prototype;
  first_child_getter = get_descriptor(node_prototype, "firstChild").get;
  next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get;
  if (is_extensible(element_prototype)) {
    element_prototype[CLASS_CACHE] = void 0;
    element_prototype[ATTRIBUTES_CACHE] = null;
    element_prototype[STYLE_CACHE] = void 0;
    element_prototype.__e = void 0;
  }
  if (is_extensible(text_prototype)) {
    text_prototype[TEXT_CACHE] = void 0;
  }
  if (dev_fallback_default) {
    element_prototype.__svelte_meta = null;
    init_array_prototype_warnings();
  }
}
function create_text(value = "") {
  return document.createTextNode(value);
}
// @__NO_SIDE_EFFECTS__
function get_first_child(node) {
  return (
    /** @type {TemplateNode | null} */
    first_child_getter.call(node)
  );
}
// @__NO_SIDE_EFFECTS__
function get_next_sibling(node) {
  return (
    /** @type {TemplateNode | null} */
    next_sibling_getter.call(node)
  );
}
function child(node, is_text) {
  if (!hydrating) {
    return /* @__PURE__ */ get_first_child(node);
  }
  var child2 = /* @__PURE__ */ get_first_child(hydrate_node);
  if (child2 === null) {
    child2 = hydrate_node.appendChild(create_text());
  } else if (is_text && child2.nodeType !== TEXT_NODE) {
    var text2 = create_text();
    child2 == null ? void 0 : child2.before(text2);
    set_hydrate_node(text2);
    return text2;
  }
  if (is_text) {
    merge_text_nodes(
      /** @type {Text} */
      child2
    );
  }
  set_hydrate_node(child2);
  return child2;
}
function first_child(node, is_text = false) {
  var _a5, _b3;
  if (!hydrating) {
    var first = /* @__PURE__ */ get_first_child(node);
    if (first instanceof Comment && first.data === "") return /* @__PURE__ */ get_next_sibling(first);
    return first;
  }
  if (is_text) {
    if (((_a5 = hydrate_node) == null ? void 0 : _a5.nodeType) !== TEXT_NODE) {
      var text2 = create_text();
      (_b3 = hydrate_node) == null ? void 0 : _b3.before(text2);
      set_hydrate_node(text2);
      return text2;
    }
    merge_text_nodes(
      /** @type {Text} */
      hydrate_node
    );
  }
  return hydrate_node;
}
function sibling(node, count = 1, is_text = false) {
  let next_sibling = hydrating ? hydrate_node : node;
  var last_sibling;
  while (count--) {
    last_sibling = next_sibling;
    next_sibling = /** @type {TemplateNode} */
    /* @__PURE__ */ get_next_sibling(next_sibling);
  }
  if (!hydrating) {
    return next_sibling;
  }
  if (is_text) {
    if ((next_sibling == null ? void 0 : next_sibling.nodeType) !== TEXT_NODE) {
      var text2 = create_text();
      if (next_sibling === null) {
        last_sibling == null ? void 0 : last_sibling.after(text2);
      } else {
        next_sibling.before(text2);
      }
      set_hydrate_node(text2);
      return text2;
    }
    merge_text_nodes(
      /** @type {Text} */
      next_sibling
    );
  }
  set_hydrate_node(next_sibling);
  return next_sibling;
}
function clear_text_content(node) {
  node.textContent = "";
}
function should_defer_append() {
  if (!async_mode_flag) return false;
  if (eager_block_effects !== null) return false;
  var flags2 = (
    /** @type {Effect} */
    active_effect.f
  );
  return (flags2 & REACTION_RAN) !== 0;
}
function create_element(tag2, namespace, is2) {
  if (namespace == null || namespace === NAMESPACE_HTML) {
    return (
      /** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */
      is2 ? document.createElement(tag2, { is: is2 }) : document.createElement(tag2)
    );
  }
  return (
    /** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */
    is2 ? document.createElementNS(namespace, tag2, { is: is2 }) : document.createElementNS(namespace, tag2)
  );
}
function merge_text_nodes(text2) {
  if (
    /** @type {string} */
    text2.nodeValue.length < 65536
  ) {
    return;
  }
  let next2 = text2.nextSibling;
  while (next2 !== null && next2.nodeType === TEXT_NODE) {
    next2.remove();
    text2.nodeValue += /** @type {string} */
    next2.nodeValue;
    next2 = text2.nextSibling;
  }
}

// node_modules/svelte/src/internal/client/error-handling.js
var adjustments = /* @__PURE__ */ new WeakMap();
function handle_error(error) {
  var effect2 = active_effect;
  if (effect2 === null) {
    active_reaction.f |= ERROR_VALUE;
    return error;
  }
  if (dev_fallback_default && error instanceof Error && !adjustments.has(error)) {
    adjustments.set(error, get_adjustments(error, effect2));
  }
  if ((effect2.f & REACTION_RAN) === 0 && (effect2.f & EFFECT) === 0) {
    if (dev_fallback_default && !effect2.parent && error instanceof Error) {
      apply_adjustments(error);
    }
    throw error;
  }
  invoke_error_boundary(error, effect2);
}
function invoke_error_boundary(error, effect2) {
  while (effect2 !== null) {
    if ((effect2.f & BOUNDARY_EFFECT) !== 0) {
      if ((effect2.f & REACTION_RAN) === 0) {
        throw error;
      }
      try {
        effect2.b.error(error);
        return;
      } catch (e) {
        error = e;
      }
    }
    effect2 = effect2.parent;
  }
  if (dev_fallback_default && error instanceof Error) {
    apply_adjustments(error);
  }
  throw error;
}
function get_adjustments(error, effect2) {
  var _a5, _b3, _c2;
  const message_descriptor = get_descriptor(error, "message");
  if (message_descriptor && !message_descriptor.configurable) return;
  var indent = is_firefox ? "  " : "	";
  var component_stack = `
${indent}in ${((_a5 = effect2.fn) == null ? void 0 : _a5.name) || "<unknown>"}`;
  var context = effect2.ctx;
  while (context !== null) {
    component_stack += `
${indent}in ${(_b3 = context.function) == null ? void 0 : _b3[FILENAME].split("/").pop()}`;
    context = context.p;
  }
  return {
    message: error.message + `
${component_stack}
`,
    stack: (_c2 = error.stack) == null ? void 0 : _c2.split("\n").filter((line) => !line.includes("svelte/src/internal")).join("\n")
  };
}
function apply_adjustments(error) {
  const adjusted = adjustments.get(error);
  if (adjusted) {
    define_property(error, "message", {
      value: adjusted.message
    });
    define_property(error, "stack", {
      value: adjusted.stack
    });
  }
}

// node_modules/svelte/src/internal/client/reactivity/status.js
var STATUS_MASK = ~(DIRTY | MAYBE_DIRTY | CLEAN);
function set_signal_status(signal, status) {
  signal.f = signal.f & STATUS_MASK | status;
}
function update_derived_status(derived3) {
  if ((derived3.f & CONNECTED) !== 0 || derived3.deps === null) {
    set_signal_status(derived3, CLEAN);
  } else {
    set_signal_status(derived3, MAYBE_DIRTY);
  }
}

// node_modules/svelte/src/internal/client/reactivity/utils.js
function clear_marked(deps) {
  if (deps === null) return;
  for (const dep of deps) {
    if ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) {
      continue;
    }
    dep.f ^= WAS_MARKED;
    clear_marked(
      /** @type {Derived} */
      dep.deps
    );
  }
}
function defer_effect(effect2, dirty_effects, maybe_dirty_effects) {
  if ((effect2.f & DIRTY) !== 0) {
    dirty_effects.add(effect2);
  } else if ((effect2.f & MAYBE_DIRTY) !== 0) {
    maybe_dirty_effects.add(effect2);
  }
  clear_marked(effect2.deps);
  set_signal_status(effect2, CLEAN);
}

// node_modules/svelte/src/store/utils.js
function subscribe_to_store(store, run3, invalidate) {
  if (store == null) {
    run3(void 0);
    if (invalidate) invalidate(void 0);
    return noop;
  }
  const unsub = untrack(
    () => store.subscribe(
      run3,
      // @ts-expect-error
      invalidate
    )
  );
  return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}

// node_modules/svelte/src/store/shared/index.js
var subscriber_queue = [];
function readable(value, start) {
  return {
    subscribe: writable(value, start).subscribe
  };
}
function writable(value, start = noop) {
  let stop = null;
  const subscribers = /* @__PURE__ */ new Set();
  function set2(new_value) {
    if (safe_not_equal(value, new_value)) {
      value = new_value;
      if (stop) {
        const run_queue = !subscriber_queue.length;
        for (const subscriber of subscribers) {
          subscriber[1]();
          subscriber_queue.push(subscriber, value);
        }
        if (run_queue) {
          for (let i = 0; i < subscriber_queue.length; i += 2) {
            subscriber_queue[i][0](subscriber_queue[i + 1]);
          }
          subscriber_queue.length = 0;
        }
      }
    }
  }
  function update2(fn) {
    set2(fn(
      /** @type {T} */
      value
    ));
  }
  function subscribe(run3, invalidate = noop) {
    const subscriber = [run3, invalidate];
    subscribers.add(subscriber);
    if (subscribers.size === 1) {
      stop = start(set2, update2) || noop;
    }
    run3(
      /** @type {T} */
      value
    );
    return () => {
      subscribers.delete(subscriber);
      if (subscribers.size === 0 && stop) {
        stop();
        stop = null;
      }
    };
  }
  return { set: set2, update: update2, subscribe };
}
function derived(stores, fn, initial_value) {
  const single = !Array.isArray(stores);
  const stores_array = single ? [stores] : stores;
  if (!stores_array.every(Boolean)) {
    throw new Error("derived() expects stores as input, got a falsy value");
  }
  const auto = fn.length < 2;
  return readable(initial_value, (set2, update2) => {
    let started = false;
    const values = [];
    let pending2 = 0;
    let cleanup = noop;
    const sync = () => {
      if (pending2) {
        return;
      }
      cleanup();
      const result = fn(single ? values[0] : values, set2, update2);
      if (auto) {
        set2(result);
      } else {
        cleanup = typeof result === "function" ? result : noop;
      }
    };
    const unsubscribers = stores_array.map(
      (store, i) => subscribe_to_store(
        store,
        (value) => {
          values[i] = value;
          pending2 &= ~(1 << i);
          if (started) {
            sync();
          }
        },
        () => {
          pending2 |= 1 << i;
        }
      )
    );
    started = true;
    sync();
    return function stop() {
      run_all(unsubscribers);
      cleanup();
      started = false;
    };
  });
}
function get2(store) {
  let value;
  subscribe_to_store(store, (_) => value = _)();
  return value;
}

// node_modules/svelte/src/internal/client/reactivity/store.js
var legacy_is_updating_store = false;
var is_store_binding = false;
var IS_UNMOUNTED = /* @__PURE__ */ Symbol("unmounted");
function store_get(store, store_name, stores) {
  var _a5;
  const entry = (_a5 = stores[store_name]) != null ? _a5 : stores[store_name] = {
    store: null,
    source: mutable_source(void 0),
    unsubscribe: noop
  };
  if (dev_fallback_default) {
    entry.source.label = store_name;
  }
  if (entry.store !== store && !(IS_UNMOUNTED in stores)) {
    entry.unsubscribe();
    entry.store = store != null ? store : null;
    if (store == null) {
      entry.source.v = void 0;
      entry.unsubscribe = noop;
    } else {
      var is_synchronous_callback = true;
      entry.unsubscribe = subscribe_to_store(store, (v) => {
        if (is_synchronous_callback) {
          entry.source.v = v;
        } else {
          set(entry.source, v);
        }
      });
      is_synchronous_callback = false;
    }
  }
  if (store && IS_UNMOUNTED in stores) {
    return get2(store);
  }
  return get(entry.source);
}
function setup_stores() {
  const stores = {};
  function cleanup() {
    teardown(() => {
      for (var store_name in stores) {
        const ref = stores[store_name];
        ref.unsubscribe();
      }
      define_property(stores, IS_UNMOUNTED, {
        enumerable: false,
        value: true
      });
    });
  }
  return [stores, cleanup];
}
function update_with_flag(store, value) {
  legacy_is_updating_store = true;
  try {
    store.set(value);
  } finally {
    legacy_is_updating_store = false;
  }
}
function store_mutate(store, expression, new_value) {
  update_with_flag(store, new_value);
  return expression;
}
function capture_store_binding(fn) {
  var previous_is_store_binding = is_store_binding;
  try {
    is_store_binding = false;
    return [fn(), is_store_binding];
  } finally {
    is_store_binding = previous_is_store_binding;
  }
}

// node_modules/svelte/src/internal/client/reactivity/batch.js
var first_batch = null;
var last_batch = null;
var current_batch = null;
var previous_batch = null;
var batch_values = null;
var last_scheduled_effect = null;
var is_flushing_sync = false;
var is_processing = false;
var collected_effects = null;
var legacy_updates = null;
var flush_count = 0;
var source_stacks = /* @__PURE__ */ new Set();
var uid = 1;
var _started, _prev, _next, _commit_callbacks, _discard_callbacks, _pending, _blocking_pending, _deferred, _roots, _new_effects, _dirty_effects, _maybe_dirty_effects, _skipped_branches, _unskipped_branches, _decrement_queued, _Batch_instances, is_deferred_fn, process_fn, traverse_fn, find_earlier_batch_fn, merge_fn, defer_effects_fn, commit_fn, unlink_fn;
var _Batch = class _Batch {
  constructor() {
    __privateAdd(this, _Batch_instances);
    __publicField(this, "id", uid++);
    /** True as soon as `#process` was called */
    __privateAdd(this, _started, false);
    __publicField(this, "linked", true);
    /** @type {Batch | null} */
    __privateAdd(this, _prev, null);
    /** @type {Batch | null} */
    __privateAdd(this, _next, null);
    /** @type {Map<Effect, ReturnType<typeof deferred<any>>>} */
    __publicField(this, "async_deriveds", /* @__PURE__ */ new Map());
    /**
     * The current values of any signals that are updated in this batch.
     * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment)
     * They keys of this map are identical to `this.#previous`
     * @type {Map<Value, [any, boolean]>}
     */
    __publicField(this, "current", /* @__PURE__ */ new Map());
    /**
     * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place.
     * They keys of this map are identical to `this.#current`
     * @type {Map<Value, any>}
     */
    __publicField(this, "previous", /* @__PURE__ */ new Map());
    /**
     * When the batch is committed (and the DOM is updated), we need to remove old branches
     * and append new ones by calling the functions added inside (if/each/key/etc) blocks
     * @type {Set<(batch: Batch) => void>}
     */
    __privateAdd(this, _commit_callbacks, /* @__PURE__ */ new Set());
    /**
     * If a fork is discarded, we need to destroy any effects that are no longer needed
     * @type {Set<(batch: Batch) => void>}
     */
    __privateAdd(this, _discard_callbacks, /* @__PURE__ */ new Set());
    /**
     * The number of async effects that are currently in flight
     */
    __privateAdd(this, _pending, 0);
    /**
     * Async effects that are currently in flight, _not_ inside a pending boundary
     * @type {Map<Effect, number>}
     */
    __privateAdd(this, _blocking_pending, /* @__PURE__ */ new Map());
    /**
     * A deferred that resolves when the batch is committed, used with `settled()`
     * TODO replace with Promise.withResolvers once supported widely enough
     * @type {{ promise: Promise<void>, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null}
     */
    __privateAdd(this, _deferred, null);
    /**
     * The root effects that need to be flushed
     * @type {Effect[]}
     */
    __privateAdd(this, _roots, []);
    /**
     * Effects created while this batch was active.
     * @type {Effect[]}
     */
    __privateAdd(this, _new_effects, []);
    /**
     * Deferred effects (which run after async work has completed) that are DIRTY
     * @type {Set<Effect>}
     */
    __privateAdd(this, _dirty_effects, /* @__PURE__ */ new Set());
    /**
     * Deferred effects that are MAYBE_DIRTY
     * @type {Set<Effect>}
     */
    __privateAdd(this, _maybe_dirty_effects, /* @__PURE__ */ new Set());
    /**
     * A map of branches that still exist, but will be destroyed when this batch
     * is committed — we skip over these during `process`.
     * The value contains child effects that were dirty/maybe_dirty before being reset,
     * so they can be rescheduled if the branch survives.
     * @type {Map<Effect, { d: Effect[], m: Effect[] }>}
     */
    __privateAdd(this, _skipped_branches, /* @__PURE__ */ new Map());
    /**
     * Inverse of #skipped_branches which we need to tell prior batches to unskip them when committing
     * @type {Set<Effect>}
     */
    __privateAdd(this, _unskipped_branches, /* @__PURE__ */ new Set());
    __publicField(this, "is_fork", false);
    __privateAdd(this, _decrement_queued, false);
    if (last_batch === null) {
      first_batch = last_batch = this;
    } else {
      __privateSet(last_batch, _next, this);
      __privateSet(this, _prev, last_batch);
    }
    last_batch = this;
  }
  /**
   * Add an effect to the #skipped_branches map and reset its children
   * @param {Effect} effect
   */
  skip_effect(effect2) {
    if (!__privateGet(this, _skipped_branches).has(effect2)) {
      __privateGet(this, _skipped_branches).set(effect2, { d: [], m: [] });
    }
    __privateGet(this, _unskipped_branches).delete(effect2);
  }
  /**
   * Remove an effect from the #skipped_branches map and reschedule
   * any tracked dirty/maybe_dirty child effects
   * @param {Effect} effect
   * @param {(e: Effect) => void} callback
   */
  unskip_effect(effect2, callback = (e) => this.schedule(e)) {
    var tracked = __privateGet(this, _skipped_branches).get(effect2);
    if (tracked) {
      __privateGet(this, _skipped_branches).delete(effect2);
      for (var e of tracked.d) {
        set_signal_status(e, DIRTY);
        callback(e);
      }
      for (e of tracked.m) {
        set_signal_status(e, MAYBE_DIRTY);
        callback(e);
      }
    }
    __privateGet(this, _unskipped_branches).add(effect2);
  }
  /**
   * Associate a change to a given source with the current
   * batch, noting its previous and current values
   * @param {Value} source
   * @param {any} value
   * @param {boolean} [is_derived]
   */
  capture(source2, value, is_derived = false) {
    if (source2.v !== UNINITIALIZED && !this.previous.has(source2)) {
      this.previous.set(source2, source2.v);
    }
    if ((source2.f & ERROR_VALUE) === 0) {
      this.current.set(source2, [value, is_derived]);
      batch_values == null ? void 0 : batch_values.set(source2, value);
    }
    if (!this.is_fork) {
      source2.v = value;
    }
  }
  activate() {
    current_batch = this;
  }
  deactivate() {
    current_batch = null;
    batch_values = null;
  }
  flush() {
    try {
      if (dev_fallback_default) {
        source_stacks.clear();
      }
      is_processing = true;
      current_batch = this;
      __privateMethod(this, _Batch_instances, process_fn).call(this);
    } finally {
      flush_count = 0;
      last_scheduled_effect = null;
      collected_effects = null;
      legacy_updates = null;
      is_processing = false;
      current_batch = null;
      batch_values = null;
      old_values.clear();
      if (dev_fallback_default) {
        for (const source2 of source_stacks) {
          source2.updated = null;
        }
      }
    }
  }
  discard() {
    var _a5;
    for (const fn of __privateGet(this, _discard_callbacks)) fn(this);
    __privateGet(this, _discard_callbacks).clear();
    __privateMethod(this, _Batch_instances, unlink_fn).call(this);
    (_a5 = __privateGet(this, _deferred)) == null ? void 0 : _a5.resolve();
  }
  /**
   * @param {Effect} effect
   */
  register_created_effect(effect2) {
    __privateGet(this, _new_effects).push(effect2);
  }
  /**
   * @param {boolean} blocking
   * @param {Effect} effect
   */
  increment(blocking, effect2) {
    var _a5;
    __privateSet(this, _pending, __privateGet(this, _pending) + 1);
    if (blocking) {
      let blocking_pending_count = (_a5 = __privateGet(this, _blocking_pending).get(effect2)) != null ? _a5 : 0;
      __privateGet(this, _blocking_pending).set(effect2, blocking_pending_count + 1);
    }
  }
  /**
   * @param {boolean} blocking
   * @param {Effect} effect
   */
  decrement(blocking, effect2) {
    var _a5;
    __privateSet(this, _pending, __privateGet(this, _pending) - 1);
    if (blocking) {
      let blocking_pending_count = (_a5 = __privateGet(this, _blocking_pending).get(effect2)) != null ? _a5 : 0;
      if (blocking_pending_count === 1) {
        __privateGet(this, _blocking_pending).delete(effect2);
      } else {
        __privateGet(this, _blocking_pending).set(effect2, blocking_pending_count - 1);
      }
    }
    if (__privateGet(this, _decrement_queued)) return;
    __privateSet(this, _decrement_queued, true);
    queue_micro_task(() => {
      __privateSet(this, _decrement_queued, false);
      if (this.linked) {
        this.flush();
      }
    });
  }
  /**
   * @param {Set<Effect>} dirty_effects
   * @param {Set<Effect>} maybe_dirty_effects
   */
  transfer_effects(dirty_effects, maybe_dirty_effects) {
    for (const e of dirty_effects) {
      __privateGet(this, _dirty_effects).add(e);
    }
    for (const e of maybe_dirty_effects) {
      __privateGet(this, _maybe_dirty_effects).add(e);
    }
    dirty_effects.clear();
    maybe_dirty_effects.clear();
  }
  /** @param {(batch: Batch) => void} fn */
  oncommit(fn) {
    __privateGet(this, _commit_callbacks).add(fn);
  }
  /** @param {(batch: Batch) => void} fn */
  ondiscard(fn) {
    __privateGet(this, _discard_callbacks).add(fn);
  }
  settled() {
    var _a5;
    return ((_a5 = __privateGet(this, _deferred)) != null ? _a5 : __privateSet(this, _deferred, deferred())).promise;
  }
  static ensure() {
    if (current_batch === null) {
      const batch = current_batch = new _Batch();
      if (!is_processing && !is_flushing_sync) {
        queue_micro_task(() => {
          if (!__privateGet(batch, _started)) {
            batch.flush();
          }
        });
      }
    }
    return current_batch;
  }
  apply() {
    if (!async_mode_flag || !this.is_fork && __privateGet(this, _prev) === null && __privateGet(this, _next) === null) {
      batch_values = null;
      return;
    }
    batch_values = /* @__PURE__ */ new Map();
    for (const [source2, [value]] of this.current) {
      batch_values.set(source2, value);
    }
    for (let batch = first_batch; batch !== null; batch = __privateGet(batch, _next)) {
      if (batch === this || batch.is_fork) continue;
      var intersects = false;
      if (batch.id < this.id) {
        for (const [source2, [, is_derived]] of batch.current) {
          if (is_derived) continue;
          if (this.current.has(source2)) {
            intersects = true;
            break;
          }
        }
      }
      if (!intersects) {
        for (const [source2, previous] of batch.previous) {
          if (!batch_values.has(source2)) {
            batch_values.set(source2, previous);
          }
        }
      }
    }
  }
  /**
   *
   * @param {Effect} effect
   */
  schedule(effect2) {
    var _a5;
    last_scheduled_effect = effect2;
    if (((_a5 = effect2.b) == null ? void 0 : _a5.is_pending) && (effect2.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 && (effect2.f & REACTION_RAN) === 0) {
      effect2.b.defer_effect(effect2);
      return;
    }
    var e = effect2;
    while (e.parent !== null) {
      e = e.parent;
      var flags2 = e.f;
      if (collected_effects !== null && e === active_effect) {
        if (async_mode_flag) return;
        if ((active_reaction === null || (active_reaction.f & DERIVED) === 0) && !legacy_is_updating_store) {
          return;
        }
      }
      if ((flags2 & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {
        if ((flags2 & CLEAN) === 0) {
          return;
        }
        e.f ^= CLEAN;
      }
    }
    __privateGet(this, _roots).push(e);
  }
};
_started = new WeakMap();
_prev = new WeakMap();
_next = new WeakMap();
_commit_callbacks = new WeakMap();
_discard_callbacks = new WeakMap();
_pending = new WeakMap();
_blocking_pending = new WeakMap();
_deferred = new WeakMap();
_roots = new WeakMap();
_new_effects = new WeakMap();
_dirty_effects = new WeakMap();
_maybe_dirty_effects = new WeakMap();
_skipped_branches = new WeakMap();
_unskipped_branches = new WeakMap();
_decrement_queued = new WeakMap();
_Batch_instances = new WeakSet();
is_deferred_fn = function() {
  if (this.is_fork) return true;
  for (const effect2 of __privateGet(this, _blocking_pending).keys()) {
    var e = effect2;
    var skipped = false;
    while (e.parent !== null) {
      if (__privateGet(this, _skipped_branches).has(e)) {
        skipped = true;
        break;
      }
      e = e.parent;
    }
    if (!skipped) {
      return true;
    }
  }
  return false;
};
process_fn = function() {
  var _a5, _b3, _c2, _d;
  __privateSet(this, _started, true);
  if (flush_count++ > 1e3) {
    __privateMethod(this, _Batch_instances, unlink_fn).call(this);
    infinite_loop_guard();
  }
  if (dev_fallback_default) {
    for (const value of this.current.keys()) {
      source_stacks.add(value);
    }
  }
  for (const e of __privateGet(this, _dirty_effects)) {
    __privateGet(this, _maybe_dirty_effects).delete(e);
    set_signal_status(e, DIRTY);
    this.schedule(e);
  }
  for (const e of __privateGet(this, _maybe_dirty_effects)) {
    set_signal_status(e, MAYBE_DIRTY);
    this.schedule(e);
  }
  const roots = __privateGet(this, _roots);
  __privateSet(this, _roots, []);
  this.apply();
  var effects = collected_effects = [];
  var render_effects = [];
  var updates = legacy_updates = [];
  for (const root22 of roots) {
    try {
      __privateMethod(this, _Batch_instances, traverse_fn).call(this, root22, effects, render_effects);
    } catch (e) {
      reset_all(root22);
      if (!__privateMethod(this, _Batch_instances, is_deferred_fn).call(this)) this.discard();
      throw e;
    }
  }
  current_batch = null;
  if (updates.length > 0) {
    var batch = _Batch.ensure();
    for (const e of updates) {
      batch.schedule(e);
    }
  }
  collected_effects = null;
  legacy_updates = null;
  if (__privateMethod(this, _Batch_instances, is_deferred_fn).call(this)) {
    __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, render_effects);
    __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, effects);
    for (const [e, t] of __privateGet(this, _skipped_branches)) {
      reset_branch(e, t);
    }
    if (updates.length > 0) {
      /** @type {unknown} */
      __privateMethod(_a5 = current_batch, _Batch_instances, process_fn).call(_a5);
    }
    return;
  }
  const earlier_batch = __privateMethod(this, _Batch_instances, find_earlier_batch_fn).call(this);
  if (earlier_batch) {
    __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, render_effects);
    __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, effects);
    __privateMethod(_b3 = earlier_batch, _Batch_instances, merge_fn).call(_b3, this);
    return;
  }
  __privateGet(this, _dirty_effects).clear();
  __privateGet(this, _maybe_dirty_effects).clear();
  for (const fn of __privateGet(this, _commit_callbacks)) fn(this);
  __privateGet(this, _commit_callbacks).clear();
  previous_batch = this;
  flush_queued_effects(render_effects);
  flush_queued_effects(effects);
  previous_batch = null;
  (_c2 = __privateGet(this, _deferred)) == null ? void 0 : _c2.resolve();
  var next_batch = (
    /** @type {Batch | null} */
    /** @type {unknown} */
    current_batch
  );
  if (__privateGet(this, _pending) === 0 && (__privateGet(this, _roots).length === 0 || next_batch !== null)) {
    __privateMethod(this, _Batch_instances, unlink_fn).call(this);
    if (async_mode_flag) {
      __privateMethod(this, _Batch_instances, commit_fn).call(this);
      current_batch = next_batch;
    }
  }
  if (__privateGet(this, _roots).length > 0) {
    if (next_batch !== null) {
      const batch2 = next_batch;
      __privateGet(batch2, _roots).push(...__privateGet(this, _roots).filter((r2) => !__privateGet(batch2, _roots).includes(r2)));
    } else {
      next_batch = this;
    }
  }
  if (next_batch !== null) {
    __privateMethod(_d = next_batch, _Batch_instances, process_fn).call(_d);
  }
};
/**
 * Traverse the effect tree, executing effects or stashing
 * them for later execution as appropriate
 * @param {Effect} root
 * @param {Effect[]} effects
 * @param {Effect[]} render_effects
 */
traverse_fn = function(root22, effects, render_effects) {
  root22.f ^= CLEAN;
  var effect2 = root22.first;
  while (effect2 !== null) {
    var flags2 = effect2.f;
    var is_branch = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;
    var is_skippable_branch = is_branch && (flags2 & CLEAN) !== 0;
    var skip = is_skippable_branch || (flags2 & INERT) !== 0 || __privateGet(this, _skipped_branches).has(effect2);
    if (!skip && effect2.fn !== null) {
      if (is_branch) {
        effect2.f ^= CLEAN;
      } else if ((flags2 & EFFECT) !== 0) {
        effects.push(effect2);
      } else if (async_mode_flag && (flags2 & (RENDER_EFFECT | MANAGED_EFFECT)) !== 0) {
        render_effects.push(effect2);
      } else if (is_dirty(effect2)) {
        if ((flags2 & BLOCK_EFFECT) !== 0) __privateGet(this, _maybe_dirty_effects).add(effect2);
        update_effect(effect2);
      }
      var child2 = effect2.first;
      if (child2 !== null) {
        effect2 = child2;
        continue;
      }
    }
    while (effect2 !== null) {
      var next2 = effect2.next;
      if (next2 !== null) {
        effect2 = next2;
        break;
      }
      effect2 = effect2.parent;
    }
  }
};
find_earlier_batch_fn = function() {
  var batch = __privateGet(this, _prev);
  while (batch !== null) {
    if (!batch.is_fork) {
      for (const [value, [, is_derived]] of this.current) {
        if (batch.current.has(value) && !is_derived) {
          return batch;
        }
      }
    }
    batch = __privateGet(batch, _prev);
  }
  return null;
};
/**
 * @param {Batch} batch
 */
merge_fn = function(batch) {
  var _a5;
  for (const [source2, value] of batch.current) {
    if (!this.previous.has(source2) && batch.previous.has(source2)) {
      this.previous.set(source2, batch.previous.get(source2));
    }
    this.current.set(source2, value);
  }
  for (const [effect2, deferred2] of batch.async_deriveds) {
    const d = this.async_deriveds.get(effect2);
    if (d) deferred2.promise.then(d.resolve).catch(d.reject);
  }
  this.transfer_effects(__privateGet(batch, _dirty_effects), __privateGet(batch, _maybe_dirty_effects));
  const mark = (value) => {
    var reactions = value.reactions;
    if (reactions === null) return;
    for (const reaction of reactions) {
      var flags2 = reaction.f;
      if ((flags2 & DERIVED) !== 0) {
        mark(
          /** @type {Derived} */
          reaction
        );
      } else {
        var effect2 = (
          /** @type {Effect} */
          reaction
        );
        if (flags2 & (ASYNC | BLOCK_EFFECT) && !this.async_deriveds.has(effect2)) {
          __privateGet(this, _maybe_dirty_effects).delete(effect2);
          set_signal_status(effect2, DIRTY);
          this.schedule(effect2);
        }
      }
    }
  };
  for (const source2 of this.current.keys()) {
    mark(source2);
  }
  this.oncommit(() => batch.discard());
  __privateMethod(_a5 = batch, _Batch_instances, unlink_fn).call(_a5);
  current_batch = this;
  __privateMethod(this, _Batch_instances, process_fn).call(this);
};
/**
 * @param {Effect[]} effects
 */
defer_effects_fn = function(effects) {
  for (var i = 0; i < effects.length; i += 1) {
    defer_effect(effects[i], __privateGet(this, _dirty_effects), __privateGet(this, _maybe_dirty_effects));
  }
};
commit_fn = function() {
  var _a5;
  for (let batch = first_batch; batch !== null; batch = __privateGet(batch, _next)) {
    var is_earlier = batch.id < this.id;
    var sources = [];
    for (const [source3, [value, is_derived]] of this.current) {
      if (batch.current.has(source3)) {
        var batch_value = (
          /** @type {[any, boolean]} */
          batch.current.get(source3)[0]
        );
        if (is_earlier && value !== batch_value) {
          batch.current.set(source3, [value, is_derived]);
        } else {
          continue;
        }
      }
      sources.push(source3);
    }
    if (is_earlier) {
      for (const [effect2, deferred2] of this.async_deriveds) {
        const d = batch.async_deriveds.get(effect2);
        if (d) deferred2.promise.then(d.resolve).catch(d.reject);
      }
    }
    if (!__privateGet(batch, _started)) continue;
    var others = [...batch.current.keys()].filter(
      (s) => !/** @type {[any, boolean]} */
      batch.current.get(s)[1] && !this.current.has(s)
    );
    if (others.length === 0) {
      if (is_earlier) {
        batch.discard();
      }
    } else if (sources.length > 0) {
      if (dev_fallback_default && !__privateGet(batch, _decrement_queued)) {
        invariant(__privateGet(batch, _roots).length === 0, "Batch has scheduled roots");
      }
      if (is_earlier) {
        for (const unskipped of __privateGet(this, _unskipped_branches)) {
          batch.unskip_effect(unskipped, (e) => {
            var _a6;
            if ((e.f & (BLOCK_EFFECT | ASYNC)) !== 0) {
              batch.schedule(e);
            } else {
              __privateMethod(_a6 = batch, _Batch_instances, defer_effects_fn).call(_a6, [e]);
            }
          });
        }
      }
      batch.activate();
      var marked = /* @__PURE__ */ new Set();
      var checked = /* @__PURE__ */ new Map();
      for (var source2 of sources) {
        mark_effects(source2, others, marked, checked);
      }
      checked = /* @__PURE__ */ new Map();
      var current_unequal = [...batch.current].filter(([c, v1]) => {
        const v2 = this.current.get(c);
        if (!v2) return true;
        return v2[0] !== v1[0] || v2[1] !== v1[1];
      }).map(([c]) => c);
      if (current_unequal.length > 0) {
        for (const effect2 of __privateGet(this, _new_effects)) {
          if ((effect2.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 && depends_on(effect2, current_unequal, checked)) {
            if ((effect2.f & (ASYNC | BLOCK_EFFECT)) !== 0) {
              set_signal_status(effect2, DIRTY);
              batch.schedule(effect2);
            } else {
              __privateGet(batch, _dirty_effects).add(effect2);
            }
          }
        }
      }
      if (__privateGet(batch, _roots).length > 0 && !__privateGet(batch, _decrement_queued)) {
        batch.apply();
        for (var root22 of __privateGet(batch, _roots)) {
          __privateMethod(_a5 = batch, _Batch_instances, traverse_fn).call(_a5, root22, [], []);
        }
        __privateSet(batch, _roots, []);
      }
      batch.deactivate();
    }
  }
};
unlink_fn = function() {
  if (!this.linked) return;
  var prev = __privateGet(this, _prev);
  var next2 = __privateGet(this, _next);
  if (prev === null) {
    first_batch = next2;
  } else {
    __privateSet(prev, _next, next2);
  }
  if (next2 === null) {
    last_batch = prev;
  } else {
    __privateSet(next2, _prev, prev);
  }
  this.linked = false;
};
var Batch = _Batch;
function flushSync(fn) {
  var was_flushing_sync = is_flushing_sync;
  is_flushing_sync = true;
  try {
    var result;
    if (fn) {
      if (current_batch !== null && !current_batch.is_fork) {
        current_batch.flush();
      }
      result = fn();
    }
    while (true) {
      flush_tasks();
      if (current_batch === null) {
        return (
          /** @type {T} */
          result
        );
      }
      current_batch.flush();
    }
  } finally {
    is_flushing_sync = was_flushing_sync;
  }
}
function infinite_loop_guard() {
  var _a5;
  if (dev_fallback_default) {
    var updates = /* @__PURE__ */ new Map();
    for (
      const source2 of
      /** @type {Batch} */
      current_batch.current.keys()
    ) {
      for (const [stack2, update2] of (_a5 = source2.updated) != null ? _a5 : []) {
        var entry = updates.get(stack2);
        if (!entry) {
          entry = { error: update2.error, count: 0 };
          updates.set(stack2, entry);
        }
        entry.count += update2.count;
      }
    }
    for (const update2 of updates.values()) {
      if (update2.error) {
        console.error(update2.error);
      }
    }
  }
  try {
    effect_update_depth_exceeded();
  } catch (error) {
    if (dev_fallback_default) {
      define_property(error, "stack", { value: "" });
    }
    invoke_error_boundary(error, last_scheduled_effect);
  }
}
var eager_block_effects = null;
function flush_queued_effects(effects) {
  var length = effects.length;
  if (length === 0) return;
  var i = 0;
  while (i < length) {
    var effect2 = effects[i++];
    if ((effect2.f & (DESTROYED | INERT)) === 0 && is_dirty(effect2)) {
      eager_block_effects = /* @__PURE__ */ new Set();
      update_effect(effect2);
      if (effect2.deps === null && effect2.first === null && effect2.nodes === null && effect2.teardown === null && effect2.ac === null) {
        unlink_effect(effect2);
      }
      if ((eager_block_effects == null ? void 0 : eager_block_effects.size) > 0) {
        old_values.clear();
        for (const e of eager_block_effects) {
          if ((e.f & (DESTROYED | INERT)) !== 0) continue;
          const ordered_effects = [e];
          let ancestor = e.parent;
          while (ancestor !== null) {
            if (eager_block_effects.has(ancestor)) {
              eager_block_effects.delete(ancestor);
              ordered_effects.push(ancestor);
            }
            ancestor = ancestor.parent;
          }
          for (let j = ordered_effects.length - 1; j >= 0; j--) {
            const e2 = ordered_effects[j];
            if ((e2.f & (DESTROYED | INERT)) !== 0) continue;
            update_effect(e2);
          }
        }
        eager_block_effects.clear();
      }
    }
  }
  eager_block_effects = null;
}
function mark_effects(value, sources, marked, checked) {
  if (marked.has(value)) return;
  marked.add(value);
  if (value.reactions !== null) {
    for (const reaction of value.reactions) {
      const flags2 = reaction.f;
      if ((flags2 & DERIVED) !== 0) {
        mark_effects(
          /** @type {Derived} */
          reaction,
          sources,
          marked,
          checked
        );
      } else if ((flags2 & (ASYNC | BLOCK_EFFECT)) !== 0 && (flags2 & DIRTY) === 0 && depends_on(reaction, sources, checked)) {
        set_signal_status(reaction, DIRTY);
        schedule_effect(
          /** @type {Effect} */
          reaction
        );
      }
    }
  }
}
function depends_on(reaction, sources, checked) {
  const depends = checked.get(reaction);
  if (depends !== void 0) return depends;
  if (reaction.deps !== null) {
    for (const dep of reaction.deps) {
      if (includes.call(sources, dep)) {
        return true;
      }
      if ((dep.f & DERIVED) !== 0 && depends_on(
        /** @type {Derived} */
        dep,
        sources,
        checked
      )) {
        checked.set(
          /** @type {Derived} */
          dep,
          true
        );
        return true;
      }
    }
  }
  checked.set(reaction, false);
  return false;
}
function schedule_effect(effect2) {
  current_batch.schedule(effect2);
}
function reset_branch(effect2, tracked) {
  if ((effect2.f & BRANCH_EFFECT) !== 0 && (effect2.f & CLEAN) !== 0) {
    return;
  }
  if ((effect2.f & DIRTY) !== 0) {
    tracked.d.push(effect2);
  } else if ((effect2.f & MAYBE_DIRTY) !== 0) {
    tracked.m.push(effect2);
  }
  set_signal_status(effect2, CLEAN);
  var e = effect2.first;
  while (e !== null) {
    reset_branch(e, tracked);
    e = e.next;
  }
}
function reset_all(effect2) {
  set_signal_status(effect2, CLEAN);
  var e = effect2.first;
  while (e !== null) {
    reset_all(e);
    e = e.next;
  }
}

// node_modules/svelte/src/reactivity/create-subscriber.js
function createSubscriber(start) {
  let subscribers = 0;
  let version = source(0);
  let stop;
  if (dev_fallback_default) {
    tag(version, "createSubscriber version");
  }
  return () => {
    if (effect_tracking()) {
      get(version);
      render_effect(() => {
        if (subscribers === 0) {
          stop = untrack(() => start(() => increment(version)));
        }
        subscribers += 1;
        return () => {
          queue_micro_task(() => {
            subscribers -= 1;
            if (subscribers === 0) {
              stop == null ? void 0 : stop();
              stop = void 0;
              increment(version);
            }
          });
        };
      });
    }
  };
}

// node_modules/svelte/src/internal/client/dom/blocks/boundary.js
var flags = EFFECT_TRANSPARENT | EFFECT_PRESERVED;
function boundary(node, props, children, transform_error) {
  new Boundary(node, props, children, transform_error);
}
var _anchor, _hydrate_open, _props, _children, _effect, _main_effect, _pending_effect, _failed_effect, _offscreen_fragment, _local_pending_count, _pending_count, _pending_count_update_queued, _dirty_effects2, _maybe_dirty_effects2, _effect_pending, _effect_pending_subscriber, _Boundary_instances, hydrate_resolved_content_fn, hydrate_failed_content_fn, hydrate_pending_content_fn, render_fn, resolve_fn, run_fn, update_pending_count_fn, handle_error_fn;
var Boundary = class {
  /**
   * @param {TemplateNode} node
   * @param {BoundaryProps} props
   * @param {((anchor: Node) => void)} children
   * @param {((error: unknown) => unknown) | undefined} [transform_error]
   */
  constructor(node, props, children, transform_error) {
    __privateAdd(this, _Boundary_instances);
    /** @type {Boundary | null} */
    __publicField(this, "parent");
    __publicField(this, "is_pending", false);
    /**
     * API-level transformError transform function. Transforms errors before they reach the `failed` snippet.
     * Inherited from parent boundary, or defaults to identity.
     * @type {(error: unknown) => unknown}
     */
    __publicField(this, "transform_error");
    /** @type {TemplateNode} */
    __privateAdd(this, _anchor);
    /** @type {TemplateNode | null} */
    __privateAdd(this, _hydrate_open, hydrating ? hydrate_node : null);
    /** @type {BoundaryProps} */
    __privateAdd(this, _props);
    /** @type {((anchor: Node) => void)} */
    __privateAdd(this, _children);
    /** @type {Effect} */
    __privateAdd(this, _effect);
    /** @type {Effect | null} */
    __privateAdd(this, _main_effect, null);
    /** @type {Effect | null} */
    __privateAdd(this, _pending_effect, null);
    /** @type {Effect | null} */
    __privateAdd(this, _failed_effect, null);
    /** @type {DocumentFragment | null} */
    __privateAdd(this, _offscreen_fragment, null);
    __privateAdd(this, _local_pending_count, 0);
    __privateAdd(this, _pending_count, 0);
    __privateAdd(this, _pending_count_update_queued, false);
    /** @type {Set<Effect>} */
    __privateAdd(this, _dirty_effects2, /* @__PURE__ */ new Set());
    /** @type {Set<Effect>} */
    __privateAdd(this, _maybe_dirty_effects2, /* @__PURE__ */ new Set());
    /**
     * A source containing the number of pending async deriveds/expressions.
     * Only created if `$effect.pending()` is used inside the boundary,
     * otherwise updating the source results in needless `Batch.ensure()`
     * calls followed by no-op flushes
     * @type {Source<number> | null}
     */
    __privateAdd(this, _effect_pending, null);
    __privateAdd(this, _effect_pending_subscriber, createSubscriber(() => {
      __privateSet(this, _effect_pending, source(__privateGet(this, _local_pending_count)));
      if (dev_fallback_default) {
        tag(__privateGet(this, _effect_pending), "$effect.pending()");
      }
      return () => {
        __privateSet(this, _effect_pending, null);
      };
    }));
    var _a5, _b3;
    __privateSet(this, _anchor, node);
    __privateSet(this, _props, props);
    __privateSet(this, _children, (anchor) => {
      var effect2 = (
        /** @type {Effect} */
        active_effect
      );
      effect2.b = this;
      effect2.f |= BOUNDARY_EFFECT;
      children(anchor);
    });
    this.parent = /** @type {Effect} */
    active_effect.b;
    this.transform_error = (_b3 = transform_error != null ? transform_error : (_a5 = this.parent) == null ? void 0 : _a5.transform_error) != null ? _b3 : ((e) => e);
    __privateSet(this, _effect, block(() => {
      if (hydrating) {
        const comment2 = (
          /** @type {Comment} */
          __privateGet(this, _hydrate_open)
        );
        hydrate_next();
        const server_rendered_pending = comment2.data === HYDRATION_START_ELSE;
        const server_rendered_failed = comment2.data.startsWith(HYDRATION_START_FAILED);
        if (server_rendered_failed) {
          const serialized_error = JSON.parse(comment2.data.slice(HYDRATION_START_FAILED.length));
          __privateMethod(this, _Boundary_instances, hydrate_failed_content_fn).call(this, serialized_error);
        } else if (server_rendered_pending) {
          __privateMethod(this, _Boundary_instances, hydrate_pending_content_fn).call(this);
        } else {
          __privateMethod(this, _Boundary_instances, hydrate_resolved_content_fn).call(this);
        }
      } else {
        __privateMethod(this, _Boundary_instances, render_fn).call(this);
      }
    }, flags));
    if (hydrating) {
      __privateSet(this, _anchor, hydrate_node);
    }
  }
  /**
   * Defer an effect inside a pending boundary until the boundary resolves
   * @param {Effect} effect
   */
  defer_effect(effect2) {
    defer_effect(effect2, __privateGet(this, _dirty_effects2), __privateGet(this, _maybe_dirty_effects2));
  }
  /**
   * Returns `false` if the effect exists inside a boundary whose pending snippet is shown
   * @returns {boolean}
   */
  is_rendered() {
    return !this.is_pending && (!this.parent || this.parent.is_rendered());
  }
  has_pending_snippet() {
    return !!__privateGet(this, _props).pending;
  }
  /**
   * Update the source that powers `$effect.pending()` inside this boundary,
   * and controls when the current `pending` snippet (if any) is removed.
   * Do not call from inside the class
   * @param {1 | -1} d
   * @param {Batch} batch
   */
  update_pending_count(d, batch) {
    __privateMethod(this, _Boundary_instances, update_pending_count_fn).call(this, d, batch);
    __privateSet(this, _local_pending_count, __privateGet(this, _local_pending_count) + d);
    if (!__privateGet(this, _effect_pending) || __privateGet(this, _pending_count_update_queued)) return;
    __privateSet(this, _pending_count_update_queued, true);
    queue_micro_task(() => {
      __privateSet(this, _pending_count_update_queued, false);
      if (__privateGet(this, _effect_pending)) {
        internal_set(__privateGet(this, _effect_pending), __privateGet(this, _local_pending_count));
      }
    });
  }
  get_effect_pending() {
    __privateGet(this, _effect_pending_subscriber).call(this);
    return get(
      /** @type {Source<number>} */
      __privateGet(this, _effect_pending)
    );
  }
  /** @param {unknown} error */
  error(error) {
    var _a5;
    if (!__privateGet(this, _props).onerror && !__privateGet(this, _props).failed) {
      throw error;
    }
    if ((_a5 = current_batch) == null ? void 0 : _a5.is_fork) {
      if (__privateGet(this, _main_effect)) current_batch.skip_effect(__privateGet(this, _main_effect));
      if (__privateGet(this, _pending_effect)) current_batch.skip_effect(__privateGet(this, _pending_effect));
      if (__privateGet(this, _failed_effect)) current_batch.skip_effect(__privateGet(this, _failed_effect));
      current_batch.oncommit(() => {
        __privateMethod(this, _Boundary_instances, handle_error_fn).call(this, error);
      });
    } else {
      __privateMethod(this, _Boundary_instances, handle_error_fn).call(this, error);
    }
  }
};
_anchor = new WeakMap();
_hydrate_open = new WeakMap();
_props = new WeakMap();
_children = new WeakMap();
_effect = new WeakMap();
_main_effect = new WeakMap();
_pending_effect = new WeakMap();
_failed_effect = new WeakMap();
_offscreen_fragment = new WeakMap();
_local_pending_count = new WeakMap();
_pending_count = new WeakMap();
_pending_count_update_queued = new WeakMap();
_dirty_effects2 = new WeakMap();
_maybe_dirty_effects2 = new WeakMap();
_effect_pending = new WeakMap();
_effect_pending_subscriber = new WeakMap();
_Boundary_instances = new WeakSet();
hydrate_resolved_content_fn = function() {
  try {
    __privateSet(this, _main_effect, branch(() => __privateGet(this, _children).call(this, __privateGet(this, _anchor))));
  } catch (error) {
    this.error(error);
  }
};
/**
 * @param {unknown} error The deserialized error from the server's hydration comment
 */
hydrate_failed_content_fn = function(error) {
  const failed = __privateGet(this, _props).failed;
  if (!failed) return;
  __privateSet(this, _failed_effect, branch(() => {
    failed(
      __privateGet(this, _anchor),
      () => error,
      () => () => {
      }
    );
  }));
};
hydrate_pending_content_fn = function() {
  const pending2 = __privateGet(this, _props).pending;
  if (!pending2) return;
  this.is_pending = true;
  __privateSet(this, _pending_effect, branch(() => pending2(__privateGet(this, _anchor))));
  queue_micro_task(() => {
    var fragment = __privateSet(this, _offscreen_fragment, document.createDocumentFragment());
    var anchor = create_text();
    fragment.append(anchor);
    __privateSet(this, _main_effect, __privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
      return branch(() => __privateGet(this, _children).call(this, anchor));
    }));
    if (__privateGet(this, _pending_count) === 0) {
      __privateGet(this, _anchor).before(fragment);
      __privateSet(this, _offscreen_fragment, null);
      pause_effect(
        /** @type {Effect} */
        __privateGet(this, _pending_effect),
        () => {
          __privateSet(this, _pending_effect, null);
        }
      );
      __privateMethod(this, _Boundary_instances, resolve_fn).call(
        this,
        /** @type {Batch} */
        current_batch
      );
    }
  });
};
render_fn = function() {
  try {
    this.is_pending = this.has_pending_snippet();
    __privateSet(this, _pending_count, 0);
    __privateSet(this, _local_pending_count, 0);
    __privateSet(this, _main_effect, branch(() => {
      __privateGet(this, _children).call(this, __privateGet(this, _anchor));
    }));
    if (__privateGet(this, _pending_count) > 0) {
      var fragment = __privateSet(this, _offscreen_fragment, document.createDocumentFragment());
      move_effect(__privateGet(this, _main_effect), fragment);
      const pending2 = (
        /** @type {(anchor: Node) => void} */
        __privateGet(this, _props).pending
      );
      __privateSet(this, _pending_effect, branch(() => pending2(__privateGet(this, _anchor))));
    } else {
      __privateMethod(this, _Boundary_instances, resolve_fn).call(
        this,
        /** @type {Batch} */
        current_batch
      );
    }
  } catch (error) {
    this.error(error);
  }
};
/**
 * @param {Batch} batch
 */
resolve_fn = function(batch) {
  this.is_pending = false;
  batch.transfer_effects(__privateGet(this, _dirty_effects2), __privateGet(this, _maybe_dirty_effects2));
};
/**
 * @template T
 * @param {() => T} fn
 */
run_fn = function(fn) {
  var previous_effect = active_effect;
  var previous_reaction = active_reaction;
  var previous_ctx = component_context;
  set_active_effect(__privateGet(this, _effect));
  set_active_reaction(__privateGet(this, _effect));
  set_component_context(__privateGet(this, _effect).ctx);
  try {
    Batch.ensure();
    return fn();
  } catch (e) {
    handle_error(e);
    return null;
  } finally {
    set_active_effect(previous_effect);
    set_active_reaction(previous_reaction);
    set_component_context(previous_ctx);
  }
};
/**
 * Updates the pending count associated with the currently visible pending snippet,
 * if any, such that we can replace the snippet with content once work is done
 * @param {1 | -1} d
 * @param {Batch} batch
 */
update_pending_count_fn = function(d, batch) {
  var _a5;
  if (!this.has_pending_snippet()) {
    if (this.parent) {
      __privateMethod(_a5 = this.parent, _Boundary_instances, update_pending_count_fn).call(_a5, d, batch);
    }
    return;
  }
  __privateSet(this, _pending_count, __privateGet(this, _pending_count) + d);
  if (__privateGet(this, _pending_count) === 0) {
    __privateMethod(this, _Boundary_instances, resolve_fn).call(this, batch);
    if (__privateGet(this, _pending_effect)) {
      pause_effect(__privateGet(this, _pending_effect), () => {
        __privateSet(this, _pending_effect, null);
      });
    }
    if (__privateGet(this, _offscreen_fragment)) {
      __privateGet(this, _anchor).before(__privateGet(this, _offscreen_fragment));
      __privateSet(this, _offscreen_fragment, null);
    }
  }
};
/**
 * @param {unknown} error
 */
handle_error_fn = function(error) {
  if (__privateGet(this, _main_effect)) {
    destroy_effect(__privateGet(this, _main_effect));
    __privateSet(this, _main_effect, null);
  }
  if (__privateGet(this, _pending_effect)) {
    destroy_effect(__privateGet(this, _pending_effect));
    __privateSet(this, _pending_effect, null);
  }
  if (__privateGet(this, _failed_effect)) {
    destroy_effect(__privateGet(this, _failed_effect));
    __privateSet(this, _failed_effect, null);
  }
  if (hydrating) {
    set_hydrate_node(
      /** @type {TemplateNode} */
      __privateGet(this, _hydrate_open)
    );
    next();
    set_hydrate_node(skip_nodes());
  }
  var onerror = __privateGet(this, _props).onerror;
  let failed = __privateGet(this, _props).failed;
  var did_reset = false;
  var calling_on_error = false;
  const reset2 = () => {
    if (did_reset) {
      svelte_boundary_reset_noop();
      return;
    }
    did_reset = true;
    if (calling_on_error) {
      svelte_boundary_reset_onerror();
    }
    if (__privateGet(this, _failed_effect) !== null) {
      pause_effect(__privateGet(this, _failed_effect), () => {
        __privateSet(this, _failed_effect, null);
      });
    }
    __privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
      __privateMethod(this, _Boundary_instances, render_fn).call(this);
    });
  };
  const handle_error_result = (transformed_error) => {
    try {
      calling_on_error = true;
      onerror == null ? void 0 : onerror(transformed_error, reset2);
      calling_on_error = false;
    } catch (error2) {
      invoke_error_boundary(error2, __privateGet(this, _effect) && __privateGet(this, _effect).parent);
    }
    if (failed) {
      __privateSet(this, _failed_effect, __privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
        try {
          return branch(() => {
            var effect2 = (
              /** @type {Effect} */
              active_effect
            );
            effect2.b = this;
            effect2.f |= BOUNDARY_EFFECT;
            failed(
              __privateGet(this, _anchor),
              () => transformed_error,
              () => reset2
            );
          });
        } catch (error2) {
          invoke_error_boundary(
            error2,
            /** @type {Effect} */
            __privateGet(this, _effect).parent
          );
          return null;
        }
      }));
    }
  };
  queue_micro_task(() => {
    var result;
    try {
      result = this.transform_error(error);
    } catch (e) {
      invoke_error_boundary(e, __privateGet(this, _effect) && __privateGet(this, _effect).parent);
      return;
    }
    if (result !== null && typeof result === "object" && typeof /** @type {any} */
    result.then === "function") {
      result.then(
        handle_error_result,
        /** @param {unknown} e */
        (e) => invoke_error_boundary(e, __privateGet(this, _effect) && __privateGet(this, _effect).parent)
      );
    } else {
      handle_error_result(result);
    }
  });
};

// node_modules/svelte/src/internal/client/reactivity/async.js
function flatten(blockers, sync, async2, fn) {
  const d = is_runes() ? derived2 : derived_safe_equal;
  var pending2 = blockers.filter((b) => !b.settled);
  if (async2.length === 0 && pending2.length === 0) {
    fn(sync.map(d));
    return;
  }
  var parent = (
    /** @type {Effect} */
    active_effect
  );
  var restore = capture();
  var blocker_promise = pending2.length === 1 ? pending2[0].promise : pending2.length > 1 ? Promise.all(pending2.map((b) => b.promise)) : null;
  function finish(values) {
    if ((parent.f & DESTROYED) !== 0) {
      return;
    }
    restore();
    try {
      fn(values);
    } catch (error) {
      invoke_error_boundary(error, parent);
    }
    unset_context();
  }
  var decrement_pending = increment_pending();
  if (async2.length === 0) {
    blocker_promise.then(() => finish(sync.map(d))).finally(decrement_pending);
    return;
  }
  function run3() {
    Promise.all(async2.map((expression) => async_derived(expression))).then((result) => finish([...sync.map(d), ...result])).catch((error) => invoke_error_boundary(error, parent)).finally(decrement_pending);
  }
  if (blocker_promise) {
    blocker_promise.then(() => {
      restore();
      run3();
      unset_context();
    });
  } else {
    run3();
  }
}
function capture() {
  var previous_effect = (
    /** @type {Effect} */
    active_effect
  );
  var previous_reaction = active_reaction;
  var previous_component_context = component_context;
  var previous_batch2 = (
    /** @type {Batch} */
    current_batch
  );
  if (dev_fallback_default) {
    var previous_dev_stack = dev_stack;
  }
  return function restore(activate_batch = true) {
    set_active_effect(previous_effect);
    set_active_reaction(previous_reaction);
    set_component_context(previous_component_context);
    if (activate_batch && (previous_effect.f & DESTROYED) === 0) {
      previous_batch2 == null ? void 0 : previous_batch2.activate();
      previous_batch2 == null ? void 0 : previous_batch2.apply();
    }
    if (dev_fallback_default) {
      set_reactivity_loss_tracker(null);
      set_dev_stack(previous_dev_stack);
    }
  };
}
function unset_context(deactivate_batch = true) {
  var _a5;
  set_active_effect(null);
  set_active_reaction(null);
  set_component_context(null);
  if (deactivate_batch) (_a5 = current_batch) == null ? void 0 : _a5.deactivate();
  if (dev_fallback_default) {
    set_reactivity_loss_tracker(null);
    set_dev_stack(null);
  }
}
function increment_pending() {
  var effect2 = (
    /** @type {Effect} */
    active_effect
  );
  var boundary2 = effect2.b;
  var batch = (
    /** @type {Batch} */
    current_batch
  );
  var blocking = !!(boundary2 == null ? void 0 : boundary2.is_rendered());
  boundary2 == null ? void 0 : boundary2.update_pending_count(1, batch);
  batch.increment(blocking, effect2);
  return () => {
    boundary2 == null ? void 0 : boundary2.update_pending_count(-1, batch);
    batch.decrement(blocking, effect2);
  };
}

// node_modules/svelte/src/internal/client/reactivity/deriveds.js
var reactivity_loss_tracker = null;
function set_reactivity_loss_tracker(v) {
  reactivity_loss_tracker = v;
}
var recent_async_deriveds = /* @__PURE__ */ new Set();
// @__NO_SIDE_EFFECTS__
function derived2(fn) {
  var flags2 = DERIVED | DIRTY;
  if (active_effect !== null) {
    active_effect.f |= EFFECT_PRESERVED;
  }
  const signal = {
    ctx: component_context,
    deps: null,
    effects: null,
    equals,
    f: flags2,
    fn,
    reactions: null,
    rv: 0,
    v: (
      /** @type {V} */
      UNINITIALIZED
    ),
    wv: 0,
    parent: active_effect,
    ac: null
  };
  if (dev_fallback_default && tracing_mode_flag) {
    signal.created = get_error("created at");
  }
  return signal;
}
var OBSOLETE = /* @__PURE__ */ Symbol("obsolete");
// @__NO_SIDE_EFFECTS__
function async_derived(fn, label, location) {
  let parent = (
    /** @type {Effect | null} */
    active_effect
  );
  if (parent === null) {
    async_derived_orphan();
  }
  var promise = (
    /** @type {Promise<V>} */
    /** @type {unknown} */
    void 0
  );
  var signal = source(
    /** @type {V} */
    UNINITIALIZED
  );
  if (dev_fallback_default) signal.label = label != null ? label : fn.toString();
  var should_suspend = !active_reaction;
  var deferreds = /* @__PURE__ */ new Set();
  async_effect(() => {
    var _a5, _b3;
    var effect2 = (
      /** @type {Effect} */
      active_effect
    );
    if (dev_fallback_default) {
      reactivity_loss_tracker = { effect: effect2, effect_deps: /* @__PURE__ */ new Set(), warned: false };
    }
    var d = deferred();
    promise = d.promise;
    try {
      Promise.resolve(fn()).then(d.resolve, (e) => {
        if (e !== STALE_REACTION) d.reject(e);
      }).finally(unset_context);
    } catch (error) {
      d.reject(error);
      unset_context();
    }
    if (dev_fallback_default) {
      if (reactivity_loss_tracker) {
        if (effect2.deps !== null) {
          for (let i = 0; i < skipped_deps; i += 1) {
            reactivity_loss_tracker.effect_deps.add(effect2.deps[i]);
          }
        }
        if (new_deps !== null) {
          for (let i = 0; i < new_deps.length; i += 1) {
            reactivity_loss_tracker.effect_deps.add(new_deps[i]);
          }
        }
      }
      reactivity_loss_tracker = null;
    }
    var batch = (
      /** @type {Batch} */
      current_batch
    );
    if (should_suspend) {
      if ((effect2.f & REACTION_RAN) !== 0) {
        var decrement_pending = increment_pending();
      }
      if (
        // boundary can be null if the async derived is inside an $effect.root not connected to the component render tree
        (_a5 = parent.b) == null ? void 0 : _a5.is_rendered()
      ) {
        (_b3 = batch.async_deriveds.get(effect2)) == null ? void 0 : _b3.reject(OBSOLETE);
      } else {
        for (const d2 of deferreds.values()) {
          d2.reject(OBSOLETE);
        }
      }
      deferreds.add(d);
      batch.async_deriveds.set(effect2, d);
    }
    const handler = (value, error = void 0) => {
      if (dev_fallback_default) {
        reactivity_loss_tracker = null;
      }
      decrement_pending == null ? void 0 : decrement_pending();
      deferreds.delete(d);
      if (error === OBSOLETE) return;
      batch.activate();
      if (error) {
        signal.f |= ERROR_VALUE;
        internal_set(signal, error);
      } else {
        if ((signal.f & ERROR_VALUE) !== 0) {
          signal.f ^= ERROR_VALUE;
        }
        if (dev_fallback_default && location !== void 0 && !signal.equals(value)) {
          recent_async_deriveds.add(signal);
          setTimeout(() => {
            if (recent_async_deriveds.has(signal) && (effect2.f & DESTROYED) === 0) {
              await_waterfall(
                /** @type {string} */
                signal.label,
                location
              );
              recent_async_deriveds.delete(signal);
            }
          });
        }
        internal_set(signal, value);
      }
      batch.deactivate();
    };
    d.promise.then(handler, (e) => handler(null, e || "unknown"));
  });
  teardown(() => {
    for (const d of deferreds) {
      d.reject(OBSOLETE);
    }
  });
  if (dev_fallback_default) {
    signal.f |= ASYNC;
  }
  return new Promise((fulfil) => {
    function next2(p) {
      function go() {
        if (p === promise) {
          fulfil(signal);
        } else {
          next2(promise);
        }
      }
      p.then(go, go);
    }
    next2(promise);
  });
}
// @__NO_SIDE_EFFECTS__
function user_derived(fn) {
  const d = /* @__PURE__ */ derived2(fn);
  if (!async_mode_flag) push_reaction_value(d);
  return d;
}
// @__NO_SIDE_EFFECTS__
function derived_safe_equal(fn) {
  const signal = /* @__PURE__ */ derived2(fn);
  signal.equals = safe_equals;
  return signal;
}
function destroy_derived_effects(derived3) {
  var effects = derived3.effects;
  if (effects !== null) {
    derived3.effects = null;
    for (var i = 0; i < effects.length; i += 1) {
      destroy_effect(
        /** @type {Effect} */
        effects[i]
      );
    }
  }
}
var stack = [];
function execute_derived(derived3) {
  var value;
  var prev_active_effect = active_effect;
  var parent = derived3.parent;
  if (!is_destroying_effect && parent !== null && derived3.v !== UNINITIALIZED && // if it was never evaluated before, it's guaranteed to fail downstream, so we try to execute instead
  (parent.f & (DESTROYED | INERT)) !== 0) {
    derived_inert();
    return derived3.v;
  }
  set_active_effect(parent);
  if (dev_fallback_default) {
    let prev_eager_effects = eager_effects;
    set_eager_effects(/* @__PURE__ */ new Set());
    try {
      if (includes.call(stack, derived3)) {
        derived_references_self();
      }
      stack.push(derived3);
      derived3.f &= ~WAS_MARKED;
      destroy_derived_effects(derived3);
      value = update_reaction(derived3);
    } finally {
      set_active_effect(prev_active_effect);
      set_eager_effects(prev_eager_effects);
      stack.pop();
    }
  } else {
    try {
      derived3.f &= ~WAS_MARKED;
      destroy_derived_effects(derived3);
      value = update_reaction(derived3);
    } finally {
      set_active_effect(prev_active_effect);
    }
  }
  return value;
}
function update_derived(derived3) {
  var _a5, _b3, _c2;
  var value = execute_derived(derived3);
  if (!derived3.equals(value)) {
    derived3.wv = increment_write_version();
    if (!((_a5 = current_batch) == null ? void 0 : _a5.is_fork) || derived3.deps === null) {
      if (current_batch !== null) {
        current_batch.capture(derived3, value, true);
        (_b3 = previous_batch) == null ? void 0 : _b3.capture(derived3, value, true);
      } else {
        derived3.v = value;
      }
      if (derived3.deps === null) {
        set_signal_status(derived3, CLEAN);
        return;
      }
    }
  }
  if (is_destroying_effect) {
    return;
  }
  if (batch_values !== null) {
    if (effect_tracking() || ((_c2 = current_batch) == null ? void 0 : _c2.is_fork)) {
      batch_values.set(derived3, value);
    }
  } else {
    update_derived_status(derived3);
  }
}
function freeze_derived_effects(derived3) {
  var _a5, _b3;
  if (derived3.effects === null) return;
  for (const e of derived3.effects) {
    if (e.teardown || e.ac) {
      (_a5 = e.teardown) == null ? void 0 : _a5.call(e);
      (_b3 = e.ac) == null ? void 0 : _b3.abort(STALE_REACTION);
      if (e.fn !== null) e.teardown = noop;
      e.ac = null;
      remove_reactions(e, 0);
      destroy_effect_children(e);
    }
  }
}
function unfreeze_derived_effects(derived3) {
  if (derived3.effects === null) return;
  for (const e of derived3.effects) {
    if (e.teardown && e.fn !== null) {
      update_effect(e);
    }
  }
}

// node_modules/svelte/src/internal/client/reactivity/sources.js
var eager_effects = /* @__PURE__ */ new Set();
var old_values = /* @__PURE__ */ new Map();
function set_eager_effects(v) {
  eager_effects = v;
}
var eager_effects_deferred = false;
function set_eager_effects_deferred() {
  eager_effects_deferred = true;
}
function source(v, stack2) {
  var signal = {
    f: 0,
    // TODO ideally we could skip this altogether, but it causes type errors
    v,
    reactions: null,
    equals,
    rv: 0,
    wv: 0
  };
  if (dev_fallback_default && tracing_mode_flag) {
    signal.created = stack2 != null ? stack2 : get_error("created at");
    signal.updated = null;
    signal.set_during_effect = false;
    signal.trace = null;
  }
  return signal;
}
// @__NO_SIDE_EFFECTS__
function state(v, stack2) {
  const s = source(v, stack2);
  push_reaction_value(s);
  return s;
}
// @__NO_SIDE_EFFECTS__
function mutable_source(initial_value, immutable = false, trackable = true) {
  var _a5, _b3;
  const s = source(initial_value);
  if (!immutable) {
    s.equals = safe_equals;
  }
  if (legacy_mode_flag && trackable && component_context !== null && component_context.l !== null) {
    ((_b3 = (_a5 = component_context.l).s) != null ? _b3 : _a5.s = []).push(s);
  }
  return s;
}
function mutate(source2, value) {
  set(
    source2,
    untrack(() => get(source2))
  );
  return value;
}
function set(source2, value, should_proxy = false) {
  if (active_reaction !== null && // since we are untracking the function inside `$inspect.with` we need to add this check
  // to ensure we error if state is set inside an inspect effect
  (!untracking || (active_reaction.f & EAGER_EFFECT) !== 0) && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | EAGER_EFFECT)) !== 0 && (current_sources === null || !current_sources.has(source2))) {
    state_unsafe_mutation();
  }
  let new_value = should_proxy ? proxy(value) : value;
  if (dev_fallback_default) {
    tag_proxy(
      new_value,
      /** @type {string} */
      source2.label
    );
  }
  return internal_set(source2, new_value, legacy_updates);
}
function internal_set(source2, value, updated_during_traversal = null) {
  var _a5, _b3, _c2;
  if (!source2.equals(value)) {
    old_values.set(source2, is_destroying_effect ? value : source2.v);
    var batch = Batch.ensure();
    batch.capture(source2, value);
    if (dev_fallback_default) {
      if (tracing_mode_flag || active_effect !== null) {
        (_a5 = source2.updated) != null ? _a5 : source2.updated = /* @__PURE__ */ new Map();
        const count = ((_c2 = (_b3 = source2.updated.get("")) == null ? void 0 : _b3.count) != null ? _c2 : 0) + 1;
        source2.updated.set("", { error: (
          /** @type {any} */
          null
        ), count });
        if (tracing_mode_flag || count > 5) {
          const error = get_error("updated at");
          if (error !== null) {
            let entry = source2.updated.get(error.stack);
            if (!entry) {
              entry = { error, count: 0 };
              source2.updated.set(error.stack, entry);
            }
            entry.count++;
          }
        }
      }
      if (active_effect !== null) {
        source2.set_during_effect = true;
      }
    }
    if ((source2.f & DERIVED) !== 0) {
      const derived3 = (
        /** @type {Derived} */
        source2
      );
      if ((source2.f & DIRTY) !== 0) {
        execute_derived(derived3);
      }
      if (batch_values === null) {
        update_derived_status(derived3);
      }
    }
    source2.wv = increment_write_version();
    mark_reactions(source2, DIRTY, updated_during_traversal);
    if (is_runes() && active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) {
      if (untracked_writes === null) {
        set_untracked_writes([source2]);
      } else {
        untracked_writes.push(source2);
      }
    }
    if (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) {
      flush_eager_effects();
    }
  }
  return value;
}
function flush_eager_effects() {
  eager_effects_deferred = false;
  for (const effect2 of eager_effects) {
    if ((effect2.f & CLEAN) !== 0) {
      set_signal_status(effect2, MAYBE_DIRTY);
    }
    let dirty;
    try {
      dirty = is_dirty(effect2);
    } catch (e) {
      dirty = true;
    }
    if (dirty) {
      update_effect(effect2);
    }
  }
  eager_effects.clear();
}
function update(source2, d = 1) {
  var value = get(source2);
  var result = d === 1 ? value++ : value--;
  set(source2, value);
  return result;
}
function increment(source2) {
  set(source2, source2.v + 1);
}
function mark_reactions(signal, status, updated_during_traversal) {
  var _a5;
  var reactions = signal.reactions;
  if (reactions === null) return;
  var runes = is_runes();
  var length = reactions.length;
  for (var i = 0; i < length; i++) {
    var reaction = reactions[i];
    var flags2 = reaction.f;
    if (!runes && reaction === active_effect) continue;
    var not_dirty = (flags2 & DIRTY) === 0;
    if (not_dirty) {
      set_signal_status(reaction, status);
    }
    if ((flags2 & EAGER_EFFECT) !== 0) {
      eager_effects.add(
        /** @type {Effect} */
        reaction
      );
    } else if ((flags2 & DERIVED) !== 0) {
      var derived3 = (
        /** @type {Derived} */
        reaction
      );
      (_a5 = batch_values) == null ? void 0 : _a5.delete(derived3);
      if ((flags2 & WAS_MARKED) === 0) {
        if (flags2 & CONNECTED && (active_effect === null || (active_effect.f & REACTION_IS_UPDATING) === 0)) {
          reaction.f |= WAS_MARKED;
        }
        mark_reactions(derived3, MAYBE_DIRTY, updated_during_traversal);
      }
    } else if (not_dirty) {
      var effect2 = (
        /** @type {Effect} */
        reaction
      );
      if ((flags2 & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) {
        eager_block_effects.add(effect2);
      }
      if (updated_during_traversal !== null) {
        updated_during_traversal.push(effect2);
      } else {
        schedule_effect(effect2);
      }
    }
  }
}

// node_modules/svelte/src/internal/client/legacy.js
var captured_signals = null;

// node_modules/svelte/src/internal/client/dom/elements/misc.js
function autofocus(dom, value) {
  if (value) {
    const body = document.body;
    dom.autofocus = true;
    queue_micro_task(() => {
      if (document.activeElement === body) {
        dom.focus();
      }
    });
  }
}
function remove_textarea_child(dom) {
  if (hydrating && get_first_child(dom) !== null) {
    clear_text_content(dom);
  }
}
var listening_to_form_reset = false;
function add_form_reset_listener() {
  if (!listening_to_form_reset) {
    listening_to_form_reset = true;
    document.addEventListener(
      "reset",
      (evt) => {
        Promise.resolve().then(() => {
          var _a5;
          if (!evt.defaultPrevented) {
            for (
              const e of
              /**@type {HTMLFormElement} */
              evt.target.elements
            ) {
              (_a5 = e[FORM_RESET_HANDLER]) == null ? void 0 : _a5.call(e);
            }
          }
        });
      },
      // In the capture phase to guarantee we get noticed of it (no possibility of stopPropagation)
      { capture: true }
    );
  }
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/shared.js
function without_reactive_context(fn) {
  var previous_reaction = active_reaction;
  var previous_effect = active_effect;
  set_active_reaction(null);
  set_active_effect(null);
  try {
    return fn();
  } finally {
    set_active_reaction(previous_reaction);
    set_active_effect(previous_effect);
  }
}
function listen_to_event_and_reset_event(element2, event2, handler, on_reset = handler) {
  element2.addEventListener(event2, () => without_reactive_context(handler));
  const prev = (
    /** @type {any} */
    element2[FORM_RESET_HANDLER]
  );
  if (prev) {
    element2[FORM_RESET_HANDLER] = () => {
      prev();
      on_reset(true);
    };
  } else {
    element2[FORM_RESET_HANDLER] = () => on_reset(true);
  }
  add_form_reset_listener();
}

// node_modules/svelte/src/internal/client/runtime.js
var is_updating_effect = false;
var is_destroying_effect = false;
function set_is_destroying_effect(value) {
  is_destroying_effect = value;
}
var active_reaction = null;
var untracking = false;
function set_active_reaction(reaction) {
  active_reaction = reaction;
}
var active_effect = null;
function set_active_effect(effect2) {
  active_effect = effect2;
}
var current_sources = null;
function push_reaction_value(value) {
  if (active_reaction !== null && (!async_mode_flag || (active_reaction.f & DERIVED) !== 0)) {
    (current_sources != null ? current_sources : current_sources = /* @__PURE__ */ new Set()).add(value);
  }
}
var new_deps = null;
var skipped_deps = 0;
var untracked_writes = null;
function set_untracked_writes(value) {
  untracked_writes = value;
}
var write_version = 1;
var read_version = 0;
var update_version = read_version;
function set_update_version(value) {
  update_version = value;
}
function increment_write_version() {
  return ++write_version;
}
function is_dirty(reaction) {
  var flags2 = reaction.f;
  if ((flags2 & DIRTY) !== 0) {
    return true;
  }
  if (flags2 & DERIVED) {
    reaction.f &= ~WAS_MARKED;
  }
  if ((flags2 & MAYBE_DIRTY) !== 0) {
    var dependencies = (
      /** @type {Value[]} */
      reaction.deps
    );
    var length = dependencies.length;
    for (var i = 0; i < length; i++) {
      var dependency = dependencies[i];
      if (is_dirty(
        /** @type {Derived} */
        dependency
      )) {
        update_derived(
          /** @type {Derived} */
          dependency
        );
      }
      if (dependency.wv > reaction.wv) {
        return true;
      }
    }
    if ((flags2 & CONNECTED) !== 0 && // During time traveling we don't want to reset the status so that
    // traversal of the graph in the other batches still happens
    batch_values === null) {
      set_signal_status(reaction, CLEAN);
    }
  }
  return false;
}
function schedule_possible_effect_self_invalidation(signal, effect2, root22 = true) {
  var reactions = signal.reactions;
  if (reactions === null) return;
  if (!async_mode_flag && current_sources !== null && current_sources.has(signal)) {
    return;
  }
  for (var i = 0; i < reactions.length; i++) {
    var reaction = reactions[i];
    if ((reaction.f & DERIVED) !== 0) {
      schedule_possible_effect_self_invalidation(
        /** @type {Derived} */
        reaction,
        effect2,
        false
      );
    } else if (effect2 === reaction) {
      if (root22) {
        set_signal_status(reaction, DIRTY);
      } else if ((reaction.f & CLEAN) !== 0) {
        set_signal_status(reaction, MAYBE_DIRTY);
      }
      schedule_effect(
        /** @type {Effect} */
        reaction
      );
    }
  }
}
function update_reaction(reaction) {
  var _a5, _b3, _c2;
  var previous_deps = new_deps;
  var previous_skipped_deps = skipped_deps;
  var previous_untracked_writes = untracked_writes;
  var previous_reaction = active_reaction;
  var previous_sources = current_sources;
  var previous_component_context = component_context;
  var previous_untracking = untracking;
  var previous_update_version = update_version;
  var flags2 = reaction.f;
  new_deps = /** @type {null | Value[]} */
  null;
  skipped_deps = 0;
  untracked_writes = null;
  active_reaction = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;
  current_sources = null;
  set_component_context(reaction.ctx);
  untracking = false;
  update_version = ++read_version;
  if (reaction.ac !== null) {
    without_reactive_context(() => {
      reaction.ac.abort(STALE_REACTION);
    });
    reaction.ac = null;
  }
  try {
    reaction.f |= REACTION_IS_UPDATING;
    var fn = (
      /** @type {Function} */
      reaction.fn
    );
    var result = fn();
    reaction.f |= REACTION_RAN;
    var deps = reaction.deps;
    var is_fork = (_a5 = current_batch) == null ? void 0 : _a5.is_fork;
    if (new_deps !== null) {
      var i;
      if (!is_fork) {
        remove_reactions(reaction, skipped_deps);
      }
      if (deps !== null && skipped_deps > 0) {
        deps.length = skipped_deps + new_deps.length;
        for (i = 0; i < new_deps.length; i++) {
          deps[skipped_deps + i] = new_deps[i];
        }
      } else {
        reaction.deps = deps = new_deps;
      }
      if (effect_tracking() && (reaction.f & CONNECTED) !== 0) {
        for (i = skipped_deps; i < deps.length; i++) {
          ((_c2 = (_b3 = deps[i]).reactions) != null ? _c2 : _b3.reactions = []).push(reaction);
        }
      }
    } else if (!is_fork && deps !== null && skipped_deps < deps.length) {
      remove_reactions(reaction, skipped_deps);
      deps.length = skipped_deps;
    }
    if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) {
      for (i = 0; i < /** @type {Source[]} */
      untracked_writes.length; i++) {
        schedule_possible_effect_self_invalidation(
          untracked_writes[i],
          /** @type {Effect} */
          reaction
        );
      }
    }
    if (previous_reaction !== null && previous_reaction !== reaction) {
      read_version++;
      if (previous_reaction.deps !== null) {
        for (let i2 = 0; i2 < previous_skipped_deps; i2 += 1) {
          previous_reaction.deps[i2].rv = read_version;
        }
      }
      if (previous_deps !== null) {
        for (const dep of previous_deps) {
          dep.rv = read_version;
        }
      }
      if (untracked_writes !== null) {
        if (previous_untracked_writes === null) {
          previous_untracked_writes = untracked_writes;
        } else {
          previous_untracked_writes.push(.../** @type {Source[]} */
          untracked_writes);
        }
      }
    }
    if ((reaction.f & ERROR_VALUE) !== 0) {
      reaction.f ^= ERROR_VALUE;
    }
    return result;
  } catch (error) {
    return handle_error(error);
  } finally {
    reaction.f ^= REACTION_IS_UPDATING;
    new_deps = previous_deps;
    skipped_deps = previous_skipped_deps;
    untracked_writes = previous_untracked_writes;
    active_reaction = previous_reaction;
    current_sources = previous_sources;
    set_component_context(previous_component_context);
    untracking = previous_untracking;
    update_version = previous_update_version;
  }
}
function remove_reaction(signal, dependency) {
  let reactions = dependency.reactions;
  if (reactions !== null) {
    var index2 = index_of.call(reactions, signal);
    if (index2 !== -1) {
      var new_length = reactions.length - 1;
      if (new_length === 0) {
        reactions = dependency.reactions = null;
      } else {
        reactions[index2] = reactions[new_length];
        reactions.pop();
      }
    }
  }
  if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear
  // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps`
  // allows us to skip the expensive work of disconnecting and immediately reconnecting it
  (new_deps === null || !includes.call(new_deps, dependency))) {
    var derived3 = (
      /** @type {Derived} */
      dependency
    );
    if ((derived3.f & CONNECTED) !== 0) {
      derived3.f ^= CONNECTED;
      derived3.f &= ~WAS_MARKED;
    }
    if (derived3.v !== UNINITIALIZED) {
      update_derived_status(derived3);
    }
    freeze_derived_effects(derived3);
    remove_reactions(derived3, 0);
  }
}
function remove_reactions(signal, start_index) {
  var dependencies = signal.deps;
  if (dependencies === null) return;
  for (var i = start_index; i < dependencies.length; i++) {
    remove_reaction(signal, dependencies[i]);
  }
}
function update_effect(effect2) {
  var _a5;
  var flags2 = effect2.f;
  if ((flags2 & DESTROYED) !== 0) {
    return;
  }
  set_signal_status(effect2, CLEAN);
  var previous_effect = active_effect;
  var was_updating_effect = is_updating_effect;
  active_effect = effect2;
  is_updating_effect = true;
  if (dev_fallback_default) {
    var previous_component_fn = dev_current_component_function;
    set_dev_current_component_function(effect2.component_function);
    var previous_stack = (
      /** @type {any} */
      dev_stack
    );
    set_dev_stack((_a5 = effect2.dev_stack) != null ? _a5 : dev_stack);
  }
  try {
    if ((flags2 & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) {
      destroy_block_effect_children(effect2);
    } else {
      destroy_effect_children(effect2);
    }
    execute_effect_teardown(effect2);
    var teardown2 = update_reaction(effect2);
    effect2.teardown = typeof teardown2 === "function" ? teardown2 : null;
    effect2.wv = write_version;
    if (dev_fallback_default && tracing_mode_flag && (effect2.f & DIRTY) !== 0 && effect2.deps !== null) {
      for (var dep of effect2.deps) {
        if (dep.set_during_effect) {
          dep.wv = increment_write_version();
          dep.set_during_effect = false;
        }
      }
    }
  } finally {
    is_updating_effect = was_updating_effect;
    active_effect = previous_effect;
    if (dev_fallback_default) {
      set_dev_current_component_function(previous_component_fn);
      set_dev_stack(previous_stack);
    }
  }
}
async function tick() {
  if (async_mode_flag) {
    return new Promise((f) => {
      requestAnimationFrame(() => f());
      setTimeout(() => f());
    });
  }
  await Promise.resolve();
  flushSync();
}
function get(signal) {
  var _a5, _b3, _c2;
  var flags2 = signal.f;
  var is_derived = (flags2 & DERIVED) !== 0;
  (_a5 = captured_signals) == null ? void 0 : _a5.add(signal);
  if (active_reaction !== null && !untracking) {
    var destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0;
    if (!destroyed && (current_sources === null || !current_sources.has(signal))) {
      var deps = active_reaction.deps;
      if ((active_reaction.f & REACTION_IS_UPDATING) !== 0) {
        if (signal.rv < read_version) {
          signal.rv = read_version;
          if (new_deps === null && deps !== null && deps[skipped_deps] === signal) {
            skipped_deps++;
          } else if (new_deps === null) {
            new_deps = [signal];
          } else {
            new_deps.push(signal);
          }
        }
      } else {
        (_b3 = active_reaction.deps) != null ? _b3 : active_reaction.deps = [];
        if (!includes.call(active_reaction.deps, signal)) {
          active_reaction.deps.push(signal);
        }
        var reactions = signal.reactions;
        if (reactions === null) {
          signal.reactions = [active_reaction];
        } else if (!includes.call(reactions, active_reaction)) {
          reactions.push(active_reaction);
        }
      }
    }
  }
  if (dev_fallback_default) {
    if (!untracking && reactivity_loss_tracker && !reactivity_loss_tracker.warned && (reactivity_loss_tracker.effect.f & REACTION_IS_UPDATING) === 0 && !reactivity_loss_tracker.effect_deps.has(signal)) {
      reactivity_loss_tracker.warned = true;
      await_reactivity_loss(
        /** @type {string} */
        signal.label
      );
      var trace2 = get_error("traced at");
      if (trace2) console.warn(trace2);
    }
    recent_async_deriveds.delete(signal);
    if (tracing_mode_flag && !untracking && tracing_expressions !== null && active_reaction !== null && tracing_expressions.reaction === active_reaction) {
      if (signal.trace) {
        signal.trace();
      } else {
        trace2 = get_error("traced at");
        if (trace2) {
          var entry = tracing_expressions.entries.get(signal);
          if (entry === void 0) {
            entry = { traces: [] };
            tracing_expressions.entries.set(signal, entry);
          }
          var last = entry.traces[entry.traces.length - 1];
          if (trace2.stack !== (last == null ? void 0 : last.stack)) {
            entry.traces.push(trace2);
          }
        }
      }
    }
  }
  if (is_destroying_effect && old_values.has(signal)) {
    return old_values.get(signal);
  }
  if (is_derived) {
    var derived3 = (
      /** @type {Derived} */
      signal
    );
    if (is_destroying_effect) {
      var value = derived3.v;
      if ((derived3.f & CLEAN) === 0 && derived3.reactions !== null || depends_on_old_values(derived3)) {
        value = execute_derived(derived3);
      }
      old_values.set(derived3, value);
      return value;
    }
    var should_connect = (derived3.f & CONNECTED) === 0 && !untracking && active_reaction !== null && (is_updating_effect || (active_reaction.f & CONNECTED) !== 0);
    var is_new = (derived3.f & REACTION_RAN) === 0;
    if (is_dirty(derived3)) {
      if (should_connect) {
        derived3.f |= CONNECTED;
      }
      update_derived(derived3);
    }
    if (should_connect && !is_new) {
      unfreeze_derived_effects(derived3);
      reconnect(derived3);
    }
  }
  if ((_c2 = batch_values) == null ? void 0 : _c2.has(signal)) {
    return batch_values.get(signal);
  }
  if ((signal.f & ERROR_VALUE) !== 0) {
    throw signal.v;
  }
  return signal.v;
}
function reconnect(derived3) {
  var _a5;
  derived3.f |= CONNECTED;
  if (derived3.deps === null) return;
  for (const dep of derived3.deps) {
    ((_a5 = dep.reactions) != null ? _a5 : dep.reactions = []).push(derived3);
    if ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) {
      unfreeze_derived_effects(
        /** @type {Derived} */
        dep
      );
      reconnect(
        /** @type {Derived} */
        dep
      );
    }
  }
}
function depends_on_old_values(derived3) {
  if (derived3.v === UNINITIALIZED) return true;
  if (derived3.deps === null) return false;
  for (const dep of derived3.deps) {
    if (old_values.has(dep)) {
      return true;
    }
    if ((dep.f & DERIVED) !== 0 && depends_on_old_values(
      /** @type {Derived} */
      dep
    )) {
      return true;
    }
  }
  return false;
}
function untrack(fn) {
  var previous_untracking = untracking;
  try {
    untracking = true;
    return fn();
  } finally {
    untracking = previous_untracking;
  }
}
function deep_read_state(value) {
  if (typeof value !== "object" || !value || value instanceof EventTarget) {
    return;
  }
  if (STATE_SYMBOL in value) {
    deep_read(value);
  } else if (!Array.isArray(value)) {
    for (let key2 in value) {
      const prop2 = value[key2];
      if (typeof prop2 === "object" && prop2 && STATE_SYMBOL in prop2) {
        deep_read(prop2);
      }
    }
  }
}
function deep_read(value, visited = /* @__PURE__ */ new Set()) {
  if (typeof value === "object" && value !== null && // We don't want to traverse DOM elements
  !(value instanceof EventTarget) && !visited.has(value)) {
    visited.add(value);
    if (value instanceof Date) {
      value.getTime();
    }
    for (let key2 in value) {
      try {
        deep_read(value[key2], visited);
      } catch (e) {
      }
    }
    const proto = get_prototype_of(value);
    if (proto !== Object.prototype && proto !== Array.prototype && proto !== Map.prototype && proto !== Set.prototype && proto !== Date.prototype) {
      const descriptors = get_descriptors(proto);
      for (let key2 in descriptors) {
        const get3 = descriptors[key2].get;
        if (get3) {
          try {
            get3.call(value);
          } catch (e) {
          }
        }
      }
    }
  }
}

// node_modules/svelte/src/internal/client/reactivity/effects.js
function validate_effect(rune) {
  if (active_effect === null) {
    if (active_reaction === null) {
      effect_orphan(rune);
    }
    effect_in_unowned_derived();
  }
  if (is_destroying_effect) {
    effect_in_teardown(rune);
  }
}
function push_effect(effect2, parent_effect) {
  var parent_last = parent_effect.last;
  if (parent_last === null) {
    parent_effect.last = parent_effect.first = effect2;
  } else {
    parent_last.next = effect2;
    effect2.prev = parent_last;
    parent_effect.last = effect2;
  }
}
function create_effect(type, fn) {
  var _a5, _b3;
  var parent = active_effect;
  if (dev_fallback_default) {
    while (parent !== null && (parent.f & EAGER_EFFECT) !== 0) {
      parent = parent.parent;
    }
  }
  if (parent !== null && (parent.f & INERT) !== 0) {
    type |= INERT;
  }
  var effect2 = {
    ctx: component_context,
    deps: null,
    nodes: null,
    f: type | DIRTY | CONNECTED,
    first: null,
    fn,
    last: null,
    next: null,
    parent,
    b: parent && parent.b,
    prev: null,
    teardown: null,
    wv: 0,
    ac: null
  };
  if (dev_fallback_default) {
    effect2.component_function = dev_current_component_function;
  }
  (_a5 = current_batch) == null ? void 0 : _a5.register_created_effect(effect2);
  var e = effect2;
  if ((type & EFFECT) !== 0) {
    if (collected_effects !== null) {
      collected_effects.push(effect2);
    } else {
      Batch.ensure().schedule(effect2);
    }
  } else if (fn !== null) {
    try {
      update_effect(effect2);
    } catch (e2) {
      destroy_effect(effect2);
      throw e2;
    }
    if (e.deps === null && e.teardown === null && e.nodes === null && e.first === e.last && // either `null`, or a singular child
    (e.f & EFFECT_PRESERVED) === 0) {
      e = e.first;
      if ((type & BLOCK_EFFECT) !== 0 && (type & EFFECT_TRANSPARENT) !== 0 && e !== null) {
        e.f |= EFFECT_TRANSPARENT;
      }
    }
  }
  if (e !== null) {
    e.parent = parent;
    if (parent !== null) {
      push_effect(e, parent);
    }
    if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0 && (type & ROOT_EFFECT) === 0) {
      var derived3 = (
        /** @type {Derived} */
        active_reaction
      );
      ((_b3 = derived3.effects) != null ? _b3 : derived3.effects = []).push(e);
    }
  }
  return effect2;
}
function effect_tracking() {
  return active_reaction !== null && !untracking;
}
function teardown(fn) {
  const effect2 = create_effect(RENDER_EFFECT, null);
  set_signal_status(effect2, CLEAN);
  effect2.teardown = fn;
  return effect2;
}
function user_effect(fn) {
  var _a5;
  validate_effect("$effect");
  if (dev_fallback_default) {
    define_property(fn, "name", {
      value: "$effect"
    });
  }
  var flags2 = (
    /** @type {Effect} */
    active_effect.f
  );
  var defer = !active_reaction && (flags2 & BRANCH_EFFECT) !== 0 && component_context !== null && !component_context.i;
  if (defer) {
    var context = (
      /** @type {ComponentContext} */
      component_context
    );
    ((_a5 = context.e) != null ? _a5 : context.e = []).push(fn);
  } else {
    return create_user_effect(fn);
  }
}
function create_user_effect(fn) {
  return create_effect(EFFECT | USER_EFFECT, fn);
}
function user_pre_effect(fn) {
  validate_effect("$effect.pre");
  if (dev_fallback_default) {
    define_property(fn, "name", {
      value: "$effect.pre"
    });
  }
  return create_effect(RENDER_EFFECT | USER_EFFECT, fn);
}
function effect_root(fn) {
  Batch.ensure();
  const effect2 = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn);
  return () => {
    destroy_effect(effect2);
  };
}
function component_root(fn) {
  Batch.ensure();
  const effect2 = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn);
  return (options2 = {}) => {
    return new Promise((fulfil) => {
      if (options2.outro) {
        pause_effect(effect2, () => {
          destroy_effect(effect2);
          fulfil(void 0);
        });
      } else {
        destroy_effect(effect2);
        fulfil(void 0);
      }
    });
  };
}
function effect(fn) {
  return create_effect(EFFECT, fn);
}
function legacy_pre_effect(deps, fn) {
  var context = (
    /** @type {ComponentContextLegacy} */
    component_context
  );
  var token = { effect: null, ran: false, deps };
  context.l.$.push(token);
  token.effect = render_effect(() => {
    deps();
    if (token.ran) return;
    token.ran = true;
    var effect2 = (
      /** @type {Effect} */
      active_effect
    );
    try {
      set_active_effect(effect2.parent);
      untrack(fn);
    } finally {
      set_active_effect(effect2);
    }
  });
}
function legacy_pre_effect_reset() {
  var context = (
    /** @type {ComponentContextLegacy} */
    component_context
  );
  render_effect(() => {
    for (var token of context.l.$) {
      token.deps();
      var effect2 = token.effect;
      if ((effect2.f & CLEAN) !== 0 && effect2.deps !== null) {
        set_signal_status(effect2, MAYBE_DIRTY);
      }
      if (is_dirty(effect2)) {
        update_effect(effect2);
      }
      token.ran = false;
    }
  });
}
function async_effect(fn) {
  return create_effect(ASYNC | EFFECT_PRESERVED, fn);
}
function render_effect(fn, flags2 = 0) {
  return create_effect(RENDER_EFFECT | flags2, fn);
}
function template_effect(fn, sync = [], async2 = [], blockers = []) {
  flatten(blockers, sync, async2, (values) => {
    create_effect(RENDER_EFFECT, () => fn(...values.map(get)));
  });
}
function block(fn, flags2 = 0) {
  var effect2 = create_effect(BLOCK_EFFECT | flags2, fn);
  if (dev_fallback_default) {
    effect2.dev_stack = dev_stack;
  }
  return effect2;
}
function managed(fn, flags2 = 0) {
  var effect2 = create_effect(MANAGED_EFFECT | flags2, fn);
  if (dev_fallback_default) {
    effect2.dev_stack = dev_stack;
  }
  return effect2;
}
function branch(fn) {
  return create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn);
}
function execute_effect_teardown(effect2) {
  var teardown2 = effect2.teardown;
  if (teardown2 !== null) {
    const previously_destroying_effect = is_destroying_effect;
    const previous_reaction = active_reaction;
    set_is_destroying_effect(true);
    set_active_reaction(null);
    try {
      teardown2.call(null);
    } finally {
      set_is_destroying_effect(previously_destroying_effect);
      set_active_reaction(previous_reaction);
    }
  }
}
function destroy_effect_children(signal, remove_dom = false) {
  var effect2 = signal.first;
  signal.first = signal.last = null;
  while (effect2 !== null) {
    const controller = effect2.ac;
    if (controller !== null) {
      without_reactive_context(() => {
        controller.abort(STALE_REACTION);
      });
    }
    var next2 = effect2.next;
    if ((effect2.f & ROOT_EFFECT) !== 0) {
      effect2.parent = null;
    } else {
      destroy_effect(effect2, remove_dom);
    }
    effect2 = next2;
  }
}
function destroy_block_effect_children(signal) {
  var effect2 = signal.first;
  while (effect2 !== null) {
    var next2 = effect2.next;
    if ((effect2.f & BRANCH_EFFECT) === 0) {
      destroy_effect(effect2);
    }
    effect2 = next2;
  }
}
function destroy_effect(effect2, remove_dom = true) {
  var removed = false;
  if ((remove_dom || (effect2.f & HEAD_EFFECT) !== 0) && effect2.nodes !== null && effect2.nodes.end !== null) {
    remove_effect_dom(
      effect2.nodes.start,
      /** @type {TemplateNode} */
      effect2.nodes.end
    );
    removed = true;
  }
  set_signal_status(effect2, DESTROYING);
  destroy_effect_children(effect2, remove_dom && !removed);
  remove_reactions(effect2, 0);
  var transitions = effect2.nodes && effect2.nodes.t;
  if (transitions !== null) {
    for (const transition2 of transitions) {
      transition2.stop();
    }
  }
  execute_effect_teardown(effect2);
  effect2.f ^= DESTROYING;
  effect2.f |= DESTROYED;
  var parent = effect2.parent;
  if (parent !== null && parent.first !== null) {
    unlink_effect(effect2);
  }
  if (dev_fallback_default) {
    effect2.component_function = null;
  }
  effect2.next = effect2.prev = effect2.teardown = effect2.ctx = effect2.deps = effect2.fn = effect2.nodes = effect2.ac = effect2.b = null;
}
function remove_effect_dom(node, end) {
  while (node !== null) {
    var next2 = node === end ? null : get_next_sibling(node);
    node.remove();
    node = next2;
  }
}
function unlink_effect(effect2) {
  var parent = effect2.parent;
  var prev = effect2.prev;
  var next2 = effect2.next;
  if (prev !== null) prev.next = next2;
  if (next2 !== null) next2.prev = prev;
  if (parent !== null) {
    if (parent.first === effect2) parent.first = next2;
    if (parent.last === effect2) parent.last = prev;
  }
}
function pause_effect(effect2, callback, destroy = true) {
  var transitions = [];
  pause_children(effect2, transitions, true);
  var fn = () => {
    if (destroy) destroy_effect(effect2);
    if (callback) callback();
  };
  var remaining = transitions.length;
  if (remaining > 0) {
    var check = () => --remaining || fn();
    for (var transition2 of transitions) {
      transition2.out(check);
    }
  } else {
    fn();
  }
}
function pause_children(effect2, transitions, local) {
  if ((effect2.f & INERT) !== 0) return;
  effect2.f ^= INERT;
  var t = effect2.nodes && effect2.nodes.t;
  if (t !== null) {
    for (const transition2 of t) {
      if (transition2.is_global || local) {
        transitions.push(transition2);
      }
    }
  }
  var child2 = effect2.first;
  while (child2 !== null) {
    var sibling2 = child2.next;
    if ((child2.f & ROOT_EFFECT) === 0) {
      var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || // If this is a branch effect without a block effect parent,
      // it means the parent block effect was pruned. In that case,
      // transparency information was transferred to the branch effect.
      (child2.f & BRANCH_EFFECT) !== 0 && (effect2.f & BLOCK_EFFECT) !== 0;
      pause_children(child2, transitions, transparent ? local : false);
    }
    child2 = sibling2;
  }
}
function resume_effect(effect2) {
  resume_children(effect2, true);
}
function resume_children(effect2, local) {
  if ((effect2.f & INERT) === 0) return;
  effect2.f ^= INERT;
  if ((effect2.f & CLEAN) === 0) {
    set_signal_status(effect2, DIRTY);
    Batch.ensure().schedule(effect2);
  }
  var child2 = effect2.first;
  while (child2 !== null) {
    var sibling2 = child2.next;
    var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
    resume_children(child2, transparent ? local : false);
    child2 = sibling2;
  }
  var t = effect2.nodes && effect2.nodes.t;
  if (t !== null) {
    for (const transition2 of t) {
      if (transition2.is_global || local) {
        transition2.in();
      }
    }
  }
}
function move_effect(effect2, fragment) {
  if (!effect2.nodes) return;
  var node = effect2.nodes.start;
  var end = effect2.nodes.end;
  while (node !== null) {
    var next2 = node === end ? null : get_next_sibling(node);
    fragment.append(node);
    node = next2;
  }
}

// node_modules/svelte/src/internal/client/dom/elements/events.js
var event_symbol = /* @__PURE__ */ Symbol("events");
var all_registered_events = /* @__PURE__ */ new Set();
var root_event_handles = /* @__PURE__ */ new Set();
function create_event(event_name, dom, handler, options2 = {}) {
  function target_handler(event2) {
    if (!options2.capture) {
      handle_event_propagation.call(dom, event2);
    }
    if (!event2.cancelBubble) {
      return without_reactive_context(() => {
        return handler == null ? void 0 : handler.call(this, event2);
      });
    }
  }
  if (event_name.startsWith("pointer") || event_name.startsWith("touch") || event_name === "wheel") {
    queue_micro_task(() => {
      dom.addEventListener(event_name, target_handler, options2);
    });
  } else {
    dom.addEventListener(event_name, target_handler, options2);
  }
  return target_handler;
}
function event(event_name, dom, handler, capture2, passive2) {
  var options2 = { capture: capture2, passive: passive2 };
  var target_handler = create_event(event_name, dom, handler, options2);
  if (dom === document.body || // @ts-ignore
  dom === window || // @ts-ignore
  dom === document || // Firefox has quirky behavior, it can happen that we still get "canplay" events when the element is already removed
  dom instanceof HTMLMediaElement) {
    teardown(() => {
      dom.removeEventListener(event_name, target_handler, options2);
    });
  }
}
function delegated(event_name, element2, handler) {
  var _a5;
  ((_a5 = element2[event_symbol]) != null ? _a5 : element2[event_symbol] = {})[event_name] = handler;
}
function delegate(events) {
  for (var i = 0; i < events.length; i++) {
    all_registered_events.add(events[i]);
  }
  for (var fn of root_event_handles) {
    fn(events);
  }
}
var last_propagated_event = null;
function handle_event_propagation(event2) {
  var _a5, _b3;
  var handler_element = this;
  var owner_document = (
    /** @type {Node} */
    handler_element.ownerDocument
  );
  var event_name = event2.type;
  var path = ((_a5 = event2.composedPath) == null ? void 0 : _a5.call(event2)) || [];
  var current_target = (
    /** @type {null | Element} */
    path[0] || event2.target
  );
  last_propagated_event = event2;
  var path_idx = 0;
  var handled_at = last_propagated_event === event2 && event2[event_symbol];
  if (handled_at) {
    var at_idx = path.indexOf(handled_at);
    if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */
    window)) {
      event2[event_symbol] = handler_element;
      return;
    }
    var handler_idx = path.indexOf(handler_element);
    if (handler_idx === -1) {
      return;
    }
    if (at_idx <= handler_idx) {
      path_idx = at_idx;
    }
  }
  current_target = /** @type {Element} */
  path[path_idx] || event2.target;
  if (current_target === handler_element) return;
  define_property(event2, "currentTarget", {
    configurable: true,
    get() {
      return current_target || owner_document;
    }
  });
  var previous_reaction = active_reaction;
  var previous_effect = active_effect;
  set_active_reaction(null);
  set_active_effect(null);
  try {
    var throw_error;
    var other_errors = [];
    while (current_target !== null) {
      if (current_target === handler_element) break;
      try {
        var delegated2 = (_b3 = current_target[event_symbol]) == null ? void 0 : _b3[event_name];
        if (delegated2 != null && (!/** @type {any} */
        current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well
        // -> the target could not have been disabled because it emits the event in the first place
        event2.target === current_target)) {
          delegated2.call(current_target, event2);
        }
      } catch (error) {
        if (throw_error) {
          other_errors.push(error);
        } else {
          throw_error = error;
        }
      }
      if (event2.cancelBubble) break;
      path_idx++;
      current_target = path_idx < path.length ? (
        /** @type {Element} */
        path[path_idx]
      ) : null;
    }
    if (throw_error) {
      for (let error of other_errors) {
        queueMicrotask(() => {
          throw error;
        });
      }
      throw throw_error;
    }
  } finally {
    event2[event_symbol] = handler_element;
    delete event2.currentTarget;
    set_active_reaction(previous_reaction);
    set_active_effect(previous_effect);
  }
}

// node_modules/svelte/src/internal/client/dom/reconciler.js
var _a3;
var policy = (
  // We gotta write it like this because after downleveling the pure comment may end up in the wrong location
  ((_a3 = globalThis == null ? void 0 : globalThis.window) == null ? void 0 : _a3.trustedTypes) && /* @__PURE__ */ globalThis.window.trustedTypes.createPolicy("svelte-trusted-html", {
    /** @param {string} html */
    createHTML: (html2) => {
      return html2;
    }
  })
);
function create_trusted_html(html2) {
  var _a5;
  return (
    /** @type {string} */
    (_a5 = policy == null ? void 0 : policy.createHTML(html2)) != null ? _a5 : html2
  );
}
function create_fragment_from_html(html2) {
  var elem = create_element("template");
  elem.innerHTML = create_trusted_html(html2.replaceAll("<!>", "<!---->"));
  return elem.content;
}

// node_modules/svelte/src/internal/client/dom/template.js
function assign_nodes(start, end) {
  var effect2 = (
    /** @type {Effect} */
    active_effect
  );
  if (effect2.nodes === null) {
    effect2.nodes = { start, end, a: null, t: null };
  }
}
// @__NO_SIDE_EFFECTS__
function from_html(content, flags2) {
  var is_fragment = (flags2 & TEMPLATE_FRAGMENT) !== 0;
  var use_import_node = (flags2 & TEMPLATE_USE_IMPORT_NODE) !== 0;
  var node;
  var has_start = !content.startsWith("<!>");
  return () => {
    if (hydrating) {
      assign_nodes(hydrate_node, null);
      return hydrate_node;
    }
    if (node === void 0) {
      node = create_fragment_from_html(has_start ? content : "<!>" + content);
      if (!is_fragment) node = /** @type {TemplateNode} */
      get_first_child(node);
    }
    var clone = (
      /** @type {TemplateNode} */
      use_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)
    );
    if (is_fragment) {
      var start = (
        /** @type {TemplateNode} */
        get_first_child(clone)
      );
      var end = (
        /** @type {TemplateNode} */
        clone.lastChild
      );
      assign_nodes(start, end);
    } else {
      assign_nodes(clone, clone);
    }
    return clone;
  };
}
// @__NO_SIDE_EFFECTS__
function from_namespace(content, flags2, ns = "svg") {
  var has_start = !content.startsWith("<!>");
  var is_fragment = (flags2 & TEMPLATE_FRAGMENT) !== 0;
  var wrapped = `<${ns}>${has_start ? content : "<!>" + content}</${ns}>`;
  var node;
  return () => {
    if (hydrating) {
      assign_nodes(hydrate_node, null);
      return hydrate_node;
    }
    if (!node) {
      var fragment = (
        /** @type {DocumentFragment} */
        create_fragment_from_html(wrapped)
      );
      var root22 = (
        /** @type {Element} */
        get_first_child(fragment)
      );
      if (is_fragment) {
        node = document.createDocumentFragment();
        while (get_first_child(root22)) {
          node.appendChild(
            /** @type {TemplateNode} */
            get_first_child(root22)
          );
        }
      } else {
        node = /** @type {Element} */
        get_first_child(root22);
      }
    }
    var clone = (
      /** @type {TemplateNode} */
      node.cloneNode(true)
    );
    if (is_fragment) {
      var start = (
        /** @type {TemplateNode} */
        get_first_child(clone)
      );
      var end = (
        /** @type {TemplateNode} */
        clone.lastChild
      );
      assign_nodes(start, end);
    } else {
      assign_nodes(clone, clone);
    }
    return clone;
  };
}
// @__NO_SIDE_EFFECTS__
function from_svg(content, flags2) {
  return /* @__PURE__ */ from_namespace(content, flags2, "svg");
}
function text(value = "") {
  if (!hydrating) {
    var t = create_text(value + "");
    assign_nodes(t, t);
    return t;
  }
  var node = hydrate_node;
  if (node.nodeType !== TEXT_NODE) {
    node.before(node = create_text());
    set_hydrate_node(node);
  } else {
    merge_text_nodes(
      /** @type {Text} */
      node
    );
  }
  assign_nodes(node, node);
  return node;
}
function comment() {
  if (hydrating) {
    assign_nodes(hydrate_node, null);
    return hydrate_node;
  }
  var frag = document.createDocumentFragment();
  var start = document.createComment("");
  var anchor = create_text();
  frag.append(start, anchor);
  assign_nodes(start, anchor);
  return frag;
}
function append(anchor, dom) {
  if (hydrating) {
    var effect2 = (
      /** @type {Effect & { nodes: EffectNodes }} */
      active_effect
    );
    if ((effect2.f & REACTION_RAN) === 0 || effect2.nodes.end === null) {
      effect2.nodes.end = hydrate_node;
    }
    hydrate_next();
    return;
  }
  if (anchor === null) {
    return;
  }
  anchor.before(
    /** @type {Node} */
    dom
  );
}

// node_modules/svelte/src/utils.js
function is_capture_event(name) {
  return name.endsWith("capture") && name !== "gotpointercapture" && name !== "lostpointercapture";
}
var DELEGATED_EVENTS = [
  "beforeinput",
  "click",
  "change",
  "dblclick",
  "contextmenu",
  "focusin",
  "focusout",
  "input",
  "keydown",
  "keyup",
  "mousedown",
  "mousemove",
  "mouseout",
  "mouseover",
  "mouseup",
  "pointerdown",
  "pointermove",
  "pointerout",
  "pointerover",
  "pointerup",
  "touchend",
  "touchmove",
  "touchstart"
];
function can_delegate_event(event_name) {
  return DELEGATED_EVENTS.includes(event_name);
}
var DOM_BOOLEAN_ATTRIBUTES = [
  "allowfullscreen",
  "async",
  "autofocus",
  "autoplay",
  "checked",
  "controls",
  "default",
  "disabled",
  "formnovalidate",
  "indeterminate",
  "inert",
  "ismap",
  "loop",
  "multiple",
  "muted",
  "nomodule",
  "novalidate",
  "open",
  "playsinline",
  "readonly",
  "required",
  "reversed",
  "seamless",
  "selected",
  "webkitdirectory",
  "defer",
  "disablepictureinpicture",
  "disableremoteplayback"
];
var ATTRIBUTE_ALIASES = {
  // no `class: 'className'` because we handle that separately
  formnovalidate: "formNoValidate",
  ismap: "isMap",
  nomodule: "noModule",
  playsinline: "playsInline",
  readonly: "readOnly",
  defaultvalue: "defaultValue",
  defaultchecked: "defaultChecked",
  srcobject: "srcObject",
  novalidate: "noValidate",
  allowfullscreen: "allowFullscreen",
  disablepictureinpicture: "disablePictureInPicture",
  disableremoteplayback: "disableRemotePlayback"
};
function normalize_attribute(name) {
  var _a5;
  name = name.toLowerCase();
  return (_a5 = ATTRIBUTE_ALIASES[name]) != null ? _a5 : name;
}
var DOM_PROPERTIES = [
  ...DOM_BOOLEAN_ATTRIBUTES,
  "formNoValidate",
  "isMap",
  "noModule",
  "playsInline",
  "readOnly",
  "value",
  "volume",
  "defaultValue",
  "defaultChecked",
  "srcObject",
  "noValidate",
  "allowFullscreen",
  "disablePictureInPicture",
  "disableRemotePlayback"
];
var PASSIVE_EVENTS = ["touchstart", "touchmove"];
function is_passive_event(name) {
  return PASSIVE_EVENTS.includes(name);
}
var STATE_CREATION_RUNES = (
  /** @type {const} */
  [
    "$state",
    "$state.raw",
    "$derived",
    "$derived.by"
  ]
);
var RUNES = (
  /** @type {const} */
  [
    ...STATE_CREATION_RUNES,
    "$state.eager",
    "$state.snapshot",
    "$props",
    "$props.id",
    "$bindable",
    "$effect",
    "$effect.pre",
    "$effect.tracking",
    "$effect.root",
    "$effect.pending",
    "$inspect",
    "$inspect().with",
    "$inspect.trace",
    "$host"
  ]
);

// node_modules/svelte/src/internal/client/render.js
var should_intro = true;
function set_text(text2, value) {
  var _a5, _b3;
  var str2 = value == null ? "" : typeof value === "object" ? `${value}` : value;
  if (str2 !== /** @type {any} */
  ((_b3 = text2[_a5 = TEXT_CACHE]) != null ? _b3 : text2[_a5] = text2.nodeValue)) {
    text2[TEXT_CACHE] = str2;
    text2.nodeValue = `${str2}`;
  }
}
function mount(component2, options2) {
  return _mount(component2, options2);
}
function hydrate(component2, options2) {
  var _a5;
  init_operations();
  options2.intro = (_a5 = options2.intro) != null ? _a5 : false;
  const target = options2.target;
  const was_hydrating = hydrating;
  const previous_hydrate_node = hydrate_node;
  try {
    var anchor = get_first_child(target);
    while (anchor && (anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */
    anchor.data !== HYDRATION_START)) {
      anchor = get_next_sibling(anchor);
    }
    if (!anchor) {
      throw HYDRATION_ERROR;
    }
    set_hydrating(true);
    set_hydrate_node(
      /** @type {Comment} */
      anchor
    );
    const instance = _mount(component2, { ...options2, anchor });
    set_hydrating(false);
    return (
      /**  @type {Exports} */
      instance
    );
  } catch (error) {
    if (error instanceof Error && error.message.split("\n").some((line) => line.startsWith("https://svelte.dev/e/"))) {
      throw error;
    }
    if (error !== HYDRATION_ERROR) {
      console.warn("Failed to hydrate: ", error);
    }
    if (options2.recover === false) {
      hydration_failed();
    }
    init_operations();
    clear_text_content(target);
    set_hydrating(false);
    return mount(component2, options2);
  } finally {
    set_hydrating(was_hydrating);
    set_hydrate_node(previous_hydrate_node);
  }
}
var listeners = /* @__PURE__ */ new Map();
function _mount(Component2, { target, anchor, props = {}, events, context, intro = true, transformError }) {
  init_operations();
  var component2 = void 0;
  var unmount2 = component_root(() => {
    var anchor_node = anchor != null ? anchor : target.appendChild(create_text());
    boundary(
      /** @type {TemplateNode} */
      anchor_node,
      {
        pending: () => {
        }
      },
      (anchor_node2) => {
        push({});
        var ctx = (
          /** @type {ComponentContext} */
          component_context
        );
        if (context) ctx.c = context;
        if (events) {
          props.$$events = events;
        }
        if (hydrating) {
          assign_nodes(
            /** @type {TemplateNode} */
            anchor_node2,
            null
          );
        }
        should_intro = intro;
        component2 = Component2(anchor_node2, props) || {};
        should_intro = true;
        if (hydrating) {
          active_effect.nodes.end = hydrate_node;
          if (hydrate_node === null || hydrate_node.nodeType !== COMMENT_NODE || /** @type {Comment} */
          hydrate_node.data !== HYDRATION_END) {
            hydration_mismatch();
            throw HYDRATION_ERROR;
          }
        }
        pop();
      },
      transformError
    );
    var registered_events = /* @__PURE__ */ new Set();
    var event_handle = (events2) => {
      for (var i = 0; i < events2.length; i++) {
        var event_name = events2[i];
        if (registered_events.has(event_name)) continue;
        registered_events.add(event_name);
        var passive2 = is_passive_event(event_name);
        for (const node of [target, document]) {
          var counts = listeners.get(node);
          if (counts === void 0) {
            counts = /* @__PURE__ */ new Map();
            listeners.set(node, counts);
          }
          var count = counts.get(event_name);
          if (count === void 0) {
            node.addEventListener(event_name, handle_event_propagation, { passive: passive2 });
            counts.set(event_name, 1);
          } else {
            counts.set(event_name, count + 1);
          }
        }
      }
    };
    event_handle(array_from(all_registered_events));
    root_event_handles.add(event_handle);
    return () => {
      var _a5;
      for (var event_name of registered_events) {
        for (const node of [target, document]) {
          var counts = (
            /** @type {Map<string, number>} */
            listeners.get(node)
          );
          var count = (
            /** @type {number} */
            counts.get(event_name)
          );
          if (--count == 0) {
            node.removeEventListener(event_name, handle_event_propagation);
            counts.delete(event_name);
            if (counts.size === 0) {
              listeners.delete(node);
            }
          } else {
            counts.set(event_name, count);
          }
        }
      }
      root_event_handles.delete(event_handle);
      if (anchor_node !== anchor) {
        (_a5 = anchor_node.parentNode) == null ? void 0 : _a5.removeChild(anchor_node);
      }
    };
  });
  mounted_components.set(component2, unmount2);
  return component2;
}
var mounted_components = /* @__PURE__ */ new WeakMap();
function unmount(component2, options2) {
  const fn = mounted_components.get(component2);
  if (fn) {
    mounted_components.delete(component2);
    return fn(options2);
  }
  if (dev_fallback_default) {
    if (STATE_SYMBOL in component2) {
      state_proxy_unmount();
    } else {
      lifecycle_double_unmount();
    }
  }
  return Promise.resolve();
}

// node_modules/svelte/src/internal/client/dom/legacy/event-modifiers.js
function stopPropagation(fn) {
  return function(...args) {
    var event2 = (
      /** @type {Event} */
      args[0]
    );
    event2.stopPropagation();
    return fn == null ? void 0 : fn.apply(this, args);
  };
}
function preventDefault(fn) {
  return function(...args) {
    var event2 = (
      /** @type {Event} */
      args[0]
    );
    event2.preventDefault();
    return fn == null ? void 0 : fn.apply(this, args);
  };
}

// node_modules/svelte/src/legacy/legacy-client.js
function createClassComponent(options2) {
  return new Svelte4Component(options2);
}
var _events, _instance;
var Svelte4Component = class {
  /**
   * @param {ComponentConstructorOptions & {
   *  component: any;
   * }} options
   */
  constructor(options2) {
    /** @type {any} */
    __privateAdd(this, _events);
    /** @type {Record<string, any>} */
    __privateAdd(this, _instance);
    var _a5, _b3;
    var sources = /* @__PURE__ */ new Map();
    var add_source = (key2, value) => {
      var s = mutable_source(value, false, false);
      sources.set(key2, s);
      return s;
    };
    const props = new Proxy(
      { ...options2.props || {}, $$events: {} },
      {
        get(target, prop2) {
          var _a6;
          return get((_a6 = sources.get(prop2)) != null ? _a6 : add_source(prop2, Reflect.get(target, prop2)));
        },
        has(target, prop2) {
          var _a6;
          if (prop2 === LEGACY_PROPS) return true;
          get((_a6 = sources.get(prop2)) != null ? _a6 : add_source(prop2, Reflect.get(target, prop2)));
          return Reflect.has(target, prop2);
        },
        set(target, prop2, value) {
          var _a6;
          set((_a6 = sources.get(prop2)) != null ? _a6 : add_source(prop2, value), value);
          return Reflect.set(target, prop2, value);
        }
      }
    );
    __privateSet(this, _instance, (options2.hydrate ? hydrate : mount)(options2.component, {
      target: options2.target,
      anchor: options2.anchor,
      props,
      context: options2.context,
      intro: (_a5 = options2.intro) != null ? _a5 : false,
      recover: options2.recover,
      transformError: options2.transformError
    }));
    if (!async_mode_flag && (!((_b3 = options2 == null ? void 0 : options2.props) == null ? void 0 : _b3.$$host) || options2.sync === false)) {
      flushSync();
    }
    __privateSet(this, _events, props.$$events);
    for (const key2 of Object.keys(__privateGet(this, _instance))) {
      if (key2 === "$set" || key2 === "$destroy" || key2 === "$on") continue;
      define_property(this, key2, {
        get() {
          return __privateGet(this, _instance)[key2];
        },
        /** @param {any} value */
        set(value) {
          __privateGet(this, _instance)[key2] = value;
        },
        enumerable: true
      });
    }
    __privateGet(this, _instance).$set = /** @param {Record<string, any>} next */
    (next2) => {
      Object.assign(props, next2);
    };
    __privateGet(this, _instance).$destroy = () => {
      unmount(__privateGet(this, _instance));
    };
  }
  /** @param {Record<string, any>} props */
  $set(props) {
    __privateGet(this, _instance).$set(props);
  }
  /**
   * @param {string} event
   * @param {(...args: any[]) => any} callback
   * @returns {any}
   */
  $on(event2, callback) {
    __privateGet(this, _events)[event2] = __privateGet(this, _events)[event2] || [];
    const cb = (...args) => callback.call(this, ...args);
    __privateGet(this, _events)[event2].push(cb);
    return () => {
      __privateGet(this, _events)[event2] = __privateGet(this, _events)[event2].filter(
        /** @param {any} fn */
        (fn) => fn !== cb
      );
    };
  }
  $destroy() {
    __privateGet(this, _instance).$destroy();
  }
};
_events = new WeakMap();
_instance = new WeakMap();

// node_modules/svelte/src/version.js
var PUBLIC_VERSION = "5";

// node_modules/svelte/src/internal/disclose-version.js
var _a4, _b2, _c;
if (typeof window !== "undefined") {
  ((_c = (_b2 = (_a4 = window.__svelte) != null ? _a4 : window.__svelte = {}).v) != null ? _c : _b2.v = /* @__PURE__ */ new Set()).add(PUBLIC_VERSION);
}

// node_modules/svelte/src/internal/flags/legacy.js
enable_legacy_mode_flag();

// node_modules/svelte/src/internal/client/dom/blocks/branches.js
var _batches, _onscreen, _offscreen, _outroing, _transition, _commit, _discard;
var BranchManager = class {
  /**
   * @param {TemplateNode} anchor
   * @param {boolean} transition
   */
  constructor(anchor, transition2 = true) {
    /** @type {TemplateNode} */
    __publicField(this, "anchor");
    /** @type {Map<Batch, Key>} */
    __privateAdd(this, _batches, /* @__PURE__ */ new Map());
    /**
     * Map of keys to effects that are currently rendered in the DOM.
     * These effects are visible and actively part of the document tree.
     * Example:
     * ```
     * {#if condition}
     * 	foo
     * {:else}
     * 	bar
     * {/if}
     * ```
     * Can result in the entries `true->Effect` and `false->Effect`
     * @type {Map<Key, Effect>}
     */
    __privateAdd(this, _onscreen, /* @__PURE__ */ new Map());
    /**
     * Similar to #onscreen with respect to the keys, but contains branches that are not yet
     * in the DOM, because their insertion is deferred.
     * @type {Map<Key, Branch>}
     */
    __privateAdd(this, _offscreen, /* @__PURE__ */ new Map());
    /**
     * Keys of effects that are currently outroing
     * @type {Set<Key>}
     */
    __privateAdd(this, _outroing, /* @__PURE__ */ new Set());
    /**
     * Whether to pause (i.e. outro) on change, or destroy immediately.
     * This is necessary for `<svelte:element>`
     */
    __privateAdd(this, _transition, true);
    /**
     * @param {Batch} batch
     */
    __privateAdd(this, _commit, (batch) => {
      if (!__privateGet(this, _batches).has(batch)) return;
      var key2 = (
        /** @type {Key} */
        __privateGet(this, _batches).get(batch)
      );
      var onscreen = __privateGet(this, _onscreen).get(key2);
      if (onscreen) {
        resume_effect(onscreen);
        __privateGet(this, _outroing).delete(key2);
      } else {
        var offscreen = __privateGet(this, _offscreen).get(key2);
        if (offscreen) {
          resume_effect(offscreen.effect);
          __privateGet(this, _onscreen).set(key2, offscreen.effect);
          __privateGet(this, _offscreen).delete(key2);
          if (dev_fallback_default) {
            offscreen.fragment.lastChild[HMR_ANCHOR] = this.anchor;
          }
          offscreen.fragment.lastChild.remove();
          this.anchor.before(offscreen.fragment);
          onscreen = offscreen.effect;
        }
      }
      for (const [b, k] of __privateGet(this, _batches)) {
        __privateGet(this, _batches).delete(b);
        if (b === batch) {
          break;
        }
        const offscreen2 = __privateGet(this, _offscreen).get(k);
        if (offscreen2) {
          destroy_effect(offscreen2.effect);
          __privateGet(this, _offscreen).delete(k);
        }
      }
      for (const [k, effect2] of __privateGet(this, _onscreen)) {
        if (k === key2 || __privateGet(this, _outroing).has(k)) continue;
        const on_destroy = () => {
          const keys = Array.from(__privateGet(this, _batches).values());
          if (keys.includes(k)) {
            var fragment = document.createDocumentFragment();
            move_effect(effect2, fragment);
            fragment.append(create_text());
            __privateGet(this, _offscreen).set(k, { effect: effect2, fragment });
          } else {
            destroy_effect(effect2);
          }
          __privateGet(this, _outroing).delete(k);
          __privateGet(this, _onscreen).delete(k);
        };
        if (__privateGet(this, _transition) || !onscreen) {
          __privateGet(this, _outroing).add(k);
          pause_effect(effect2, on_destroy, false);
        } else {
          on_destroy();
        }
      }
    });
    /**
     * @param {Batch} batch
     */
    __privateAdd(this, _discard, (batch) => {
      __privateGet(this, _batches).delete(batch);
      const keys = Array.from(__privateGet(this, _batches).values());
      for (const [k, branch2] of __privateGet(this, _offscreen)) {
        if (!keys.includes(k)) {
          destroy_effect(branch2.effect);
          __privateGet(this, _offscreen).delete(k);
        }
      }
    });
    this.anchor = anchor;
    __privateSet(this, _transition, transition2);
  }
  /**
   *
   * @param {any} key
   * @param {null | ((target: TemplateNode) => void)} fn
   */
  ensure(key2, fn) {
    var batch = (
      /** @type {Batch} */
      current_batch
    );
    var defer = should_defer_append();
    if (fn && !__privateGet(this, _onscreen).has(key2) && !__privateGet(this, _offscreen).has(key2)) {
      if (defer) {
        var fragment = document.createDocumentFragment();
        var target = create_text();
        fragment.append(target);
        __privateGet(this, _offscreen).set(key2, {
          effect: branch(() => fn(target)),
          fragment
        });
      } else {
        __privateGet(this, _onscreen).set(
          key2,
          branch(() => fn(this.anchor))
        );
      }
    }
    __privateGet(this, _batches).set(batch, key2);
    if (defer) {
      for (const [k, effect2] of __privateGet(this, _onscreen)) {
        if (k === key2) {
          batch.unskip_effect(effect2);
        } else {
          batch.skip_effect(effect2);
        }
      }
      for (const [k, branch2] of __privateGet(this, _offscreen)) {
        if (k === key2) {
          batch.unskip_effect(branch2.effect);
        } else {
          batch.skip_effect(branch2.effect);
        }
      }
      batch.oncommit(__privateGet(this, _commit));
      batch.ondiscard(__privateGet(this, _discard));
    } else {
      if (hydrating) {
        this.anchor = hydrate_node;
      }
      __privateGet(this, _commit).call(this, batch);
    }
  }
};
_batches = new WeakMap();
_onscreen = new WeakMap();
_offscreen = new WeakMap();
_outroing = new WeakMap();
_transition = new WeakMap();
_commit = new WeakMap();
_discard = new WeakMap();

// node_modules/svelte/src/index-client.js
if (dev_fallback_default) {
  let throw_rune_error = function(rune) {
    if (!(rune in globalThis)) {
      let value;
      Object.defineProperty(globalThis, rune, {
        configurable: true,
        // eslint-disable-next-line getter-return
        get: () => {
          if (value !== void 0) {
            return value;
          }
          rune_outside_svelte(rune);
        },
        set: (v) => {
          value = v;
        }
      });
    }
  };
  throw_rune_error("$state");
  throw_rune_error("$effect");
  throw_rune_error("$derived");
  throw_rune_error("$inspect");
  throw_rune_error("$props");
  throw_rune_error("$bindable");
}
function onMount(fn) {
  if (component_context === null) {
    lifecycle_outside_component("onMount");
  }
  if (legacy_mode_flag && component_context.l !== null) {
    init_update_callbacks(component_context).m.push(fn);
  } else {
    user_effect(() => {
      const cleanup = untrack(fn);
      if (typeof cleanup === "function") return (
        /** @type {() => void} */
        cleanup
      );
    });
  }
}
function onDestroy(fn) {
  if (component_context === null) {
    lifecycle_outside_component("onDestroy");
  }
  onMount(() => () => untrack(fn));
}
function create_custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
  return new CustomEvent(type, { detail, bubbles, cancelable });
}
function createEventDispatcher() {
  const active_component_context = component_context;
  if (active_component_context === null) {
    lifecycle_outside_component("createEventDispatcher");
  }
  return (type, detail, options2) => {
    var _a5;
    const events = (
      /** @type {Record<string, Function | Function[]>} */
      (_a5 = active_component_context.s.$$events) == null ? void 0 : _a5[
        /** @type {string} */
        type
      ]
    );
    if (events) {
      const callbacks = is_array(events) ? events.slice() : [events];
      const event2 = create_custom_event(
        /** @type {string} */
        type,
        detail,
        options2
      );
      for (const fn of callbacks) {
        fn.call(active_component_context.x, event2);
      }
      return !event2.defaultPrevented;
    }
    return true;
  };
}
function beforeUpdate(fn) {
  if (component_context === null) {
    lifecycle_outside_component("beforeUpdate");
  }
  if (component_context.l === null) {
    lifecycle_legacy_only("beforeUpdate");
  }
  init_update_callbacks(component_context).b.push(fn);
}
function init_update_callbacks(context) {
  var _a5;
  var l = (
    /** @type {ComponentContextLegacy} */
    context.l
  );
  return (_a5 = l.u) != null ? _a5 : l.u = { a: [], b: [], m: [] };
}

// node_modules/svelte/src/internal/client/dev/css.js
var all_styles = /* @__PURE__ */ new Map();
function register_style(hash2, style) {
  var styles = all_styles.get(hash2);
  if (!styles) {
    styles = /* @__PURE__ */ new Set();
    all_styles.set(hash2, styles);
  }
  styles.add(style);
}

// node_modules/svelte/src/internal/client/dom/blocks/if.js
function if_block(node, fn, elseif = false) {
  var marker;
  if (hydrating) {
    marker = hydrate_node;
    hydrate_next();
  }
  var branches = new BranchManager(node);
  var flags2 = elseif ? EFFECT_TRANSPARENT : 0;
  function update_branch(key2, fn2) {
    if (hydrating) {
      var data = read_hydration_instruction(
        /** @type {TemplateNode} */
        marker
      );
      if (key2 !== parseInt(data.substring(1))) {
        var anchor = skip_nodes();
        set_hydrate_node(anchor);
        branches.anchor = anchor;
        set_hydrating(false);
        branches.ensure(key2, fn2);
        set_hydrating(true);
        return;
      }
    }
    branches.ensure(key2, fn2);
  }
  block(() => {
    var has_branch = false;
    fn((fn2, key2 = 0) => {
      has_branch = true;
      update_branch(key2, fn2);
    });
    if (!has_branch) {
      update_branch(-1, null);
    }
  }, flags2);
}

// node_modules/svelte/src/internal/client/dom/blocks/css-props.js
function css_props(element2, get_styles) {
  if (hydrating) {
    set_hydrate_node(get_first_child(element2));
  }
  render_effect(() => {
    var styles = get_styles();
    for (var key2 in styles) {
      var value = styles[key2];
      if (value) {
        element2.style.setProperty(key2, value);
      } else {
        element2.style.removeProperty(key2);
      }
    }
  });
}

// node_modules/svelte/src/internal/client/dom/blocks/each.js
function index(_, i) {
  return i;
}
function pause_effects(state2, to_destroy, controlled_anchor) {
  var _a5;
  var transitions = [];
  var length = to_destroy.length;
  var group;
  var remaining = to_destroy.length;
  for (var i = 0; i < length; i++) {
    let effect2 = to_destroy[i];
    pause_effect(
      effect2,
      () => {
        if (group) {
          group.pending.delete(effect2);
          group.done.add(effect2);
          if (group.pending.size === 0) {
            var groups = (
              /** @type {Set<EachOutroGroup>} */
              state2.outrogroups
            );
            destroy_effects(state2, array_from(group.done));
            groups.delete(group);
            if (groups.size === 0) {
              state2.outrogroups = null;
            }
          }
        } else {
          remaining -= 1;
        }
      },
      false
    );
  }
  if (remaining === 0) {
    var fast_path = transitions.length === 0 && controlled_anchor !== null;
    if (fast_path) {
      var anchor = (
        /** @type {Element} */
        controlled_anchor
      );
      var parent_node = (
        /** @type {Element} */
        anchor.parentNode
      );
      clear_text_content(parent_node);
      parent_node.append(anchor);
      state2.items.clear();
    }
    destroy_effects(state2, to_destroy, !fast_path);
  } else {
    group = {
      pending: new Set(to_destroy),
      done: /* @__PURE__ */ new Set()
    };
    ((_a5 = state2.outrogroups) != null ? _a5 : state2.outrogroups = /* @__PURE__ */ new Set()).add(group);
  }
}
function destroy_effects(state2, to_destroy, remove_dom = true) {
  var preserved_effects;
  if (state2.pending.size > 0) {
    preserved_effects = /* @__PURE__ */ new Set();
    for (const keys of state2.pending.values()) {
      for (const key2 of keys) {
        preserved_effects.add(
          /** @type {EachItem} */
          state2.items.get(key2).e
        );
      }
    }
  }
  for (var i = 0; i < to_destroy.length; i++) {
    var e = to_destroy[i];
    if (preserved_effects == null ? void 0 : preserved_effects.has(e)) {
      e.f |= EFFECT_OFFSCREEN;
      const fragment = document.createDocumentFragment();
      move_effect(e, fragment);
    } else {
      destroy_effect(to_destroy[i], remove_dom);
    }
  }
}
var offscreen_anchor;
function each(node, flags2, get_collection, get_key, render_fn2, fallback_fn = null) {
  var anchor = node;
  var items = /* @__PURE__ */ new Map();
  var is_controlled = (flags2 & EACH_IS_CONTROLLED) !== 0;
  if (is_controlled) {
    var parent_node = (
      /** @type {Element} */
      node
    );
    anchor = hydrating ? set_hydrate_node(get_first_child(parent_node)) : parent_node.appendChild(create_text());
  }
  if (hydrating) {
    hydrate_next();
  }
  var fallback2 = null;
  var each_array = derived_safe_equal(() => {
    var collection = get_collection();
    return is_array(collection) ? collection : collection == null ? [] : array_from(collection);
  });
  if (dev_fallback_default) {
    tag(each_array, "{#each ...}");
  }
  var array;
  var pending2 = /* @__PURE__ */ new Map();
  var first_run = true;
  function commit(batch) {
    if ((state2.effect.f & DESTROYED) !== 0) {
      return;
    }
    state2.pending.delete(batch);
    state2.fallback = fallback2;
    reconcile(state2, array, anchor, flags2, get_key);
    if (fallback2 !== null) {
      if (array.length === 0) {
        if ((fallback2.f & EFFECT_OFFSCREEN) === 0) {
          resume_effect(fallback2);
        } else {
          fallback2.f ^= EFFECT_OFFSCREEN;
          move(fallback2, null, anchor);
        }
      } else {
        pause_effect(fallback2, () => {
          fallback2 = null;
        });
      }
    }
  }
  function discard(batch) {
    state2.pending.delete(batch);
  }
  var effect2 = block(() => {
    array = /** @type {V[]} */
    get(each_array);
    var length = array.length;
    let mismatch = false;
    if (hydrating) {
      var is_else = read_hydration_instruction(anchor) === HYDRATION_START_ELSE;
      if (is_else !== (length === 0)) {
        anchor = skip_nodes();
        set_hydrate_node(anchor);
        set_hydrating(false);
        mismatch = true;
      }
    }
    var keys = /* @__PURE__ */ new Set();
    var batch = (
      /** @type {Batch} */
      current_batch
    );
    var defer = should_defer_append();
    for (var index2 = 0; index2 < length; index2 += 1) {
      if (hydrating && hydrate_node.nodeType === COMMENT_NODE && /** @type {Comment} */
      hydrate_node.data === HYDRATION_END) {
        anchor = /** @type {Comment} */
        hydrate_node;
        mismatch = true;
        set_hydrating(false);
      }
      var value = array[index2];
      var key2 = get_key(value, index2);
      if (dev_fallback_default) {
        var key_again = get_key(value, index2);
        if (key2 !== key_again) {
          each_key_volatile(String(index2), String(key2), String(key_again));
        }
      }
      var item = first_run ? null : items.get(key2);
      if (item) {
        if (item.v) internal_set(item.v, value);
        if (item.i) internal_set(item.i, index2);
        if (defer) {
          batch.unskip_effect(item.e);
        }
      } else {
        item = create_item(
          items,
          first_run ? anchor : offscreen_anchor != null ? offscreen_anchor : offscreen_anchor = create_text(),
          value,
          key2,
          index2,
          render_fn2,
          flags2,
          get_collection
        );
        if (!first_run) {
          item.e.f |= EFFECT_OFFSCREEN;
        }
        items.set(key2, item);
      }
      keys.add(key2);
    }
    if (length === 0 && fallback_fn && !fallback2) {
      if (first_run) {
        fallback2 = branch(() => fallback_fn(anchor));
      } else {
        fallback2 = branch(() => fallback_fn(offscreen_anchor != null ? offscreen_anchor : offscreen_anchor = create_text()));
        fallback2.f |= EFFECT_OFFSCREEN;
      }
    }
    if (length > keys.size) {
      if (dev_fallback_default) {
        validate_each_keys(array, get_key);
      } else {
        each_key_duplicate("", "", "");
      }
    }
    if (hydrating && length > 0) {
      set_hydrate_node(skip_nodes());
    }
    if (!first_run) {
      pending2.set(batch, keys);
      if (defer) {
        for (const [key3, item2] of items) {
          if (!keys.has(key3)) {
            batch.skip_effect(item2.e);
          }
        }
        batch.oncommit(commit);
        batch.ondiscard(discard);
      } else {
        commit(batch);
      }
    }
    if (mismatch) {
      set_hydrating(true);
    }
    get(each_array);
  });
  var state2 = { effect: effect2, flags: flags2, items, pending: pending2, outrogroups: null, fallback: fallback2 };
  first_run = false;
  if (hydrating) {
    anchor = hydrate_node;
  }
}
function skip_to_branch(effect2) {
  while (effect2 !== null && (effect2.f & BRANCH_EFFECT) === 0) {
    effect2 = effect2.next;
  }
  return effect2;
}
function reconcile(state2, array, anchor, flags2, get_key) {
  var _a5, _b3, _c2, _d, _e, _f, _g, _h, _i;
  var is_animated = (flags2 & EACH_IS_ANIMATED) !== 0;
  var length = array.length;
  var items = state2.items;
  var current = skip_to_branch(state2.effect.first);
  var seen;
  var prev = null;
  var to_animate;
  var matched = [];
  var stashed = [];
  var value;
  var key2;
  var effect2;
  var i;
  if (is_animated) {
    for (i = 0; i < length; i += 1) {
      value = array[i];
      key2 = get_key(value, i);
      effect2 = /** @type {EachItem} */
      items.get(key2).e;
      if ((effect2.f & EFFECT_OFFSCREEN) === 0) {
        (_b3 = (_a5 = effect2.nodes) == null ? void 0 : _a5.a) == null ? void 0 : _b3.measure();
        (to_animate != null ? to_animate : to_animate = /* @__PURE__ */ new Set()).add(effect2);
      }
    }
  }
  for (i = 0; i < length; i += 1) {
    value = array[i];
    key2 = get_key(value, i);
    effect2 = /** @type {EachItem} */
    items.get(key2).e;
    if (state2.outrogroups !== null) {
      for (const group of state2.outrogroups) {
        group.pending.delete(effect2);
        group.done.delete(effect2);
      }
    }
    if ((effect2.f & INERT) !== 0) {
      resume_effect(effect2);
      if (is_animated) {
        (_d = (_c2 = effect2.nodes) == null ? void 0 : _c2.a) == null ? void 0 : _d.unfix();
        (to_animate != null ? to_animate : to_animate = /* @__PURE__ */ new Set()).delete(effect2);
      }
    }
    if ((effect2.f & EFFECT_OFFSCREEN) !== 0) {
      effect2.f ^= EFFECT_OFFSCREEN;
      if (effect2 === current) {
        move(effect2, null, anchor);
      } else {
        var next2 = prev ? prev.next : current;
        if (effect2 === state2.effect.last) {
          state2.effect.last = effect2.prev;
        }
        if (effect2.prev) effect2.prev.next = effect2.next;
        if (effect2.next) effect2.next.prev = effect2.prev;
        link(state2, prev, effect2);
        link(state2, effect2, next2);
        move(effect2, next2, anchor);
        prev = effect2;
        matched = [];
        stashed = [];
        current = skip_to_branch(prev.next);
        continue;
      }
    }
    if (effect2 !== current) {
      if (seen !== void 0 && seen.has(effect2)) {
        if (matched.length < stashed.length) {
          var start = stashed[0];
          var j;
          prev = start.prev;
          var a = matched[0];
          var b = matched[matched.length - 1];
          for (j = 0; j < matched.length; j += 1) {
            move(matched[j], start, anchor);
          }
          for (j = 0; j < stashed.length; j += 1) {
            seen.delete(stashed[j]);
          }
          link(state2, a.prev, b.next);
          link(state2, prev, a);
          link(state2, b, start);
          current = start;
          prev = b;
          i -= 1;
          matched = [];
          stashed = [];
        } else {
          seen.delete(effect2);
          move(effect2, current, anchor);
          link(state2, effect2.prev, effect2.next);
          link(state2, effect2, prev === null ? state2.effect.first : prev.next);
          link(state2, prev, effect2);
          prev = effect2;
        }
        continue;
      }
      matched = [];
      stashed = [];
      while (current !== null && current !== effect2) {
        (seen != null ? seen : seen = /* @__PURE__ */ new Set()).add(current);
        stashed.push(current);
        current = skip_to_branch(current.next);
      }
      if (current === null) {
        continue;
      }
    }
    if ((effect2.f & EFFECT_OFFSCREEN) === 0) {
      matched.push(effect2);
    }
    prev = effect2;
    current = skip_to_branch(effect2.next);
  }
  if (state2.outrogroups !== null) {
    for (const group of state2.outrogroups) {
      if (group.pending.size === 0) {
        destroy_effects(state2, array_from(group.done));
        (_e = state2.outrogroups) == null ? void 0 : _e.delete(group);
      }
    }
    if (state2.outrogroups.size === 0) {
      state2.outrogroups = null;
    }
  }
  if (current !== null || seen !== void 0) {
    var to_destroy = [];
    if (seen !== void 0) {
      for (effect2 of seen) {
        if ((effect2.f & INERT) === 0) {
          to_destroy.push(effect2);
        }
      }
    }
    while (current !== null) {
      if ((current.f & INERT) === 0 && current !== state2.fallback) {
        to_destroy.push(current);
      }
      current = skip_to_branch(current.next);
    }
    var destroy_length = to_destroy.length;
    if (destroy_length > 0) {
      var controlled_anchor = (flags2 & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null;
      if (is_animated) {
        for (i = 0; i < destroy_length; i += 1) {
          (_g = (_f = to_destroy[i].nodes) == null ? void 0 : _f.a) == null ? void 0 : _g.measure();
        }
        for (i = 0; i < destroy_length; i += 1) {
          (_i = (_h = to_destroy[i].nodes) == null ? void 0 : _h.a) == null ? void 0 : _i.fix();
        }
      }
      pause_effects(state2, to_destroy, controlled_anchor);
    }
  }
  if (is_animated) {
    queue_micro_task(() => {
      var _a6, _b4;
      if (to_animate === void 0) return;
      for (effect2 of to_animate) {
        (_b4 = (_a6 = effect2.nodes) == null ? void 0 : _a6.a) == null ? void 0 : _b4.apply();
      }
    });
  }
}
function create_item(items, anchor, value, key2, index2, render_fn2, flags2, get_collection) {
  var v = (flags2 & EACH_ITEM_REACTIVE) !== 0 ? (flags2 & EACH_ITEM_IMMUTABLE) === 0 ? mutable_source(value, false, false) : source(value) : null;
  var i = (flags2 & EACH_INDEX_REACTIVE) !== 0 ? source(index2) : null;
  if (dev_fallback_default && v) {
    v.trace = () => {
      var _a5;
      get_collection()[(_a5 = i == null ? void 0 : i.v) != null ? _a5 : index2];
    };
  }
  return {
    v,
    i,
    e: branch(() => {
      render_fn2(anchor, v != null ? v : value, i != null ? i : index2, get_collection);
      return () => {
        items.delete(key2);
      };
    })
  };
}
function move(effect2, next2, anchor) {
  if (!effect2.nodes) return;
  var node = effect2.nodes.start;
  var end = effect2.nodes.end;
  var dest = next2 && (next2.f & EFFECT_OFFSCREEN) === 0 ? (
    /** @type {EffectNodes} */
    next2.nodes.start
  ) : anchor;
  while (node !== null) {
    var next_node = (
      /** @type {TemplateNode} */
      get_next_sibling(node)
    );
    dest.before(node);
    if (node === end) {
      return;
    }
    node = next_node;
  }
}
function link(state2, prev, next2) {
  if (prev === null) {
    state2.effect.first = next2;
  } else {
    prev.next = next2;
  }
  if (next2 === null) {
    state2.effect.last = prev;
  } else {
    next2.prev = prev;
  }
}
function validate_each_keys(array, key_fn) {
  const keys = /* @__PURE__ */ new Map();
  const length = array.length;
  for (let i = 0; i < length; i++) {
    const key2 = key_fn(array[i], i);
    if (keys.has(key2)) {
      const a = String(keys.get(key2));
      const b = String(i);
      let k = String(key2);
      if (k.startsWith("[object ")) k = null;
      each_key_duplicate(a, b, k);
    }
    keys.set(key2, i);
  }
}

// node_modules/svelte/src/internal/client/dom/blocks/slot.js
function slot(anchor, $$props, name, slot_props, fallback_fn) {
  var _a5;
  if (hydrating) {
    hydrate_next();
  }
  var slot_fn = (_a5 = $$props.$$slots) == null ? void 0 : _a5[name];
  var is_interop = false;
  if (slot_fn === true) {
    slot_fn = $$props[name === "default" ? "children" : name];
    is_interop = true;
  }
  if (slot_fn === void 0) {
    if (fallback_fn !== null) {
      fallback_fn(anchor);
    }
  } else {
    slot_fn(anchor, is_interop ? () => slot_props : slot_props);
  }
}
function sanitize_slots(props) {
  const sanitized = {};
  if (props.children) sanitized.default = true;
  for (const key2 in props.$$slots) {
    sanitized[key2] = true;
  }
  return sanitized;
}

// node_modules/svelte/src/internal/client/dom/css.js
function append_styles(anchor, css) {
  effect(() => {
    var _a5;
    var root22 = anchor.getRootNode();
    var target = (
      /** @type {ShadowRoot} */
      root22.host ? (
        /** @type {ShadowRoot} */
        root22
      ) : (
        /** @type {Document} */
        (_a5 = root22.head) != null ? _a5 : (
          /** @type {Document} */
          root22.ownerDocument.head
        )
      )
    );
    if (!target.querySelector("#" + css.hash)) {
      const style = create_element("style");
      style.id = css.hash;
      style.textContent = css.code;
      target.appendChild(style);
      if (dev_fallback_default) {
        register_style(css.hash, style);
      }
    }
  });
}

// node_modules/svelte/src/internal/client/dom/elements/actions.js
function action(dom, action2, get_value) {
  effect(() => {
    var payload = untrack(() => action2(dom, get_value == null ? void 0 : get_value()) || {});
    if (get_value && (payload == null ? void 0 : payload.update)) {
      var inited = false;
      var prev = (
        /** @type {any} */
        {}
      );
      render_effect(() => {
        var value = get_value();
        deep_read_state(value);
        if (inited && safe_not_equal(prev, value)) {
          prev = value;
          payload.update(value);
        }
      });
      inited = true;
    }
    if (payload == null ? void 0 : payload.destroy) {
      return () => (
        /** @type {Function} */
        payload.destroy()
      );
    }
  });
}

// node_modules/svelte/src/internal/client/dom/elements/attachments.js
function attach(node, get_fn) {
  var fn = void 0;
  var e;
  managed(() => {
    if (fn !== (fn = get_fn())) {
      if (e) {
        destroy_effect(e);
        e = null;
      }
      if (fn) {
        e = branch(() => {
          effect(() => (
            /** @type {(node: Element) => void} */
            fn(node)
          ));
        });
      }
    }
  });
}

// node_modules/clsx/dist/clsx.mjs
function r(e) {
  var t, f, n = "";
  if ("string" == typeof e || "number" == typeof e) n += e;
  else if ("object" == typeof e) if (Array.isArray(e)) {
    var o = e.length;
    for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
  } else for (f in e) e[f] && (n && (n += " "), n += f);
  return n;
}
function clsx() {
  for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
  return n;
}

// node_modules/svelte/src/internal/shared/attributes.js
function clsx2(value) {
  if (typeof value === "object") {
    return clsx(value);
  } else {
    return value != null ? value : "";
  }
}
var whitespace = [..." 	\n\r\f\xA0\v\uFEFF"];
function to_class(value, hash2, directives) {
  var classname = value == null ? "" : "" + value;
  if (hash2) {
    classname = classname ? classname + " " + hash2 : hash2;
  }
  if (directives) {
    for (var key2 of Object.keys(directives)) {
      if (directives[key2]) {
        classname = classname ? classname + " " + key2 : key2;
      } else if (classname.length) {
        var len = key2.length;
        var a = 0;
        while ((a = classname.indexOf(key2, a)) >= 0) {
          var b = a + len;
          if ((a === 0 || whitespace.includes(classname[a - 1])) && (b === classname.length || whitespace.includes(classname[b]))) {
            classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b + 1);
          } else {
            a = b;
          }
        }
      }
    }
  }
  return classname === "" ? null : classname;
}
function append_styles2(styles, important = false) {
  var separator = important ? " !important;" : ";";
  var css = "";
  for (var key2 of Object.keys(styles)) {
    var value = styles[key2];
    if (value != null && value !== "") {
      css += " " + key2 + ": " + value + separator;
    }
  }
  return css;
}
function to_css_name(name) {
  if (name[0] !== "-" || name[1] !== "-") {
    return name.toLowerCase();
  }
  return name;
}
function to_style(value, styles) {
  if (styles) {
    var new_style = "";
    var normal_styles;
    var important_styles;
    if (Array.isArray(styles)) {
      normal_styles = styles[0];
      important_styles = styles[1];
    } else {
      normal_styles = styles;
    }
    if (value) {
      value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim();
      var in_str = false;
      var in_apo = 0;
      var in_comment = false;
      var reserved_names = [];
      if (normal_styles) {
        reserved_names.push(...Object.keys(normal_styles).map(to_css_name));
      }
      if (important_styles) {
        reserved_names.push(...Object.keys(important_styles).map(to_css_name));
      }
      var start_index = 0;
      var name_index = -1;
      const len = value.length;
      for (var i = 0; i < len; i++) {
        var c = value[i];
        if (in_comment) {
          if (c === "/" && value[i - 1] === "*") {
            in_comment = false;
          }
        } else if (in_str) {
          if (in_str === c) {
            in_str = false;
          }
        } else if (c === "/" && value[i + 1] === "*") {
          in_comment = true;
        } else if (c === '"' || c === "'") {
          in_str = c;
        } else if (c === "(") {
          in_apo++;
        } else if (c === ")") {
          in_apo--;
        }
        if (!in_comment && in_str === false && in_apo === 0) {
          if (c === ":" && name_index === -1) {
            name_index = i;
          } else if (c === ";" || i === len - 1) {
            if (name_index !== -1) {
              var name = to_css_name(value.substring(start_index, name_index).trim());
              if (!reserved_names.includes(name)) {
                if (c !== ";") {
                  i++;
                }
                var property = value.substring(start_index, i).trim();
                new_style += " " + property + ";";
              }
            }
            start_index = i + 1;
            name_index = -1;
          }
        }
      }
    }
    if (normal_styles) {
      new_style += append_styles2(normal_styles);
    }
    if (important_styles) {
      new_style += append_styles2(important_styles, true);
    }
    new_style = new_style.trim();
    return new_style === "" ? null : new_style;
  }
  return value == null ? null : String(value);
}

// node_modules/svelte/src/internal/client/dom/elements/class.js
function set_class(dom, is_html, value, hash2, prev_classes, next_classes) {
  var prev = (
    /** @type {any} */
    dom[CLASS_CACHE]
  );
  if (hydrating || prev !== value || prev === void 0) {
    var next_class_name = to_class(value, hash2, next_classes);
    if (!hydrating || next_class_name !== dom.getAttribute("class")) {
      if (next_class_name == null) {
        dom.removeAttribute("class");
      } else if (is_html) {
        dom.className = next_class_name;
      } else {
        dom.setAttribute("class", next_class_name);
      }
    }
    dom[CLASS_CACHE] = value;
  } else if (next_classes && prev_classes !== next_classes) {
    for (var key2 in next_classes) {
      var is_present = !!next_classes[key2];
      if (prev_classes == null || is_present !== !!prev_classes[key2]) {
        dom.classList.toggle(key2, is_present);
      }
    }
  }
  return next_classes;
}

// node_modules/svelte/src/internal/client/dom/elements/style.js
function update_styles(dom, prev = {}, next2, priority) {
  for (var key2 in next2) {
    var value = next2[key2];
    if (prev[key2] !== value) {
      if (next2[key2] == null) {
        dom.style.removeProperty(key2);
      } else {
        dom.style.setProperty(key2, value, priority);
      }
    }
  }
}
function set_style(dom, value, prev_styles, next_styles) {
  var prev = (
    /** @type {any} */
    dom[STYLE_CACHE]
  );
  if (hydrating || prev !== value) {
    var next_style_attr = to_style(value, next_styles);
    if (!hydrating || next_style_attr !== dom.getAttribute("style")) {
      if (next_style_attr == null) {
        dom.removeAttribute("style");
      } else {
        dom.style.cssText = next_style_attr;
      }
    }
    dom[STYLE_CACHE] = value;
  } else if (next_styles) {
    if (Array.isArray(next_styles)) {
      update_styles(dom, prev_styles == null ? void 0 : prev_styles[0], next_styles[0]);
      update_styles(dom, prev_styles == null ? void 0 : prev_styles[1], next_styles[1], "important");
    } else {
      update_styles(dom, prev_styles, next_styles);
    }
  }
  return next_styles;
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/select.js
function select_option(select, value, mounting = false) {
  if (select.multiple) {
    if (value == void 0) {
      return;
    }
    if (!is_array(value)) {
      return select_multiple_invalid_value();
    }
    for (var option of select.options) {
      option.selected = value.includes(get_option_value(option));
    }
    return;
  }
  for (option of select.options) {
    var option_value = get_option_value(option);
    if (is(option_value, value)) {
      option.selected = true;
      return;
    }
  }
  if (!mounting || value !== void 0) {
    select.selectedIndex = -1;
  }
}
function init_select(select) {
  var observer = new MutationObserver(() => {
    select_option(select, select.__value);
  });
  observer.observe(select, {
    // Listen to option element changes
    childList: true,
    subtree: true,
    // because of <optgroup>
    // Listen to option element value attribute changes
    // (doesn't get notified of select value changes,
    // because that property is not reflected as an attribute)
    attributes: true,
    attributeFilter: ["value"]
  });
  teardown(() => {
    observer.disconnect();
  });
}
function get_option_value(option) {
  if ("__value" in option) {
    return option.__value;
  } else {
    return option.value;
  }
}

// node_modules/svelte/src/internal/client/dom/elements/attributes.js
var CLASS = /* @__PURE__ */ Symbol("class");
var STYLE = /* @__PURE__ */ Symbol("style");
var IS_CUSTOM_ELEMENT = /* @__PURE__ */ Symbol("is custom element");
var IS_HTML = /* @__PURE__ */ Symbol("is html");
var LINK_TAG = IS_XHTML ? "link" : "LINK";
var INPUT_TAG = IS_XHTML ? "input" : "INPUT";
var OPTION_TAG = IS_XHTML ? "option" : "OPTION";
var SELECT_TAG = IS_XHTML ? "select" : "SELECT";
var PROGRESS_TAG = IS_XHTML ? "progress" : "PROGRESS";
function remove_input_defaults(input) {
  if (!hydrating) return;
  var already_removed = false;
  var remove_defaults = () => {
    if (already_removed) return;
    already_removed = true;
    if (input.hasAttribute("value")) {
      var value = input.value;
      set_attribute2(input, "value", null);
      input.value = value;
    }
    if (input.hasAttribute("checked")) {
      var checked = input.checked;
      set_attribute2(input, "checked", null);
      input.checked = checked;
    }
  };
  input[FORM_RESET_HANDLER] = remove_defaults;
  queue_micro_task(remove_defaults);
  add_form_reset_listener();
}
function set_value(element2, value) {
  var attributes = get_attributes(element2);
  if (attributes.value === (attributes.value = // treat null and undefined the same for the initial value
  value != null ? value : void 0) || // @ts-expect-error
  // `progress` elements always need their value set when it's `0`
  element2.value === value && (value !== 0 || element2.nodeName !== PROGRESS_TAG)) {
    return;
  }
  element2.value = value != null ? value : "";
}
function set_checked(element2, checked) {
  var attributes = get_attributes(element2);
  if (attributes.checked === (attributes.checked = // treat null and undefined the same for the initial value
  checked != null ? checked : void 0)) {
    return;
  }
  element2.checked = checked;
}
function set_selected(element2, selected) {
  if (selected) {
    if (!element2.hasAttribute("selected")) {
      element2.setAttribute("selected", "");
    }
  } else {
    element2.removeAttribute("selected");
  }
}
function set_attribute2(element2, attribute, value, skip_warning) {
  var attributes = get_attributes(element2);
  if (hydrating) {
    attributes[attribute] = element2.getAttribute(attribute);
    if (attribute === "src" || attribute === "srcset" || attribute === "href" && element2.nodeName === LINK_TAG) {
      if (!skip_warning) {
        check_src_in_dev_hydration(element2, attribute, value != null ? value : "");
      }
      return;
    }
  }
  if (attributes[attribute] === (attributes[attribute] = value)) return;
  if (attribute === "loading") {
    element2[LOADING_ATTR_SYMBOL] = value;
  }
  if (value == null) {
    element2.removeAttribute(attribute);
  } else if (typeof value !== "string" && get_setters(element2).includes(attribute)) {
    element2[attribute] = value;
  } else {
    element2.setAttribute(attribute, value);
  }
}
function set_attributes(element2, prev, next2, css_hash, should_remove_defaults = false, skip_warning = false) {
  var _a5;
  if (hydrating && should_remove_defaults && element2.nodeName === INPUT_TAG) {
    var input = (
      /** @type {HTMLInputElement} */
      element2
    );
    var attribute = input.type === "checkbox" ? "defaultChecked" : "defaultValue";
    if (!(attribute in next2)) {
      remove_input_defaults(input);
    }
  }
  var attributes = get_attributes(element2);
  var is_custom_element = attributes[IS_CUSTOM_ELEMENT];
  var preserve_attribute_case = !attributes[IS_HTML];
  let is_hydrating_custom_element = hydrating && is_custom_element;
  if (is_hydrating_custom_element) {
    set_hydrating(false);
  }
  var current = prev || {};
  var is_option_element = element2.nodeName === OPTION_TAG;
  for (var key2 in prev) {
    if (!(key2 in next2)) {
      next2[key2] = null;
    }
  }
  if (next2.class) {
    next2.class = clsx2(next2.class);
  } else if (css_hash || next2[CLASS]) {
    next2.class = null;
  }
  if (next2[STYLE]) {
    (_a5 = next2.style) != null ? _a5 : next2.style = null;
  }
  var setters = get_setters(element2);
  for (const key3 in next2) {
    let value = next2[key3];
    if (is_option_element && key3 === "value" && value == null) {
      element2.value = element2.__value = "";
      current[key3] = value;
      continue;
    }
    if (key3 === "class") {
      var is_html = element2.namespaceURI === "http://www.w3.org/1999/xhtml";
      set_class(element2, is_html, value, css_hash, prev == null ? void 0 : prev[CLASS], next2[CLASS]);
      current[key3] = value;
      current[CLASS] = next2[CLASS];
      continue;
    }
    if (key3 === "style") {
      set_style(element2, value, prev == null ? void 0 : prev[STYLE], next2[STYLE]);
      current[key3] = value;
      current[STYLE] = next2[STYLE];
      continue;
    }
    var prev_value = current[key3];
    if (value === prev_value && !(value === void 0 && element2.hasAttribute(key3))) {
      continue;
    }
    current[key3] = value;
    var prefix = key3[0] + key3[1];
    if (prefix === "$$") continue;
    if (prefix === "on") {
      const opts = {};
      const event_handle_key = "$$" + key3;
      let event_name = key3.slice(2);
      var is_delegated = can_delegate_event(event_name);
      if (is_capture_event(event_name)) {
        event_name = event_name.slice(0, -7);
        opts.capture = true;
      }
      if (!is_delegated && prev_value) {
        if (value != null) continue;
        element2.removeEventListener(event_name, current[event_handle_key], opts);
        current[event_handle_key] = null;
      }
      if (is_delegated) {
        delegated(event_name, element2, value);
        delegate([event_name]);
      } else if (value != null) {
        let handle = function(evt) {
          current[key3].call(this, evt);
        };
        current[event_handle_key] = create_event(event_name, element2, handle, opts);
      }
    } else if (key3 === "style") {
      set_attribute2(element2, key3, value);
    } else if (key3 === "autofocus") {
      autofocus(
        /** @type {HTMLElement} */
        element2,
        Boolean(value)
      );
    } else if (!is_custom_element && (key3 === "__value" || key3 === "value" && value != null)) {
      element2.value = element2.__value = value;
    } else if (key3 === "selected" && is_option_element) {
      set_selected(
        /** @type {HTMLOptionElement} */
        element2,
        value
      );
    } else {
      var name = key3;
      if (!preserve_attribute_case) {
        name = normalize_attribute(name);
      }
      var is_default = name === "defaultValue" || name === "defaultChecked";
      if (value == null && !is_custom_element && !is_default) {
        attributes[key3] = null;
        if (name === "value" || name === "checked") {
          let input2 = (
            /** @type {HTMLInputElement} */
            element2
          );
          const use_default = prev === void 0;
          if (name === "value") {
            let previous = input2.defaultValue;
            input2.removeAttribute(name);
            input2.defaultValue = previous;
            input2.value = input2.__value = use_default ? previous : null;
          } else {
            let previous = input2.defaultChecked;
            input2.removeAttribute(name);
            input2.defaultChecked = previous;
            input2.checked = use_default ? previous : false;
          }
        } else {
          element2.removeAttribute(key3);
        }
      } else if (is_default || setters.includes(name) && (is_custom_element || typeof value !== "string")) {
        element2[name] = value;
        if (name in attributes) attributes[name] = UNINITIALIZED;
      } else if (typeof value !== "function") {
        set_attribute2(element2, name, value, skip_warning);
      }
    }
  }
  if (is_hydrating_custom_element) {
    set_hydrating(true);
  }
  return current;
}
function attribute_effect(element2, fn, sync = [], async2 = [], blockers = [], css_hash, should_remove_defaults = false, skip_warning = false) {
  flatten(blockers, sync, async2, (values) => {
    var prev = void 0;
    var effects = {};
    var is_select = element2.nodeName === SELECT_TAG;
    var inited = false;
    managed(() => {
      var next2 = fn(...values.map(get));
      var current = set_attributes(
        element2,
        prev,
        next2,
        css_hash,
        should_remove_defaults,
        skip_warning
      );
      if (inited && is_select && "value" in next2) {
        select_option(
          /** @type {HTMLSelectElement} */
          element2,
          next2.value
        );
      }
      for (let symbol of Object.getOwnPropertySymbols(effects)) {
        if (!next2[symbol]) destroy_effect(effects[symbol]);
      }
      for (let symbol of Object.getOwnPropertySymbols(next2)) {
        var n = next2[symbol];
        if (symbol.description === ATTACHMENT_KEY && (!prev || n !== prev[symbol])) {
          if (effects[symbol]) destroy_effect(effects[symbol]);
          effects[symbol] = branch(() => attach(element2, () => n));
        }
        current[symbol] = n;
      }
      prev = current;
    });
    if (is_select) {
      var select = (
        /** @type {HTMLSelectElement} */
        element2
      );
      effect(() => {
        select_option(
          select,
          /** @type {Record<string | symbol, any>} */
          prev.value,
          true
        );
        init_select(select);
      });
    }
    inited = true;
  });
}
function get_attributes(element2) {
  var _a5, _b3;
  return (
    /** @type {Record<string | symbol, unknown>} **/
    /** @type {any} */
    (_b3 = element2[_a5 = ATTRIBUTES_CACHE]) != null ? _b3 : element2[_a5] = {
      [IS_CUSTOM_ELEMENT]: element2.nodeName.includes("-"),
      [IS_HTML]: element2.namespaceURI === NAMESPACE_HTML
    }
  );
}
var setters_cache = /* @__PURE__ */ new Map();
function get_setters(element2) {
  var cache_key = element2.getAttribute("is") || element2.nodeName;
  var setters = setters_cache.get(cache_key);
  if (setters) return setters;
  setters_cache.set(cache_key, setters = []);
  var descriptors;
  var proto = element2;
  var element_proto = Element.prototype;
  while (element_proto !== proto) {
    descriptors = get_descriptors(proto);
    for (var key2 in descriptors) {
      if (descriptors[key2].set && // better safe than sorry, we don't want spread attributes to mess with HTML content
      key2 !== "innerHTML" && key2 !== "textContent" && key2 !== "innerText") {
        setters.push(key2);
      }
    }
    proto = get_prototype_of(proto);
  }
  return setters;
}
function check_src_in_dev_hydration(element2, attribute, value) {
  var _a5;
  if (!dev_fallback_default) return;
  if (attribute === "srcset" && srcset_url_equal(element2, value)) return;
  if (src_url_equal((_a5 = element2.getAttribute(attribute)) != null ? _a5 : "", value)) return;
  hydration_attribute_changed(
    attribute,
    element2.outerHTML.replace(element2.innerHTML, element2.innerHTML && "..."),
    String(value)
  );
}
function src_url_equal(element_src, url) {
  if (element_src === url) return true;
  return new URL(element_src, document.baseURI).href === new URL(url, document.baseURI).href;
}
function split_srcset(srcset) {
  return srcset.split(",").map((src) => src.trim().split(" ").filter(Boolean));
}
function srcset_url_equal(element2, srcset) {
  var element_urls = split_srcset(element2.srcset);
  var urls = split_srcset(srcset);
  return urls.length === element_urls.length && urls.every(
    ([url, width], i) => width === element_urls[i][1] && // We need to test both ways because Vite will create an a full URL with
    // `new URL(asset, import.meta.url).href` for the client when `base: './'`, and the
    // relative URLs inside srcset are not automatically resolved to absolute URLs by
    // browsers (in contrast to img.src). This means both SSR and DOM code could
    // contain relative or absolute URLs.
    (src_url_equal(element_urls[i][0], url) || src_url_equal(url, element_urls[i][0]))
  );
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/input.js
function bind_value(input, get3, set2 = get3) {
  var batches = /* @__PURE__ */ new WeakSet();
  listen_to_event_and_reset_event(input, "input", async (is_reset) => {
    if (dev_fallback_default && input.type === "checkbox") {
      bind_invalid_checkbox_value();
    }
    var value = is_reset ? input.defaultValue : input.value;
    value = is_numberlike_input(input) ? to_number(value) : value;
    set2(value);
    if (current_batch !== null) {
      batches.add(current_batch);
    }
    await tick();
    if (value !== (value = get3())) {
      var start = input.selectionStart;
      var end = input.selectionEnd;
      var length = input.value.length;
      input.value = value != null ? value : "";
      if (end !== null) {
        var new_length = input.value.length;
        if (start === end && end === length && new_length > length) {
          input.selectionStart = new_length;
          input.selectionEnd = new_length;
        } else {
          input.selectionStart = start;
          input.selectionEnd = Math.min(end, new_length);
        }
      }
    }
  });
  if (
    // If we are hydrating and the value has since changed,
    // then use the updated value from the input instead.
    hydrating && input.defaultValue !== input.value || // If defaultValue is set, then value == defaultValue
    // TODO Svelte 6: remove input.value check and set to empty string?
    untrack(get3) == null && input.value
  ) {
    set2(is_numberlike_input(input) ? to_number(input.value) : input.value);
    if (current_batch !== null) {
      batches.add(current_batch);
    }
  }
  render_effect(() => {
    if (dev_fallback_default && input.type === "checkbox") {
      bind_invalid_checkbox_value();
    }
    var value = get3();
    if (input === document.activeElement) {
      var batch = (
        /** @type {Batch} */
        async_mode_flag ? previous_batch : current_batch
      );
      if (batches.has(batch)) {
        return;
      }
    }
    if (is_numberlike_input(input) && value === to_number(input.value)) {
      return;
    }
    if (input.type === "date" && !value && !input.value) {
      return;
    }
    if (value !== input.value) {
      input.value = value != null ? value : "";
    }
  });
}
function is_numberlike_input(input) {
  var type = input.type;
  return type === "number" || type === "range";
}
function to_number(value) {
  return value === "" ? null : +value;
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/props.js
function bind_prop(props, prop2, value) {
  var desc = get_descriptor(props, prop2);
  if (desc && desc.set) {
    props[prop2] = value;
    teardown(() => {
      props[prop2] = null;
    });
  }
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/size.js
var _listeners, _observer, _options, _ResizeObserverSingleton_instances, getObserver_fn;
var _ResizeObserverSingleton = class _ResizeObserverSingleton {
  /** @param {ResizeObserverOptions} options */
  constructor(options2) {
    __privateAdd(this, _ResizeObserverSingleton_instances);
    /** */
    __privateAdd(this, _listeners, /* @__PURE__ */ new WeakMap());
    /** @type {ResizeObserver | undefined} */
    __privateAdd(this, _observer);
    /** @type {ResizeObserverOptions} */
    __privateAdd(this, _options);
    __privateSet(this, _options, options2);
  }
  /**
   * @param {Element} element
   * @param {(entry: ResizeObserverEntry) => any} listener
   */
  observe(element2, listener) {
    var listeners2 = __privateGet(this, _listeners).get(element2) || /* @__PURE__ */ new Set();
    listeners2.add(listener);
    __privateGet(this, _listeners).set(element2, listeners2);
    __privateMethod(this, _ResizeObserverSingleton_instances, getObserver_fn).call(this).observe(element2, __privateGet(this, _options));
    return () => {
      var listeners3 = __privateGet(this, _listeners).get(element2);
      listeners3.delete(listener);
      if (listeners3.size === 0) {
        __privateGet(this, _listeners).delete(element2);
        __privateGet(this, _observer).unobserve(element2);
      }
    };
  }
};
_listeners = new WeakMap();
_observer = new WeakMap();
_options = new WeakMap();
_ResizeObserverSingleton_instances = new WeakSet();
getObserver_fn = function() {
  var _a5;
  return (_a5 = __privateGet(this, _observer)) != null ? _a5 : __privateSet(this, _observer, new ResizeObserver(
    /** @param {any} entries */
    (entries) => {
      for (var entry of entries) {
        _ResizeObserverSingleton.entries.set(entry.target, entry);
        for (var listener of __privateGet(this, _listeners).get(entry.target) || []) {
          listener(entry);
        }
      }
    }
  ));
};
/** @static */
__publicField(_ResizeObserverSingleton, "entries", /* @__PURE__ */ new WeakMap());
var ResizeObserverSingleton = _ResizeObserverSingleton;
var resize_observer_border_box = /* @__PURE__ */ new ResizeObserverSingleton({
  box: "border-box"
});
function bind_element_size(element2, type, set2) {
  var unsub = resize_observer_border_box.observe(element2, () => set2(element2[type]));
  effect(() => {
    untrack(() => set2(element2[type]));
    return unsub;
  });
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/this.js
function is_bound_this(bound_value, element_or_component) {
  return bound_value === element_or_component || (bound_value == null ? void 0 : bound_value[STATE_SYMBOL]) === element_or_component;
}
function bind_this(element_or_component = {}, update2, get_value, get_parts) {
  var component_effect = (
    /** @type {ComponentContext} */
    component_context.r
  );
  var parent = (
    /** @type {Effect} */
    active_effect
  );
  effect(() => {
    var old_parts;
    var parts;
    render_effect(() => {
      old_parts = parts;
      parts = (get_parts == null ? void 0 : get_parts()) || [];
      untrack(() => {
        if (!is_bound_this(get_value(...parts), element_or_component)) {
          update2(element_or_component, ...parts);
          if (old_parts && is_bound_this(get_value(...old_parts), element_or_component)) {
            update2(null, ...old_parts);
          }
        }
      });
    });
    return () => {
      let p = parent;
      while (p !== component_effect && p.parent !== null && p.parent.f & DESTROYING) {
        p = p.parent;
      }
      const teardown2 = () => {
        if (parts && is_bound_this(get_value(...parts), element_or_component)) {
          update2(null, ...parts);
        }
      };
      const original_teardown = p.teardown;
      p.teardown = () => {
        teardown2();
        original_teardown == null ? void 0 : original_teardown();
      };
    };
  });
  return element_or_component;
}

// node_modules/svelte/src/internal/client/dom/legacy/lifecycle.js
function init(immutable = false) {
  const context = (
    /** @type {ComponentContextLegacy} */
    component_context
  );
  const callbacks = context.l.u;
  if (!callbacks) return;
  let props = () => deep_read_state(context.s);
  if (immutable) {
    let version = 0;
    let prev = (
      /** @type {Record<string, any>} */
      {}
    );
    const d = derived2(() => {
      let changed = false;
      const props2 = context.s;
      for (const key2 in props2) {
        if (props2[key2] !== prev[key2]) {
          prev[key2] = props2[key2];
          changed = true;
        }
      }
      if (changed) version++;
      return version;
    });
    props = () => get(d);
  }
  if (callbacks.b.length) {
    user_pre_effect(() => {
      observe_all(context, props);
      run_all(callbacks.b);
    });
  }
  user_effect(() => {
    const fns = untrack(() => callbacks.m.map(run));
    return () => {
      for (const fn of fns) {
        if (typeof fn === "function") {
          fn();
        }
      }
    };
  });
  if (callbacks.a.length) {
    user_effect(() => {
      observe_all(context, props);
      run_all(callbacks.a);
    });
  }
}
function observe_all(context, props) {
  if (context.l.s) {
    for (const signal of context.l.s) get(signal);
  }
  props();
}

// node_modules/svelte/src/internal/client/dom/legacy/misc.js
function bubble_event($$props, event2) {
  var _a5;
  var events = (
    /** @type {Record<string, Function[] | Function>} */
    (_a5 = $$props.$$events) == null ? void 0 : _a5[event2.type]
  );
  var callbacks = is_array(events) ? events.slice() : events == null ? [] : [events];
  for (var fn of callbacks) {
    fn.call(this, event2);
  }
}
function add_legacy_event_listener($$props, event_name, event_callback) {
  var _a5;
  $$props.$$events || ($$props.$$events = {});
  (_a5 = $$props.$$events)[event_name] || (_a5[event_name] = []);
  $$props.$$events[event_name].push(event_callback);
}
function update_legacy_props($$new_props) {
  for (var key2 in $$new_props) {
    if (key2 in this) {
      this[key2] = $$new_props[key2];
    }
  }
}

// node_modules/svelte/src/internal/client/reactivity/props.js
var legacy_rest_props_handler = {
  get(target, key2) {
    if (target.exclude.includes(key2)) return;
    get(target.version);
    return key2 in target.special ? target.special[key2]() : target.props[key2];
  },
  set(target, key2, value) {
    if (!(key2 in target.special)) {
      var previous_effect = active_effect;
      try {
        set_active_effect(target.parent_effect);
        target.special[key2] = prop(
          {
            get [key2]() {
              return target.props[key2];
            }
          },
          /** @type {string} */
          key2,
          PROPS_IS_UPDATED
        );
      } finally {
        set_active_effect(previous_effect);
      }
    }
    target.special[key2](value);
    update(target.version);
    return true;
  },
  getOwnPropertyDescriptor(target, key2) {
    if (target.exclude.includes(key2)) return;
    if (key2 in target.props) {
      return {
        enumerable: true,
        configurable: true,
        value: target.props[key2]
      };
    }
  },
  deleteProperty(target, key2) {
    if (target.exclude.includes(key2)) return true;
    target.exclude.push(key2);
    update(target.version);
    return true;
  },
  has(target, key2) {
    if (target.exclude.includes(key2)) return false;
    return key2 in target.props;
  },
  ownKeys(target) {
    return Reflect.ownKeys(target.props).filter((key2) => !target.exclude.includes(key2));
  }
};
function legacy_rest_props(props, exclude) {
  return new Proxy(
    {
      props,
      exclude,
      special: {},
      version: source(0),
      // TODO this is only necessary because we need to track component
      // destruction inside `prop`, because of `bind:this`, but it
      // seems likely that we can simplify `bind:this` instead
      parent_effect: (
        /** @type {Effect} */
        active_effect
      )
    },
    legacy_rest_props_handler
  );
}
function prop(props, key2, flags2, fallback2) {
  var _a5, _b3;
  var runes = !legacy_mode_flag || (flags2 & PROPS_IS_RUNES) !== 0;
  var bindable = (flags2 & PROPS_IS_BINDABLE) !== 0;
  var lazy = (flags2 & PROPS_IS_LAZY_INITIAL) !== 0;
  var fallback_value = (
    /** @type {V} */
    fallback2
  );
  var fallback_dirty = true;
  var fallback_signal = (
    /** @type {Derived<V> | undefined} */
    void 0
  );
  var get_fallback = () => {
    if (lazy && runes) {
      fallback_signal != null ? fallback_signal : fallback_signal = derived2(
        /** @type {() => V} */
        fallback2
      );
      return get(fallback_signal);
    }
    if (fallback_dirty) {
      fallback_dirty = false;
      fallback_value = lazy ? untrack(
        /** @type {() => V} */
        fallback2
      ) : (
        /** @type {V} */
        fallback2
      );
    }
    return fallback_value;
  };
  let setter;
  if (bindable) {
    var is_entry_props = STATE_SYMBOL in props || LEGACY_PROPS in props;
    setter = (_b3 = (_a5 = get_descriptor(props, key2)) == null ? void 0 : _a5.set) != null ? _b3 : is_entry_props && key2 in props ? (v) => props[key2] = v : void 0;
  }
  var initial_value;
  var is_store_sub = false;
  if (bindable) {
    [initial_value, is_store_sub] = capture_store_binding(() => (
      /** @type {V} */
      props[key2]
    ));
  } else {
    initial_value = /** @type {V} */
    props[key2];
  }
  if (initial_value === void 0 && fallback2 !== void 0) {
    initial_value = get_fallback();
    if (setter) {
      if (runes) props_invalid_value(key2);
      setter(initial_value);
    }
  }
  var getter;
  if (runes) {
    getter = () => {
      var value = (
        /** @type {V} */
        props[key2]
      );
      if (value === void 0) return get_fallback();
      fallback_dirty = true;
      return value;
    };
  } else {
    getter = () => {
      var value = (
        /** @type {V} */
        props[key2]
      );
      if (value !== void 0) {
        fallback_value = /** @type {V} */
        void 0;
      }
      return value === void 0 ? fallback_value : value;
    };
  }
  if (runes && (flags2 & PROPS_IS_UPDATED) === 0) {
    return getter;
  }
  if (setter) {
    var legacy_parent = props.$$legacy;
    return (
      /** @type {() => V} */
      (function(value, mutation) {
        if (arguments.length > 0) {
          if (!runes || !mutation || legacy_parent || is_store_sub) {
            setter(mutation ? getter() : value);
          }
          return value;
        }
        return getter();
      })
    );
  }
  var overridden = false;
  var d = ((flags2 & PROPS_IS_IMMUTABLE) !== 0 ? derived2 : derived_safe_equal)(() => {
    overridden = false;
    return getter();
  });
  if (dev_fallback_default) {
    d.label = key2;
  }
  if (bindable) get(d);
  var parent_effect = (
    /** @type {Effect} */
    active_effect
  );
  return (
    /** @type {() => V} */
    (function(value, mutation) {
      if (arguments.length > 0) {
        const new_value = mutation ? get(d) : runes && bindable ? proxy(value) : value;
        set(d, new_value);
        overridden = true;
        if (fallback_value !== void 0) {
          fallback_value = new_value;
        }
        return value;
      }
      if (is_destroying_effect && overridden || (parent_effect.f & DESTROYED) !== 0) {
        return d.v;
      }
      return get(d);
    })
  );
}

// node_modules/svelte/src/internal/client/dom/elements/custom-element.js
var SvelteElement;
if (typeof HTMLElement === "function") {
  SvelteElement = class extends HTMLElement {
    /**
     * @param {*} $$componentCtor
     * @param {*} $$slots
     * @param {ShadowRootInit | undefined} shadow_root_init
     */
    constructor($$componentCtor, $$slots, shadow_root_init) {
      super();
      /** The Svelte component constructor */
      __publicField(this, "$$ctor");
      /** Slots */
      __publicField(this, "$$s");
      /** @type {any} The Svelte component instance */
      __publicField(this, "$$c");
      /** Whether or not the custom element is connected */
      __publicField(this, "$$cn", false);
      /** @type {Record<string, any>} Component props data */
      __publicField(this, "$$d", {});
      /** `true` if currently in the process of reflecting component props back to attributes */
      __publicField(this, "$$r", false);
      /** @type {Record<string, CustomElementPropDefinition>} Props definition (name, reflected, type etc) */
      __publicField(this, "$$p_d", {});
      /** @type {Record<string, EventListenerOrEventListenerObject[]>} Event listeners */
      __publicField(this, "$$l", {});
      /** @type {Map<EventListenerOrEventListenerObject, Function>} Event listener unsubscribe functions */
      __publicField(this, "$$l_u", /* @__PURE__ */ new Map());
      /** @type {any} The managed render effect for reflecting attributes */
      __publicField(this, "$$me");
      /** @type {ShadowRoot | null} The ShadowRoot of the custom element */
      __publicField(this, "$$shadowRoot", null);
      this.$$ctor = $$componentCtor;
      this.$$s = $$slots;
      if (shadow_root_init) {
        this.$$shadowRoot = this.attachShadow(shadow_root_init);
      }
    }
    /**
     * @param {string} type
     * @param {EventListenerOrEventListenerObject} listener
     * @param {boolean | AddEventListenerOptions} [options]
     */
    addEventListener(type, listener, options2) {
      this.$$l[type] = this.$$l[type] || [];
      this.$$l[type].push(listener);
      if (this.$$c) {
        const unsub = this.$$c.$on(type, listener);
        this.$$l_u.set(listener, unsub);
      }
      super.addEventListener(type, listener, options2);
    }
    /**
     * @param {string} type
     * @param {EventListenerOrEventListenerObject} listener
     * @param {boolean | AddEventListenerOptions} [options]
     */
    removeEventListener(type, listener, options2) {
      super.removeEventListener(type, listener, options2);
      if (this.$$c) {
        const unsub = this.$$l_u.get(listener);
        if (unsub) {
          unsub();
          this.$$l_u.delete(listener);
        }
      }
    }
    async connectedCallback() {
      this.$$cn = true;
      if (!this.$$c) {
        let create_slot = function(name) {
          return (anchor) => {
            const slot2 = create_element("slot");
            if (name !== "default") slot2.name = name;
            append(anchor, slot2);
          };
        };
        await Promise.resolve();
        if (!this.$$cn || this.$$c) {
          return;
        }
        const $$slots = {};
        const existing_slots = get_custom_elements_slots(this);
        for (const name of this.$$s) {
          if (name in existing_slots) {
            if (name === "default" && !this.$$d.children) {
              this.$$d.children = create_slot(name);
              $$slots.default = true;
            } else {
              $$slots[name] = create_slot(name);
            }
          }
        }
        for (const attribute of this.attributes) {
          const name = this.$$g_p(attribute.name);
          if (!(name in this.$$d)) {
            this.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, "toProp");
          }
        }
        for (const key2 in this.$$p_d) {
          if (!(key2 in this.$$d) && this[key2] !== void 0) {
            this.$$d[key2] = this[key2];
            delete this[key2];
          }
        }
        this.$$c = createClassComponent({
          component: this.$$ctor,
          target: this.$$shadowRoot || this,
          props: {
            ...this.$$d,
            $$slots,
            $$host: this
          }
        });
        this.$$me = effect_root(() => {
          render_effect(() => {
            var _a5;
            this.$$r = true;
            for (const key2 of object_keys(this.$$c)) {
              if (!((_a5 = this.$$p_d[key2]) == null ? void 0 : _a5.reflect)) continue;
              this.$$d[key2] = this.$$c[key2];
              const attribute_value = get_custom_element_value(
                key2,
                this.$$d[key2],
                this.$$p_d,
                "toAttribute"
              );
              if (attribute_value == null) {
                this.removeAttribute(this.$$p_d[key2].attribute || key2);
              } else {
                this.setAttribute(this.$$p_d[key2].attribute || key2, attribute_value);
              }
            }
            this.$$r = false;
          });
        });
        for (const type in this.$$l) {
          for (const listener of this.$$l[type]) {
            const unsub = this.$$c.$on(type, listener);
            this.$$l_u.set(listener, unsub);
          }
        }
        this.$$l = {};
      }
    }
    // We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte
    // and setting attributes through setAttribute etc, this is helpful
    /**
     * @param {string} attr
     * @param {string} _oldValue
     * @param {string} newValue
     */
    attributeChangedCallback(attr2, _oldValue, newValue) {
      var _a5;
      if (this.$$r) return;
      attr2 = this.$$g_p(attr2);
      this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp");
      (_a5 = this.$$c) == null ? void 0 : _a5.$set({ [attr2]: this.$$d[attr2] });
    }
    disconnectedCallback() {
      this.$$cn = false;
      Promise.resolve().then(() => {
        if (!this.$$cn && this.$$c) {
          this.$$c.$destroy();
          this.$$me();
          this.$$c = void 0;
        }
      });
    }
    /**
     * @param {string} attribute_name
     */
    $$g_p(attribute_name) {
      return object_keys(this.$$p_d).find(
        (key2) => this.$$p_d[key2].attribute === attribute_name || !this.$$p_d[key2].attribute && key2.toLowerCase() === attribute_name
      ) || attribute_name;
    }
  };
}
function get_custom_element_value(prop2, value, props_definition, transform) {
  var _a5;
  const type = (_a5 = props_definition[prop2]) == null ? void 0 : _a5.type;
  value = type === "Boolean" && typeof value !== "boolean" ? value != null : value;
  if (!transform || !props_definition[prop2]) {
    return value;
  } else if (transform === "toAttribute") {
    switch (type) {
      case "Object":
      case "Array":
        return value == null ? null : JSON.stringify(value);
      case "Boolean":
        return value ? "" : null;
      case "Number":
        return value == null ? null : value;
      default:
        return value;
    }
  } else {
    switch (type) {
      case "Object":
      case "Array":
        return value && JSON.parse(value);
      case "Boolean":
        return value;
      // conversion already handled above
      case "Number":
        return value != null ? +value : value;
      default:
        return value;
    }
  }
}
function get_custom_elements_slots(element2) {
  const result = {};
  element2.childNodes.forEach((node) => {
    result[
      /** @type {Element} node */
      node.slot || "default"
    ] = true;
  });
  return result;
}

// src/parsing/kebab/kebab.ts
function kebab(input) {
  return input.replaceAll(/\p{Lu}/gu, (match) => `-${match.toLowerCase()}`).replaceAll(/\p{Z}/gu, "-").replaceAll(/[^\p{L}\p{N}\/-]/gu, "-").replaceAll(/-+/g, "-").replace(/^-/, "").replace(/-$/, "");
}

// src/parsing/properties/property_schema.ts
var PropertySchemaOption = /* @__PURE__ */ ((PropertySchemaOption3) => {
  PropertySchemaOption3["None"] = "none";
  PropertySchemaOption3["TasksPlugin"] = "tasks";
  PropertySchemaOption3["Dataview"] = "dataview";
  return PropertySchemaOption3;
})(PropertySchemaOption || {});
var UNIVERSAL_STATUS_PROPERTY_KEY = "status";
function findStatusRange(statusMatch) {
  var _a5, _b3;
  if (!(statusMatch == null ? void 0 : statusMatch[0])) {
    return { startIndex: -1, endIndex: -1 };
  }
  const bracketIndex = statusMatch[0].indexOf("[");
  const startIndex = bracketIndex >= 0 ? bracketIndex + 1 : -1;
  const endIndex = startIndex >= 0 ? startIndex + ((_b3 = (_a5 = statusMatch[1]) == null ? void 0 : _a5.length) != null ? _b3 : 0) : -1;
  return { startIndex, endIndex };
}
function parseUniversalStatus(rawLine) {
  var _a5, _b3;
  const match = rawLine.match(/^\s*[-*+]\s\[([^\[\]]*)\]/);
  const statusChar = match ? (_a5 = match[1]) != null ? _a5 : " " : " ";
  const { startIndex, endIndex } = findStatusRange(match);
  const value = statusChar === "" ? " " : (_b3 = Array.from(statusChar)[0]) != null ? _b3 : " ";
  return {
    key: UNIVERSAL_STATUS_PROPERTY_KEY,
    rawValue: value,
    value,
    startIndex,
    endIndex
  };
}
function createPropertyMapWithStatus(rawLine) {
  const properties = /* @__PURE__ */ new Map();
  const statusProp = parseUniversalStatus(rawLine);
  properties.set(UNIVERSAL_STATUS_PROPERTY_KEY, statusProp);
  return properties;
}

// src/parsing/properties/normalization.ts
var PROPERTY_KEY_ALIASES = {
  completion: "done",
  repeat: "recurrence"
};
function normalizePropertyKey(key2) {
  var _a5;
  return (_a5 = PROPERTY_KEY_ALIASES[key2]) != null ? _a5 : key2;
}
function getPropertyAliases(key2) {
  const canonicalKey = normalizePropertyKey(key2);
  const aliases = Object.entries(PROPERTY_KEY_ALIASES).filter(([, canonical]) => canonical === canonicalKey).map(([alias]) => alias);
  return [
    ...canonicalKey !== key2 ? [canonicalKey] : [],
    ...aliases.filter((alias) => alias !== key2)
  ];
}
function getPropertyByKey(properties, key2) {
  const exactMatch = properties.get(key2);
  if (exactMatch) return exactMatch;
  const canonicalKey = normalizePropertyKey(key2);
  for (const [propertyKey, property] of properties) {
    if (normalizePropertyKey(propertyKey) === canonicalKey) {
      return property;
    }
  }
  return void 0;
}

// src/parsing/properties/value_parsers.ts
var DATE_ONLY_PATTERN = "\\d{4}-\\d{2}-\\d{2}";
function parseDateOnly(value) {
  const match = value.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (!match) return null;
  const year = Number(match[1]);
  const month = Number(match[2]);
  const day = Number(match[3]);
  const parsed = new Date(Date.UTC(year, month - 1, day));
  return parsed.getUTCFullYear() === year && parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day ? parsed : null;
}
function parseIsoDate(value) {
  const trimmed = value.trim();
  const dateOnly = parseDateOnly(trimmed);
  if (dateOnly) return dateOnly;
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})?$/.test(trimmed)) {
    const parsed = new Date(trimmed);
    return isNaN(parsed.getTime()) ? null : parsed;
  }
  return null;
}
function parseNumber(value) {
  const trimmed = value.trim();
  if (!/^-?\d+(\.\d+)?$/.test(trimmed)) return null;
  const parsed = Number(trimmed);
  return isNaN(parsed) ? null : parsed;
}
function escapeRegExp(input) {
  return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// src/parsing/properties/tasks_schema.ts
var DATE_FIELDS = [
  { key: "due", label: "Due", emojis: ["\u{1F4C5}"] },
  { key: "scheduled", label: "Scheduled", emojis: ["\u23F3", "\u23F0"] },
  { key: "start", label: "Start", emojis: ["\u{1F6EB}"] },
  { key: "done", label: "Done", emojis: ["\u2705", "\u{1F3C1}"] },
  { key: "created", label: "Created", emojis: ["\u2795"] }
];
var TASKS_PRIORITY_OPTIONS = [
  { value: "highest", label: "Highest", emoji: "\u{1F53A}", weight: 5 },
  { value: "high", label: "High", emoji: "\u23EB", weight: 4 },
  { value: "medium", label: "Medium", emoji: "\u{1F53C}", weight: 3 },
  { value: "low", label: "Low", emoji: "\u{1F53D}", weight: 2 },
  { value: "lowest", label: "Lowest", emoji: "\u23EC", weight: 1 }
];
var PRIORITY_VALUES = new Map(
  TASKS_PRIORITY_OPTIONS.map((option) => [option.emoji, option.weight])
);
var METADATA_EMOJIS = [
  ...DATE_FIELDS.flatMap((field) => field.emojis),
  ...PRIORITY_VALUES.keys(),
  "\u{1F501}"
];
var RECURRENCE_EMOJI = "\u{1F501}";
var TASKS_PROPERTY_ICONS = {
  ...Object.fromEntries(DATE_FIELDS.map((field) => [field.key, field.emojis[0]])),
  recurrence: RECURRENCE_EMOJI
};
function getTasksPriorityEmoji(value) {
  for (const [emoji, weight] of PRIORITY_VALUES) {
    if (weight === value) return emoji;
  }
  return void 0;
}
function getTasksPriorityOption(value) {
  return TASKS_PRIORITY_OPTIONS.find((option) => option.value === value);
}
function getTasksPriorityValueFromWeight(weight) {
  var _a5;
  return (_a5 = TASKS_PRIORITY_OPTIONS.find((option) => option.weight === weight)) == null ? void 0 : _a5.value;
}
function parseDateFields(rawLine) {
  return DATE_FIELDS.flatMap(
    (field) => field.emojis.flatMap((emoji) => {
      const regex = new RegExp(`${escapeRegExp(emoji)}\\s*(${DATE_ONLY_PATTERN})`, "gu");
      return [...rawLine.matchAll(regex)].map((match) => {
        var _a5, _b3;
        return {
          index: (_a5 = match.index) != null ? _a5 : Number.MAX_SAFE_INTEGER,
          endIndex: ((_b3 = match.index) != null ? _b3 : 0) + match[0].length,
          key: field.key,
          rawValue: match[0],
          value: match[1] ? parseDateOnly(match[1]) : null
        };
      });
    })
  );
}
function parsePriorityFields(rawLine) {
  const priorityPattern = Array.from(PRIORITY_VALUES.keys()).map(escapeRegExp).join("|");
  const regex = new RegExp(priorityPattern, "gu");
  return [...rawLine.matchAll(regex)].map((match) => {
    var _a5, _b3, _c2;
    return {
      index: (_a5 = match.index) != null ? _a5 : Number.MAX_SAFE_INTEGER,
      endIndex: ((_b3 = match.index) != null ? _b3 : 0) + match[0].length,
      key: "priority",
      rawValue: match[0],
      value: (_c2 = PRIORITY_VALUES.get(match[0])) != null ? _c2 : null
    };
  });
}
function parseRecurrenceFields(rawLine) {
  const metadataPattern = METADATA_EMOJIS.map(escapeRegExp).join("|");
  const regex = new RegExp(`\u{1F501}\\s*(.+?)(?=\\s*(?:${metadataPattern})(?:\\s*${DATE_ONLY_PATTERN})?|$)`, "gu");
  return [...rawLine.matchAll(regex)].map((match) => {
    var _a5, _b3, _c2;
    const value = (_b3 = (_a5 = match[1]) == null ? void 0 : _a5.trim()) != null ? _b3 : "";
    const rawValue = match[0].trimEnd();
    const index2 = (_c2 = match.index) != null ? _c2 : Number.MAX_SAFE_INTEGER;
    return {
      index: index2,
      endIndex: index2 + rawValue.length,
      key: "recurrence",
      rawValue,
      value
    };
  }).filter((field) => field.value !== "");
}
var TasksPluginSchema = class {
  constructor() {
    this.id = "tasks" /* TasksPlugin */;
    this.label = "Tasks Plugin";
  }
  parseProperties(rawLine) {
    const properties = createPropertyMapWithStatus(rawLine);
    const parsedFields = [
      ...parseDateFields(rawLine),
      ...parsePriorityFields(rawLine),
      ...parseRecurrenceFields(rawLine)
    ].sort((a, b) => a.index - b.index);
    for (const field of parsedFields) {
      if (!properties.has(field.key)) {
        properties.set(field.key, {
          key: field.key,
          rawValue: field.rawValue,
          value: field.value,
          startIndex: field.index,
          endIndex: field.endIndex
        });
      }
    }
    return properties;
  }
  knownKeys() {
    return [
      { key: UNIVERSAL_STATUS_PROPERTY_KEY, label: "Status", type: "text" },
      { key: "due", label: "Due", type: "date" },
      { key: "scheduled", label: "Scheduled", type: "date" },
      { key: "start", label: "Start", type: "date" },
      { key: "done", label: "Done", type: "date", aliases: getPropertyAliases("done") },
      { key: "created", label: "Created", type: "date" },
      { key: "priority", label: "Priority", type: "priority" },
      { key: "recurrence", label: "Recurrence", type: "text", aliases: getPropertyAliases("recurrence") }
    ];
  }
};

// src/parsing/properties/display.ts
var PRIORITY_LABELS = {
  5: "Highest",
  4: "High",
  3: "Medium",
  2: "Low",
  1: "Lowest"
};
function formatPriorityColumnLabel(value) {
  var _a5, _b3;
  return (_b3 = (_a5 = getTasksPriorityOption(value)) == null ? void 0 : _a5.label) != null ? _b3 : value ? formatPropertyLabel(value) : "";
}
function formatPropertyLabel(key2) {
  if (!key2) return key2;
  return key2.charAt(0).toUpperCase() + key2.slice(1);
}
function formatPropertyValue(prop2) {
  var _a5;
  if (prop2.value instanceof Date) {
    return prop2.value.toLocaleDateString(void 0, {
      month: "short",
      day: "numeric",
      timeZone: "UTC"
    });
  }
  if (prop2.key === "priority" && typeof prop2.value === "number") {
    return (_a5 = PRIORITY_LABELS[prop2.value]) != null ? _a5 : String(prop2.value);
  }
  if (prop2.value === null) {
    return prop2.rawValue;
  }
  return String(prop2.value);
}
function tasksIconFor(prop2) {
  if (prop2.key === "priority" && typeof prop2.value === "number") {
    return getTasksPriorityEmoji(prop2.value);
  }
  return TASKS_PROPERTY_ICONS[prop2.key];
}
function stripDisplayedPropertiesFromContent(content, properties) {
  let result = content;
  for (const [key2, prop2] of properties) {
    if (key2 === UNIVERSAL_STATUS_PROPERTY_KEY) continue;
    if (!prop2.rawValue) continue;
    result = result.split(prop2.rawValue).join(" ");
  }
  return result.replace(/[ \t]{2,}/g, " ").trim();
}
function toDisplayProperties(properties) {
  const result = [];
  for (const [key2, prop2] of properties) {
    if (key2 === UNIVERSAL_STATUS_PROPERTY_KEY) continue;
    result.push({
      key: key2,
      label: formatPropertyLabel(key2),
      value: formatPropertyValue(prop2),
      icon: tasksIconFor(prop2)
    });
  }
  return result;
}

// src/ui/columns/definitions.ts
var RESERVED_COLUMN_KEYS = /* @__PURE__ */ new Set(["uncategorised", "done"]);
function parseColumnSpec(columnSpec) {
  const hashMatch = columnSpec.match(/^(.+?)\(#([0-9a-fA-F]{6})\)$/);
  const oxMatch = columnSpec.match(/^(.+?)\(0x([0-9a-fA-F]{6})\)$/);
  const match = hashMatch || oxMatch;
  if ((match == null ? void 0 : match[1]) && (match == null ? void 0 : match[2])) {
    return {
      raw: columnSpec,
      label: match[1],
      color: `#${match[2]}`
    };
  }
  return {
    raw: columnSpec,
    label: columnSpec
  };
}
function sanitizeIdBase(label) {
  const normalized = kebab(label).replace(/[^a-z0-9-]/g, "");
  return normalized.length > 0 ? normalized : "column";
}
function createColumnId(label, usedIds) {
  const base = `column-${sanitizeIdBase(label)}`;
  let candidate = base;
  let suffix = 2;
  while (usedIds.has(candidate) || RESERVED_COLUMN_KEYS.has(candidate)) {
    candidate = `${base}-${suffix}`;
    suffix += 1;
  }
  usedIds.add(candidate);
  return candidate;
}
function normalizeMatchTags(tags) {
  const normalized = tags.map((tag2) => tag2.trim().replace(/^#/, "")).filter((tag2) => tag2.length > 0);
  return [...new Set(normalized)];
}
function getNameModeWriteTag(column) {
  return kebab(column.label);
}
function usesTagMatching(column) {
  return column.matchMode === "tags";
}
function usesStatusMatching(column) {
  return column.matchMode === "status";
}
function usesPriorityMatching(column) {
  return column.matchMode === "priority";
}
function getColumnWriteTags(column) {
  return usesStatusMatching(column) || usesPriorityMatching(column) ? [] : usesTagMatching(column) ? column.matchTags : [getNameModeWriteTag(column)];
}
function columnRuleSignature(column) {
  var _a5, _b3, _c2;
  return usesStatusMatching(column) ? `status:${(_a5 = column.matchStatus) != null ? _a5 : ""}` : usesPriorityMatching(column) ? `priority:${(_b3 = getColumnPrioritySchema(column)) != null ? _b3 : ""}:${(_c2 = normalizePriorityMatchValue(column.matchPriority, getColumnPrioritySchema(column))) != null ? _c2 : ""}` : usesTagMatching(column) ? `tags:${[...getColumnWriteTags(column)].sort().join(",")}` : `name:${getNameModeWriteTag(column)}`;
}
function normalizeColumnMatchContext(context) {
  return context instanceof Set ? { tags: context } : context;
}
function getColumnStatus(column) {
  return column && usesStatusMatching(column) ? column.matchStatus : void 0;
}
function getColumnPriority(column) {
  return column && usesPriorityMatching(column) ? column.matchPriority : void 0;
}
function getColumnPrioritySchema(column) {
  var _a5;
  return column && usesPriorityMatching(column) ? (_a5 = column.matchPropertySchema) != null ? _a5 : "tasks" /* TasksPlugin */ : void 0;
}
function getStatusColumnLabel(status) {
  return status === " " ? "unchecked" : status != null ? status : "";
}
function getPriorityColumnLabel(priority) {
  return formatPriorityColumnLabel(priority);
}
function normalizePriorityMatchValue(priority, schema) {
  const trimmed = priority == null ? void 0 : priority.trim();
  if (!trimmed) {
    return void 0;
  }
  return schema === "dataview" /* Dataview */ ? trimmed.toLowerCase() : trimmed;
}
function matchesColumnDefinition(column, context) {
  const { tags: taskTags, status, priority, prioritySchema, priorities } = normalizeColumnMatchContext(context);
  if (usesStatusMatching(column)) {
    return !!column.matchStatus && status === column.matchStatus;
  }
  if (usesPriorityMatching(column)) {
    const columnPrioritySchema = getColumnPrioritySchema(column);
    const priorityForSchema = columnPrioritySchema ? priorities == null ? void 0 : priorities[columnPrioritySchema] : void 0;
    return !!column.matchPriority && (priorityForSchema !== void 0 ? normalizePriorityMatchValue(priorityForSchema, columnPrioritySchema) === normalizePriorityMatchValue(column.matchPriority, columnPrioritySchema) : normalizePriorityMatchValue(priority, prioritySchema) === normalizePriorityMatchValue(column.matchPriority, columnPrioritySchema) && prioritySchema === columnPrioritySchema);
  }
  if (usesTagMatching(column)) {
    const explicitTags = getColumnWriteTags(column);
    return explicitTags.length > 0 && explicitTags.every((tag2) => taskTags.has(tag2));
  }
  const derivedTag = getNameModeWriteTag(column);
  for (const tag2 of taskTags) {
    if (kebab(tag2) === derivedTag) {
      return true;
    }
  }
  return false;
}
function getColumnMatchSpecificity(column) {
  return usesTagMatching(column) ? getColumnWriteTags(column).length : 1;
}
function usesTagBasedPlacement(column) {
  return !usesStatusMatching(column) && !usesPriorityMatching(column);
}
function resolveMatchedColumnDefinition(columns, context) {
  let matchedColumn;
  let matchedSpecificity = -1;
  for (const column of columns) {
    if (!matchesColumnDefinition(column, context)) {
      continue;
    }
    const specificity = getColumnMatchSpecificity(column);
    if (!matchedColumn) {
      matchedColumn = column;
      matchedSpecificity = specificity;
      continue;
    }
    if (usesTagBasedPlacement(matchedColumn) && usesTagBasedPlacement(column) && specificity > matchedSpecificity) {
      matchedColumn = column;
      matchedSpecificity = specificity;
    }
  }
  return matchedColumn;
}
function isPlacementTag(column, tag2) {
  if (usesStatusMatching(column) || usesPriorityMatching(column)) {
    return false;
  }
  if (usesTagMatching(column)) {
    return getColumnWriteTags(column).includes(tag2);
  }
  return kebab(tag2) === getNameModeWriteTag(column);
}
function getColumnHeaderTags(column) {
  return usesTagMatching(column) ? column.matchTags : [];
}
function getColumnHeaderSubtitle(column) {
  var _a5;
  if (usesStatusMatching(column)) {
    return column.matchStatus ? { kind: "status", value: column.matchStatus, label: getStatusColumnLabel(column.matchStatus) } : void 0;
  }
  if (usesPriorityMatching(column)) {
    const priority = getTasksPriorityOption(column.matchPriority);
    return column.matchPriority ? {
      kind: "priority",
      value: column.matchPriority,
      label: (_a5 = priority == null ? void 0 : priority.label) != null ? _a5 : getPriorityColumnLabel(column.matchPriority),
      icon: priority == null ? void 0 : priority.emoji
    } : void 0;
  }
  return void 0;
}
function migrateColumnDefinitions(columns) {
  const usedIds = /* @__PURE__ */ new Set();
  return columns.flatMap((column) => {
    if (typeof column === "string") {
      const parsed = parseColumnSpec(column);
      return [
        {
          id: createColumnId(parsed.label, usedIds),
          label: parsed.label,
          color: parsed.color,
          matchMode: "name",
          matchTags: [],
          matchStatus: void 0,
          matchPriority: void 0,
          matchPropertySchema: void 0
        }
      ];
    }
    if (!column || typeof column !== "object") {
      return [];
    }
    const label = typeof column.label === "string" ? column.label : "";
    const idCandidate = typeof column.id === "string" ? column.id : "";
    const id = idCandidate && !usedIds.has(idCandidate) && !RESERVED_COLUMN_KEYS.has(idCandidate) ? (usedIds.add(idCandidate), idCandidate) : createColumnId(label, usedIds);
    const matchMode = column.matchMode === "tags" || column.matchMode === "status" || column.matchMode === "priority" ? column.matchMode : "name";
    const matchStatus = typeof column.matchStatus === "string" ? column.matchStatus : void 0;
    const matchPriority = typeof column.matchPriority === "string" ? column.matchPriority : void 0;
    const matchPropertySchema = column.matchPropertySchema === "dataview" /* Dataview */ || column.matchPropertySchema === "tasks" /* TasksPlugin */ ? column.matchPropertySchema : matchMode === "priority" ? "tasks" /* TasksPlugin */ : void 0;
    return [
      {
        id,
        label,
        color: typeof column.color === "string" && column.color.length > 0 ? column.color : void 0,
        matchMode,
        matchTags: normalizeMatchTags(Array.isArray(column.matchTags) ? column.matchTags : []),
        matchStatus,
        matchPriority,
        matchPropertySchema
      }
    ];
  });
}
function migrateCollapsedColumns(collapsedColumns, columns) {
  if (!collapsedColumns || collapsedColumns.length === 0) {
    return [];
  }
  const placementTagToId = /* @__PURE__ */ new Map();
  for (const column of columns) {
    placementTagToId.set(getNameModeWriteTag(column), column.id);
  }
  const migrated = /* @__PURE__ */ new Set();
  for (const value of collapsedColumns) {
    if (value === "done" || value === "uncategorised") {
      migrated.add(value);
      continue;
    }
    const matchedColumn = columns.find((column) => column.id === value);
    if (matchedColumn) {
      migrated.add(matchedColumn.id);
      continue;
    }
    const mappedId = placementTagToId.get(value);
    if (mappedId) {
      migrated.add(mappedId);
    }
  }
  return [...migrated];
}

// src/ui/columns/columns.ts
var createColumnStores = (settingsStore) => {
  const columnDefinitions = derived([settingsStore], ([settings]) => {
    var _a5;
    return (_a5 = settings.columns) != null ? _a5 : [];
  });
  const columnData = derived([columnDefinitions], ([columns]) => createColumnData(columns));
  const columnTagTable = derived([columnData], ([data]) => data.columnTagTable);
  const columnColourTable = derived([columnData], ([data]) => data.columnColourTable);
  const columnPlacementTagTable = derived([columnData], ([data]) => data.columnPlacementTagTable);
  const columnMatchTagTable = derived([columnData], ([data]) => data.columnMatchTagTable);
  const columnSubtitleTable = derived([columnData], ([data]) => data.columnSubtitleTable);
  return {
    columnDefinitions,
    columnTagTable,
    columnColourTable,
    columnPlacementTagTable,
    columnMatchTagTable,
    columnSubtitleTable
  };
};
function isColumnTag(input, columnTagTableStore) {
  return input in get2(columnTagTableStore);
}
var DEFAULT_UNCATEGORIZED_LABEL = "Uncategorized";
var DEFAULT_DONE_LABEL = "Done";
function resolveDefaultColumnName(column, uncategorizedColumnName, doneColumnName) {
  switch (column) {
    case "uncategorised":
      return uncategorizedColumnName || DEFAULT_UNCATEGORIZED_LABEL;
    case "done":
      return doneColumnName || DEFAULT_DONE_LABEL;
  }
}
var createCollapsedColumnsStore = (settingsStore) => {
  return derived([settingsStore], ([settings]) => {
    var _a5;
    return new Set((_a5 = settings.collapsedColumns) != null ? _a5 : []);
  });
};
function createColumnData(columns) {
  const columnTagTable = {};
  const columnColourTable = {};
  const columnPlacementTagTable = {};
  const columnMatchTagTable = {};
  const columnSubtitleTable = {};
  for (const column of columns) {
    if (RESERVED_COLUMN_KEYS.has(column.id)) continue;
    columnTagTable[column.id] = column.label;
    if (column.color) {
      columnColourTable[column.id] = column.color;
    }
    columnPlacementTagTable[column.id] = getColumnWriteTags(column);
    columnMatchTagTable[column.id] = getColumnHeaderTags(column);
    const subtitle = getColumnHeaderSubtitle(column);
    if (subtitle) {
      columnSubtitleTable[column.id] = subtitle;
    }
  }
  return {
    columnTagTable,
    columnColourTable,
    columnPlacementTagTable,
    columnMatchTagTable,
    columnSubtitleTable
  };
}

// src/ui/components/ColumnHeader.svelte
var import_obsidian3 = require("obsidian");

// src/ui/components/icon_button.svelte
var import_obsidian = require("obsidian");
var root = from_html(`<div></div>`);
var $$css = {
  hash: "svelte-1igl4u1",
  code: "div.svelte-1igl4u1 {width:24px;height:24px;display:flex;justify-content:center;align-items:center;border-radius:var(--radius-s);transition:background linear 100ms;cursor:pointer;background:transparent;border:none;box-shadow:none;padding:0;margin:0;}div.svelte-1igl4u1:hover {background-color:var(--background-modifier-hover);}div.svelte-1igl4u1:focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}"
};
function Icon_button($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Icon_button, ...$$anchor });
  const $$sanitized_props = legacy_rest_props($$props, ["children", "$$slots", "$$events", "$$legacy"]);
  const $$restProps = legacy_rest_props($$sanitized_props, ["icon"]);
  push($$props, false);
  append_styles($$anchor, $$css);
  let icon = prop($$props, "icon", 12);
  let element2 = mutable_source();
  function handleKeydown(e) {
    var _a5;
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      (_a5 = get(element2)) == null ? void 0 : _a5.click();
    }
  }
  legacy_pre_effect(() => (get(element2), import_obsidian.setIcon, deep_read_state(icon())), () => {
    if (get(element2)) {
      (0, import_obsidian.setIcon)(get(element2), icon());
    }
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get icon() {
      return icon();
    },
    set icon($$value) {
      icon($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root();
  attribute_effect(
    div,
    () => ({
      class: "clickable-icon",
      role: "button",
      tabindex: "0",
      ...$$restProps
    }),
    void 0,
    void 0,
    void 0,
    "svelte-1igl4u1"
  );
  bind_this(div, ($$value) => set(element2, $$value), () => get(element2));
  event("click", div, function($$arg) {
    bubble_event.call(this, $$props, $$arg);
  });
  event("keydown", div, handleKeydown);
  append($$anchor, div);
  return pop($$exports);
}

// src/ui/selection/task_selection_store.ts
var taskSelectionStore = writable(/* @__PURE__ */ new Map());
function toggleTaskSelection(taskId) {
  taskSelectionStore.update((map) => {
    const current = map.get(taskId) || false;
    map.set(taskId, !current);
    return new Map(map);
  });
}
function isTaskSelected(taskId, selectionMap) {
  return selectionMap.get(taskId) || false;
}
function getSelectedTaskCount(taskIds, selectionMap) {
  return taskIds.filter((id) => selectionMap.get(id) || false).length;
}
function clearColumnSelections(columnTaskIds) {
  taskSelectionStore.update((map) => {
    for (const id of columnTaskIds) {
      map.delete(id);
    }
    return new Map(map);
  });
}

// src/ui/selection/selection_mode_store.ts
var selectionModeStore = writable(/* @__PURE__ */ new Map());
function toggleSelectionMode(column) {
  selectionModeStore.update((map) => {
    const current = map.get(column) || false;
    const newMode = !current;
    map.set(column, newMode);
    if (current && !newMode) {
      taskSelectionStore.set(/* @__PURE__ */ new Map());
    }
    return new Map(map);
  });
}
function isInSelectionMode(column, modeMap) {
  return modeMap.get(column) || false;
}

// src/ui/components/icon.svelte
var import_obsidian2 = require("obsidian");
var root2 = from_html(`<span class="icon svelte-1cj3qcy"></span>`);
var $$css2 = {
  hash: "svelte-1cj3qcy",
  code: ".icon.svelte-1cj3qcy {display:inline-flex;justify-content:center;align-items:center;flex-shrink:0;}.icon.svelte-1cj3qcy svg {width:100%;height:100%;}"
};
function Icon($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Icon, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css2);
  let name = prop($$props, "name", 12);
  let size2 = prop(
    $$props,
    "size",
    12,
    16
    // Default icon size in pixels
  );
  let opacity = prop($$props, "opacity", 12, 1);
  let ariaLabel = prop($$props, "ariaLabel", 12, void 0);
  let element2 = mutable_source();
  onMount(() => {
    if (get(element2)) {
      (0, import_obsidian2.setIcon)(get(element2), name());
    }
  });
  legacy_pre_effect(() => (get(element2), deep_read_state(name()), import_obsidian2.setIcon), () => {
    if (get(element2) && name()) {
      (0, import_obsidian2.setIcon)(get(element2), name());
    }
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get name() {
      return name();
    },
    set name($$value) {
      name($$value);
      flushSync();
    },
    get size() {
      return size2();
    },
    set size($$value) {
      size2($$value);
      flushSync();
    },
    get opacity() {
      return opacity();
    },
    set opacity($$value) {
      opacity($$value);
      flushSync();
    },
    get ariaLabel() {
      return ariaLabel();
    },
    set ariaLabel($$value) {
      ariaLabel($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var span = root2();
  let styles;
  bind_this(span, ($$value) => set(element2, $$value), () => get(element2));
  template_effect(() => {
    var _a5, _b3;
    set_attribute2(span, "aria-label", ariaLabel());
    set_attribute2(span, "role", ariaLabel() ? "img" : void 0);
    styles = set_style(span, "", styles, {
      width: `${(_a5 = size2()) != null ? _a5 : ""}px`,
      height: `${(_b3 = size2()) != null ? _b3 : ""}px`,
      opacity: opacity()
    });
  });
  append($$anchor, span);
  return pop($$exports);
}

// src/ui/components/task_status_display.ts
function shouldRenderStatusAsText(status) {
  return status.length > 1 || /\p{Extended_Pictographic}/u.test(status);
}

// src/ui/components/TaskStatusMarker.svelte
var root3 = from_html(`<span class="status-text-marker svelte-48e5ji"> </span>`);
var root_1 = from_html(`<input type="checkbox" class="task-list-item-checkbox source-status-checkbox svelte-48e5ji" tabindex="-1" aria-hidden="true" style="pointer-events: none;"/>`);
var root_2 = from_html(`<span class="task-status-marker markdown-rendered markdown-preview-view markdown-source-view mod-cm6 svelte-48e5ji"><span><!></span></span>`);
var $$css3 = {
  hash: "svelte-48e5ji",
  code: ".task-status-marker.svelte-48e5ji {display:inline-flex !important;align-items:center;justify-content:center;width:var(--task-status-marker-size);height:var(--task-status-marker-size);min-width:var(--task-status-marker-size);min-height:var(--task-status-marker-size);overflow:visible;margin:0 !important;padding:0 !important;text-indent:0 !important;line-height:1 !important;list-style:none !important;vertical-align:middle;}.task-status-marker.svelte-48e5ji .task-list-item.HyperMD-task-line:where(.svelte-48e5ji) {display:contents !important;}.task-status-marker.svelte-48e5ji .source-status-checkbox:where(.svelte-48e5ji),\n.task-status-marker.svelte-48e5ji .status-text-marker:where(.svelte-48e5ji) {display:inline-flex !important;align-items:center !important;justify-content:center !important;box-sizing:border-box;width:var(--task-status-marker-size) !important;height:var(--task-status-marker-size) !important;min-width:var(--task-status-marker-size) !important;min-height:var(--task-status-marker-size) !important;margin:0 !important;padding:0 !important;pointer-events:none;text-indent:0 !important;line-height:1 !important;vertical-align:middle !important;}.task-status-marker.svelte-48e5ji .status-text-marker:where(.svelte-48e5ji) {font-size:calc(var(--task-status-marker-size) - 3px);}.task-status-marker.svelte-48e5ji .source-status-checkbox:where(.svelte-48e5ji) {position:relative !important;top:0 !important;left:0 !important;transform:none !important;margin:0 !important;padding:0 !important;appearance:none !important;-webkit-appearance:none !important;box-sizing:border-box !important;}"
};
function TaskStatusMarker($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: TaskStatusMarker, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css3);
  const isCustom = mutable_source();
  const markerSize = mutable_source();
  const resolvedIsChecked = mutable_source();
  let status = prop($$props, "status", 12);
  let isDone = prop($$props, "isDone", 12, false);
  let isChecked = prop($$props, "isChecked", 12, void 0);
  let size2 = prop($$props, "size", 12, 16);
  legacy_pre_effect(() => deep_read_state(status()), () => {
    set(isCustom, status() !== " ");
  });
  legacy_pre_effect(() => deep_read_state(size2()), () => {
    set(markerSize, `${size2()}px`);
  });
  legacy_pre_effect(() => (deep_read_state(isChecked()), deep_read_state(isDone())), () => {
    var _a5;
    set(resolvedIsChecked, (_a5 = isChecked()) != null ? _a5 : isDone());
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get status() {
      return status();
    },
    set status($$value) {
      status($$value);
      flushSync();
    },
    get isDone() {
      return isDone();
    },
    set isDone($$value) {
      isDone($$value);
      flushSync();
    },
    get isChecked() {
      return isChecked();
    },
    set isChecked($$value) {
      isChecked($$value);
      flushSync();
    },
    get size() {
      return size2();
    },
    set size($$value) {
      size2($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent_1 = ($$anchor2) => {
      var span = root_2();
      let styles;
      var span_1 = child(span);
      let classes;
      var node_1 = child(span_1);
      {
        var consequent = ($$anchor3) => {
          var span_2 = root3();
          var text2 = child(span_2, true);
          reset(span_2);
          template_effect(() => set_text(text2, status()));
          append($$anchor3, span_2);
        };
        var d = user_derived(() => (deep_read_state(shouldRenderStatusAsText), deep_read_state(status()), untrack(() => shouldRenderStatusAsText(status()))));
        var alternate = ($$anchor3) => {
          var input = root_1();
          remove_input_defaults(input);
          template_effect(() => {
            set_attribute2(input, "data-task", status());
            set_checked(input, get(resolvedIsChecked));
          });
          append($$anchor3, input);
        };
        if_block(node_1, ($$render) => {
          if (get(d)) $$render(consequent);
          else $$render(alternate, -1);
        });
      }
      reset(span_1);
      reset(span);
      template_effect(() => {
        styles = set_style(span, "", styles, { "--task-status-marker-size": get(markerSize) });
        classes = set_class(span_1, 1, "task-list-item HyperMD-task-line svelte-48e5ji", null, classes, { "is-checked": get(resolvedIsChecked) });
        set_attribute2(span_1, "data-task", status());
      });
      append($$anchor2, span);
    };
    var alternate_1 = ($$anchor2) => {
      {
        let $0 = derived_safe_equal(() => isDone() ? "lucide-check-square" : "lucide-square");
        let $1 = derived_safe_equal(() => isDone() ? 1 : 0.5);
        Icon($$anchor2, {
          get name() {
            return get($0);
          },
          get size() {
            return size2();
          },
          get opacity() {
            return get($1);
          }
        });
      }
    };
    if_block(node, ($$render) => {
      if (get(isCustom)) $$render(consequent_1);
      else $$render(alternate_1, -1);
    });
  }
  append($$anchor, fragment);
  return pop($$exports);
}

// src/ui/components/ColumnHeader.svelte
var root4 = from_html(`<span class="task-count svelte-1q9xxoc" aria-live="polite"> </span>`);
var root_12 = from_html(`<div class="column-match-tags svelte-1q9xxoc"> </div>`);
var root_22 = from_html(`<div class="column-match-status svelte-1q9xxoc"><span class="column-match-status-label svelte-1q9xxoc">Status</span> <span class="column-status-preview svelte-1q9xxoc"><!></span></div>`);
var root_3 = from_html(`<span class="column-priority-icon svelte-1q9xxoc" aria-hidden="true"> </span>`);
var root_4 = from_html(`<div class="column-match-priority svelte-1q9xxoc"><span class="column-match-status-label svelte-1q9xxoc">Priority</span> <span class="column-priority-preview svelte-1q9xxoc"><!> <span> </span></span></div>`);
var root_5 = from_html(`<div class="column-meta svelte-1q9xxoc"><div class="column-meta-line svelte-1q9xxoc"><!> <!> <!> <span class="task-count svelte-1q9xxoc" aria-live="polite"> </span> <div class="mode-toggle svelte-1q9xxoc" role="toolbar" aria-label="Column interaction mode"><button aria-label="Done mode: click tasks to mark complete">Done</button> <button aria-label="Select mode: click tasks to select for bulk actions">Select</button></div></div></div>`);
var root_6 = from_html(`<div class="selection-info svelte-1q9xxoc" aria-live="polite"> </div>`);
var root_7 = from_html(`<div><div class="header svelte-1q9xxoc"><span class="collapse-btn svelte-1q9xxoc" role="button" tabindex="0"> </span> <div class="column-title-group svelte-1q9xxoc"><h2 class="svelte-1q9xxoc"> </h2></div> <!> <div class="header-menu svelte-1q9xxoc"><!></div></div> <!> <!></div>`);
var $$css4 = {
  hash: "svelte-1q9xxoc",
  code: '.column-header.svelte-1q9xxoc {width:100%;--header-accent: var(--column-color, var(--background-modifier-border-hover));--column-header-x-padding: var(--column-header-x-padding-override, var(--size-4-4));--column-header-y-padding: var(--column-header-y-padding-override, var(--size-4-4));display:flex;flex-direction:column;gap:var(--size-2-3);}.column-header.svelte-1q9xxoc::before {content:"";display:block;width:calc(100% + 2 * var(--column-header-x-padding));height:12px;margin:calc(-1 * var(--column-header-y-padding)) calc(-1 * var(--column-header-x-padding)) 0;border-radius:2px;background:var(--header-accent);box-shadow:inset 0 0 0 1px color-mix(in srgb, var(--text-normal) 10%, transparent);flex:0 0 auto;}.column-header.row-header.svelte-1q9xxoc {position:relative;display:flex;align-items:stretch;margin-bottom:0;}.column-header.row-header.svelte-1q9xxoc::before {position:absolute;top:calc(-1 * var(--column-header-y-padding));bottom:calc(-1 * var(--column-header-y-padding));left:calc(-1 * var(--column-header-x-padding));width:12px;height:auto;margin:0;z-index:3;}.column-header.row-header.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) {margin:calc(-1 * var(--size-4-2)) calc(-1 * var(--size-4-3)) calc(-1 * var(--size-2-2));padding:var(--size-4-2) var(--size-4-3) var(--size-2-2);width:calc(100% + 2 * var(--size-4-3));box-sizing:border-box;position:sticky;top:var(--header-height, 0px);z-index:2;background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc),\n.column-header.row-header.svelte-1q9xxoc .selection-info:where(.svelte-1q9xxoc) {padding-left:var(--size-4-3);box-sizing:border-box;}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) {margin-top:var(--size-2-2);}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) {justify-content:flex-start;flex-wrap:wrap;gap:var(--size-2-2) var(--size-4-2);}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .column-match-tags:where(.svelte-1q9xxoc),\n.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .column-match-status:where(.svelte-1q9xxoc),\n.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .column-match-priority:where(.svelte-1q9xxoc) {order:1;flex:0 0 100%;}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .task-count:where(.svelte-1q9xxoc) {order:2;flex:0 0 100%;margin-left:0;}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .mode-toggle:where(.svelte-1q9xxoc) {order:3;flex:0 0 auto;}.column-header.collapsed.svelte-1q9xxoc {position:sticky;top:0;align-self:flex-start;z-index:1;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) {flex-direction:column;align-items:center;min-height:unset;gap:var(--size-4-2);}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .column-title-group:where(.svelte-1q9xxoc) {order:2;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .column-title-group:where(.svelte-1q9xxoc) h2:where(.svelte-1q9xxoc) {writing-mode:vertical-rl;text-orientation:mixed;white-space:nowrap;overflow:visible;text-overflow:unset;flex:0 0 auto;line-height:normal;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .task-count:where(.svelte-1q9xxoc) {order:3;writing-mode:horizontal-tb;align-self:center;line-height:normal;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .header-menu:where(.svelte-1q9xxoc) {display:flex;margin-left:0;order:4;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .header-menu button {width:20px;height:20px;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .collapse-btn:where(.svelte-1q9xxoc) {order:1;}.column-header.vertical-collapsed.row-header.svelte-1q9xxoc {margin-bottom:0;}.column-header.vertical-collapsed.row-header.svelte-1q9xxoc .header-menu:where(.svelte-1q9xxoc) {display:flex;}.header.svelte-1q9xxoc {display:flex;align-items:center;min-height:22px;width:100%;flex-shrink:0;gap:var(--size-4-2);}.header.svelte-1q9xxoc .column-title-group:where(.svelte-1q9xxoc) {min-width:0;display:flex;flex-direction:column;align-items:flex-start;gap:2px;flex:1 1 auto;}.header.svelte-1q9xxoc h2:where(.svelte-1q9xxoc) {font-size:var(--font-ui-medium);font-weight:var(--font-bold);margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.2;position:sticky;left:calc(var(--sticky-left-offset, 0px) + var(--column-header-x-padding, var(--size-4-4)));max-width:100%;}.header.svelte-1q9xxoc .task-count:where(.svelte-1q9xxoc) {font-size:var(--font-ui-small);color:var(--text-muted);white-space:nowrap;align-self:flex-start;line-height:28px;}.header.svelte-1q9xxoc .header-menu:where(.svelte-1q9xxoc) {margin-left:auto;flex-shrink:0;display:flex;align-items:center;gap:var(--size-2-1);height:24px;}.header.svelte-1q9xxoc .collapse-btn:where(.svelte-1q9xxoc) {background:transparent;border:none;box-shadow:none;cursor:pointer;color:var(--text-muted);padding:0;width:14px;height:24px;display:flex;align-items:center;justify-content:center;font-size:10px;line-height:1;flex-shrink:0;transition:color 0.15s ease;}.header.svelte-1q9xxoc .collapse-btn:where(.svelte-1q9xxoc):hover {color:var(--text-normal);background:transparent;}.header.svelte-1q9xxoc .collapse-btn:where(.svelte-1q9xxoc):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}.mode-toggle.svelte-1q9xxoc {display:flex;align-items:center;background:var(--background-modifier-form-field, var(--background-secondary));border-radius:var(--radius-s);padding:2px;gap:0;width:fit-content;max-width:100%;flex:0 0 auto;}.mode-toggle.svelte-1q9xxoc .mode-btn:where(.svelte-1q9xxoc) {font-size:var(--font-ui-smaller);padding:1px 5px;min-width:0;width:auto;border:none;background:transparent;color:var(--text-muted);border-radius:calc(var(--radius-s) - 2px);cursor:pointer;transition:background 0.15s ease, color 0.15s ease;white-space:nowrap;box-shadow:none;line-height:1.2;}.mode-toggle.svelte-1q9xxoc .mode-btn:where(.svelte-1q9xxoc):hover {background:transparent;color:var(--text-normal);box-shadow:none;}.mode-toggle.svelte-1q9xxoc .mode-btn.active:where(.svelte-1q9xxoc) {background:var(--background-primary);color:var(--text-normal);box-shadow:var(--input-shadow);font-weight:var(--font-medium);}.mode-toggle.svelte-1q9xxoc .mode-btn:where(.svelte-1q9xxoc):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:1px;}.column-meta.svelte-1q9xxoc {display:flex;flex-direction:column;gap:var(--size-2-1);width:100%;align-items:flex-start;}.column-meta.svelte-1q9xxoc .column-meta-line:where(.svelte-1q9xxoc) {display:flex;align-items:center;justify-content:space-between;width:100%;gap:var(--size-2-3);min-width:0;}.column-meta.svelte-1q9xxoc .column-meta-line:where(.svelte-1q9xxoc) .task-count:where(.svelte-1q9xxoc) {font-size:var(--font-ui-small);color:var(--text-muted);white-space:nowrap;line-height:1.3;margin-left:auto;flex:0 0 auto;}.column-match-tags.svelte-1q9xxoc,\n.column-match-status.svelte-1q9xxoc,\n.column-match-priority.svelte-1q9xxoc {font-size:var(--font-ui-small);color:var(--text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.3;min-width:0;flex:1 1 auto;}.column-match-status.svelte-1q9xxoc,\n.column-match-priority.svelte-1q9xxoc {display:inline-flex;align-items:center;gap:var(--size-2-2);flex:0 0 auto;overflow:visible;}.column-match-status-label.svelte-1q9xxoc {font-weight:var(--font-medium);}.column-priority-preview.svelte-1q9xxoc {display:inline-flex;align-items:center;gap:3px;min-width:0;}.column-priority-icon.svelte-1q9xxoc {line-height:1;}.column-status-preview.svelte-1q9xxoc {display:inline-flex !important;align-items:center !important;justify-content:center !important;width:18px !important;height:18px !important;min-width:18px !important;min-height:18px !important;max-width:18px !important;max-height:18px !important;margin:0 !important;padding:0 !important;text-indent:0 !important;line-height:1 !important;list-style:none !important;color:var(--text-normal);vertical-align:middle;}.selection-info.svelte-1q9xxoc {font-size:var(--font-ui-smaller);color:var(--text-muted);margin-top:var(--size-2-1);}'
};
function ColumnHeader($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: ColumnHeader, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css4);
  const $columnTagTableStore = () => store_get(columnTagTableStore(), "$columnTagTableStore", $$stores);
  const $columnColourTableStore = () => store_get(columnColourTableStore(), "$columnColourTableStore", $$stores);
  const $columnMatchTagTableStore = () => store_get(columnMatchTagTableStore(), "$columnMatchTagTableStore", $$stores);
  const $columnSubtitleTableStore = () => store_get(columnSubtitleTableStore(), "$columnSubtitleTableStore", $$stores);
  const $selectionModeStore = () => store_get(selectionModeStore, "$selectionModeStore", $$stores);
  const $taskSelectionStore = () => store_get(taskSelectionStore, "$taskSelectionStore", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const columnTitle = mutable_source();
  const columnColor = mutable_source();
  const columnMatchTags = mutable_source();
  const columnStatusMarker = mutable_source();
  const columnStatusLabel = mutable_source();
  const columnPriorityLabel = mutable_source();
  const columnPriorityIcon = mutable_source();
  const taskCountLabel = mutable_source();
  const collapseIcon = mutable_source();
  const isHorizontalCollapsed = mutable_source();
  const isVerticalCollapsed = mutable_source();
  const displayTaskCount = mutable_source();
  const showColumnMatchTags = mutable_source();
  const showColumnStatus = mutable_source();
  const showColumnPriority = mutable_source();
  const isSelectMode = mutable_source();
  const columnTaskIds = mutable_source();
  const selectedCount = mutable_source();
  const selectedIds = mutable_source();
  const showContextMenu = mutable_source();
  let column = prop($$props, "column", 12);
  let tasks = prop($$props, "tasks", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
  let columnColourTableStore = prop($$props, "columnColourTableStore", 12);
  let columnMatchTagTableStore = prop($$props, "columnMatchTagTableStore", 12);
  let columnSubtitleTableStore = prop($$props, "columnSubtitleTableStore", 12);
  let isVerticalFlow = prop($$props, "isVerticalFlow", 12, false);
  let isCollapsed = prop($$props, "isCollapsed", 12, false);
  let onToggleCollapse = prop($$props, "onToggleCollapse", 12);
  let uncategorizedColumnName = prop($$props, "uncategorizedColumnName", 12, void 0);
  let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
  let columnSubtitle = mutable_source();
  function getColumnTitle(col, columnTagTable) {
    switch (col) {
      case "done":
      case "uncategorised":
        return resolveDefaultColumnName(col, uncategorizedColumnName(), doneColumnName());
      default:
        return columnTagTable[col];
    }
  }
  function showMenu(e) {
    const menu = new import_obsidian3.Menu();
    if (get(isSelectMode) && get(selectedCount) > 0) {
      if (column() !== "done") {
        menu.addItem((i) => {
          i.setTitle(`Move ${get(selectedCount)} selected to ${resolveDefaultColumnName("done", uncategorizedColumnName(), doneColumnName())}`).onClick(async () => {
            for (const id of get(selectedIds)) {
              await taskActions().markDone(id);
            }
            clearColumnSelections(get(columnTaskIds));
          });
        });
      }
      for (const [tag2, label] of Object.entries($columnTagTableStore())) {
        const tagAsColumn = tag2;
        if (tagAsColumn === column()) continue;
        menu.addItem((i) => {
          i.setTitle(`Move ${get(selectedCount)} selected to ${label}`).onClick(async () => {
            for (const id of get(selectedIds)) {
              await taskActions().changeColumn(id, tagAsColumn);
            }
            clearColumnSelections(get(columnTaskIds));
          });
        });
      }
      menu.addSeparator();
      const selectedTasks = get(selectedIds).map((id) => tasks().find((t) => t.id === id)).filter(Boolean);
      const allCancelled = selectedTasks.length > 0 && selectedTasks.every((t) => t.isCancelled);
      if (allCancelled) {
        menu.addItem((i) => {
          i.setTitle(`Restore ${get(selectedCount)} selected`).onClick(async () => {
            await taskActions().restoreTasks(get(selectedIds));
            clearColumnSelections(get(columnTaskIds));
          });
        });
      } else {
        menu.addItem((i) => {
          i.setTitle(`Cancel ${get(selectedCount)} selected`).onClick(async () => {
            await taskActions().cancelTasks(get(selectedIds));
            clearColumnSelections(get(columnTaskIds));
          });
        });
      }
      menu.addSeparator();
      menu.addItem((i) => {
        i.setTitle(`Archive ${get(selectedCount)} selected`).onClick(async () => {
          await taskActions().archiveTasks(get(selectedIds));
          clearColumnSelections(get(columnTaskIds));
        });
      });
    }
    if (column() === "done") {
      menu.addItem((i) => {
        i.setTitle(`Archive all`).onClick(() => taskActions().archiveTasks(tasks().map(({ id }) => id)));
      });
    }
    menu.showAtMouseEvent(e);
  }
  legacy_pre_effect(
    () => (deep_read_state(uncategorizedColumnName()), deep_read_state(doneColumnName()), deep_read_state(column()), $columnTagTableStore()),
    () => {
      set(columnTitle, (() => {
        void uncategorizedColumnName();
        void doneColumnName();
        return getColumnTitle(column(), $columnTagTableStore());
      })());
    }
  );
  legacy_pre_effect(
    () => (isColumnTag, deep_read_state(column()), deep_read_state(columnTagTableStore()), $columnColourTableStore()),
    () => {
      set(columnColor, isColumnTag(column(), columnTagTableStore()) ? $columnColourTableStore()[column()] : void 0);
    }
  );
  legacy_pre_effect(
    () => (isColumnTag, deep_read_state(column()), deep_read_state(columnTagTableStore()), $columnMatchTagTableStore()),
    () => {
      var _a5;
      set(columnMatchTags, isColumnTag(column(), columnTagTableStore()) ? (_a5 = $columnMatchTagTableStore()[column()]) != null ? _a5 : [] : []);
    }
  );
  legacy_pre_effect(
    () => (isColumnTag, deep_read_state(column()), deep_read_state(columnTagTableStore()), $columnSubtitleTableStore()),
    () => {
      set(columnSubtitle, isColumnTag(column(), columnTagTableStore()) ? $columnSubtitleTableStore()[column()] : void 0);
    }
  );
  legacy_pre_effect(() => get(columnSubtitle), () => {
    var _a5;
    set(columnStatusMarker, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "status" ? get(columnSubtitle).value : void 0);
  });
  legacy_pre_effect(() => get(columnSubtitle), () => {
    var _a5;
    set(columnStatusLabel, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "status" ? get(columnSubtitle).label : "");
  });
  legacy_pre_effect(() => get(columnSubtitle), () => {
    var _a5;
    set(columnPriorityLabel, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "priority" ? get(columnSubtitle).label : "");
  });
  legacy_pre_effect(() => get(columnSubtitle), () => {
    var _a5;
    set(columnPriorityIcon, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "priority" ? get(columnSubtitle).icon : void 0);
  });
  legacy_pre_effect(() => deep_read_state(tasks()), () => {
    set(taskCountLabel, tasks().length === 1 ? "1 task" : `${tasks().length} tasks`);
  });
  legacy_pre_effect(() => deep_read_state(isCollapsed()), () => {
    set(collapseIcon, isCollapsed() ? "\u25B6" : "\u25BC");
  });
  legacy_pre_effect(
    () => (deep_read_state(isCollapsed()), deep_read_state(isVerticalFlow())),
    () => {
      set(isHorizontalCollapsed, isCollapsed() && !isVerticalFlow());
    }
  );
  legacy_pre_effect(
    () => (deep_read_state(isCollapsed()), deep_read_state(isVerticalFlow())),
    () => {
      set(isVerticalCollapsed, isCollapsed() && isVerticalFlow());
    }
  );
  legacy_pre_effect(
    () => (deep_read_state(isCollapsed()), deep_read_state(tasks()), get(taskCountLabel)),
    () => {
      set(displayTaskCount, isCollapsed() ? `${tasks().length}` : get(taskCountLabel));
    }
  );
  legacy_pre_effect(() => (get(columnMatchTags), deep_read_state(isCollapsed())), () => {
    set(showColumnMatchTags, get(columnMatchTags).length > 0 && !isCollapsed());
  });
  legacy_pre_effect(() => (get(columnStatusMarker), deep_read_state(isCollapsed())), () => {
    set(showColumnStatus, get(columnStatusMarker) !== void 0 && !isCollapsed());
  });
  legacy_pre_effect(() => (get(columnSubtitle), deep_read_state(isCollapsed())), () => {
    var _a5;
    set(showColumnPriority, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "priority" && !isCollapsed());
  });
  legacy_pre_effect(
    () => (isInSelectionMode, deep_read_state(column()), $selectionModeStore()),
    () => {
      set(isSelectMode, isInSelectionMode(column(), $selectionModeStore()));
    }
  );
  legacy_pre_effect(() => deep_read_state(tasks()), () => {
    set(columnTaskIds, tasks().map((t) => t.id));
  });
  legacy_pre_effect(
    () => (getSelectedTaskCount, get(columnTaskIds), $taskSelectionStore()),
    () => {
      set(selectedCount, getSelectedTaskCount(get(columnTaskIds), $taskSelectionStore()));
    }
  );
  legacy_pre_effect(() => (get(columnTaskIds), isTaskSelected, $taskSelectionStore()), () => {
    set(selectedIds, get(columnTaskIds).filter((id) => isTaskSelected(id, $taskSelectionStore())));
  });
  legacy_pre_effect(
    () => (deep_read_state(column()), get(isSelectMode), get(selectedCount)),
    () => {
      set(showContextMenu, column() === "done" || get(isSelectMode) && get(selectedCount) > 0);
    }
  );
  legacy_pre_effect_reset();
  var $$exports = {
    get column() {
      return column();
    },
    set column($$value) {
      column($$value);
      flushSync();
    },
    get tasks() {
      return tasks();
    },
    set tasks($$value) {
      tasks($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get columnTagTableStore() {
      return columnTagTableStore();
    },
    set columnTagTableStore($$value) {
      columnTagTableStore($$value);
      flushSync();
    },
    get columnColourTableStore() {
      return columnColourTableStore();
    },
    set columnColourTableStore($$value) {
      columnColourTableStore($$value);
      flushSync();
    },
    get columnMatchTagTableStore() {
      return columnMatchTagTableStore();
    },
    set columnMatchTagTableStore($$value) {
      columnMatchTagTableStore($$value);
      flushSync();
    },
    get columnSubtitleTableStore() {
      return columnSubtitleTableStore();
    },
    set columnSubtitleTableStore($$value) {
      columnSubtitleTableStore($$value);
      flushSync();
    },
    get isVerticalFlow() {
      return isVerticalFlow();
    },
    set isVerticalFlow($$value) {
      isVerticalFlow($$value);
      flushSync();
    },
    get isCollapsed() {
      return isCollapsed();
    },
    set isCollapsed($$value) {
      isCollapsed($$value);
      flushSync();
    },
    get onToggleCollapse() {
      return onToggleCollapse();
    },
    set onToggleCollapse($$value) {
      onToggleCollapse($$value);
      flushSync();
    },
    get uncategorizedColumnName() {
      return uncategorizedColumnName();
    },
    set uncategorizedColumnName($$value) {
      uncategorizedColumnName($$value);
      flushSync();
    },
    get doneColumnName() {
      return doneColumnName();
    },
    set doneColumnName($$value) {
      doneColumnName($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root_7();
  let classes;
  let styles;
  var div_1 = child(div);
  var span = child(div_1);
  var text2 = child(span, true);
  reset(span);
  var div_2 = sibling(span, 2);
  var h2 = child(div_2);
  var text_1 = child(h2, true);
  reset(h2);
  reset(div_2);
  var node = sibling(div_2, 2);
  {
    var consequent = ($$anchor2) => {
      var span_1 = root4();
      var text_2 = child(span_1, true);
      reset(span_1);
      template_effect(() => {
        set_attribute2(span_1, "aria-label", get(taskCountLabel));
        set_text(text_2, get(displayTaskCount));
      });
      append($$anchor2, span_1);
    };
    if_block(node, ($$render) => {
      if (isCollapsed()) $$render(consequent);
    });
  }
  var div_3 = sibling(node, 2);
  var node_1 = child(div_3);
  {
    var consequent_1 = ($$anchor2) => {
      Icon_button($$anchor2, {
        icon: "lucide-more-vertical",
        get "aria-label"() {
          var _a5;
          return `Column options for ${(_a5 = get(columnTitle)) != null ? _a5 : ""}`;
        },
        $$events: { click: showMenu }
      });
    };
    if_block(node_1, ($$render) => {
      if (get(showContextMenu)) $$render(consequent_1);
    });
  }
  reset(div_3);
  reset(div_1);
  var node_2 = sibling(div_1, 2);
  {
    var consequent_6 = ($$anchor2) => {
      var div_4 = root_5();
      var div_5 = child(div_4);
      var node_3 = child(div_5);
      {
        var consequent_2 = ($$anchor3) => {
          var div_6 = root_12();
          var text_3 = child(div_6, true);
          reset(div_6);
          template_effect(
            ($0, $1) => {
              set_attribute2(div_6, "title", $0);
              set_text(text_3, $1);
            },
            [
              () => (get(columnMatchTags), untrack(() => get(columnMatchTags).map((tag2) => `#${tag2}`).join(" "))),
              () => (get(columnMatchTags), untrack(() => get(columnMatchTags).map((tag2) => `#${tag2}`).join(" ")))
            ]
          );
          append($$anchor3, div_6);
        };
        if_block(node_3, ($$render) => {
          if (get(showColumnMatchTags)) $$render(consequent_2);
        });
      }
      var node_4 = sibling(node_3, 2);
      {
        var consequent_3 = ($$anchor3) => {
          var div_7 = root_22();
          var span_2 = sibling(child(div_7), 2);
          var node_5 = child(span_2);
          {
            let $0 = derived_safe_equal(() => {
              var _a5;
              return (_a5 = get(columnStatusMarker)) != null ? _a5 : " ";
            });
            TaskStatusMarker(node_5, {
              get status() {
                return get($0);
              },
              size: 18
            });
          }
          reset(span_2);
          reset(div_7);
          template_effect(() => {
            var _a5, _b3;
            set_attribute2(div_7, "title", `Status: ${(_a5 = get(columnStatusLabel)) != null ? _a5 : ""}`);
            set_attribute2(span_2, "aria-label", `Status: ${(_b3 = get(columnStatusLabel)) != null ? _b3 : ""}`);
          });
          append($$anchor3, div_7);
        };
        if_block(node_4, ($$render) => {
          if (get(showColumnStatus)) $$render(consequent_3);
        });
      }
      var node_6 = sibling(node_4, 2);
      {
        var consequent_5 = ($$anchor3) => {
          var div_8 = root_4();
          var span_3 = sibling(child(div_8), 2);
          var node_7 = child(span_3);
          {
            var consequent_4 = ($$anchor4) => {
              var span_4 = root_3();
              var text_4 = child(span_4, true);
              reset(span_4);
              template_effect(() => set_text(text_4, get(columnPriorityIcon)));
              append($$anchor4, span_4);
            };
            if_block(node_7, ($$render) => {
              if (get(columnPriorityIcon)) $$render(consequent_4);
            });
          }
          var span_5 = sibling(node_7, 2);
          var text_5 = child(span_5, true);
          reset(span_5);
          reset(span_3);
          reset(div_8);
          template_effect(() => {
            var _a5, _b3;
            set_attribute2(div_8, "title", `Priority: ${(_a5 = get(columnPriorityLabel)) != null ? _a5 : ""}`);
            set_attribute2(span_3, "aria-label", `Priority: ${(_b3 = get(columnPriorityLabel)) != null ? _b3 : ""}`);
            set_text(text_5, get(columnPriorityLabel));
          });
          append($$anchor3, div_8);
        };
        if_block(node_6, ($$render) => {
          if (get(showColumnPriority)) $$render(consequent_5);
        });
      }
      var span_6 = sibling(node_6, 2);
      var text_6 = child(span_6, true);
      reset(span_6);
      var div_9 = sibling(span_6, 2);
      var button = child(div_9);
      let classes_1;
      var button_1 = sibling(button, 2);
      let classes_2;
      reset(div_9);
      reset(div_5);
      reset(div_4);
      template_effect(() => {
        set_attribute2(span_6, "aria-label", get(taskCountLabel));
        set_text(text_6, get(displayTaskCount));
        classes_1 = set_class(button, 1, "mode-btn svelte-1q9xxoc", null, classes_1, { active: !get(isSelectMode) });
        set_attribute2(button, "aria-pressed", !get(isSelectMode));
        classes_2 = set_class(button_1, 1, "mode-btn svelte-1q9xxoc", null, classes_2, { active: get(isSelectMode) });
        set_attribute2(button_1, "aria-pressed", get(isSelectMode));
      });
      event("click", button, () => {
        if (get(isSelectMode)) toggleSelectionMode(column());
      });
      event("click", button_1, () => {
        if (!get(isSelectMode)) toggleSelectionMode(column());
      });
      append($$anchor2, div_4);
    };
    if_block(node_2, ($$render) => {
      if (!isCollapsed()) $$render(consequent_6);
    });
  }
  var node_8 = sibling(node_2, 2);
  {
    var consequent_7 = ($$anchor2) => {
      var div_10 = root_6();
      var text_7 = child(div_10);
      reset(div_10);
      template_effect(() => {
        var _a5;
        return set_text(text_7, `${(_a5 = get(selectedCount)) != null ? _a5 : ""} selected`);
      });
      append($$anchor2, div_10);
    };
    if_block(node_8, ($$render) => {
      if (get(isSelectMode) && get(selectedCount) > 0) $$render(consequent_7);
    });
  }
  reset(div);
  template_effect(() => {
    var _a5, _b3;
    classes = set_class(div, 1, "column-header svelte-1q9xxoc", null, classes, {
      "row-header": isVerticalFlow(),
      collapsed: get(isHorizontalCollapsed),
      "vertical-collapsed": get(isVerticalCollapsed)
    });
    styles = set_style(div, "", styles, { "--column-color": get(columnColor) });
    set_attribute2(span, "aria-expanded", !isCollapsed());
    set_attribute2(span, "aria-label", `${isCollapsed() ? "Expand" : "Collapse"} ${(_a5 = get(columnTitle)) != null ? _a5 : ""} column`);
    set_text(text2, get(collapseIcon));
    set_attribute2(h2, "id", `column-title-${(_b3 = column()) != null ? _b3 : ""}`);
    set_attribute2(h2, "title", get(columnTitle));
    set_text(text_1, get(columnTitle));
  });
  event("click", span, function(...$$args) {
    var _a5;
    (_a5 = onToggleCollapse()) == null ? void 0 : _a5.apply(this, $$args);
  });
  event("keydown", span, (e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      onToggleCollapse()();
    }
  });
  append($$anchor, div);
  var $$pop = pop($$exports);
  $$cleanup();
  return $$pop;
}

// src/ui/board/BoardCell.svelte
var import_obsidian7 = require("obsidian");

// src/ui/board/cell_creation.ts
function deriveCellCreationMetadata(secondaryAxisBucket) {
  var _a5, _b3, _c2;
  const value = (_a5 = secondaryAxisBucket.meta) == null ? void 0 : _a5.value;
  switch ((_c2 = (_b3 = secondaryAxisBucket.meta) == null ? void 0 : _b3.source) == null ? void 0 : _c2.kind) {
    case "file":
      return {
        targetFilePath: typeof value === "string" ? value : null,
        additionalTags: []
      };
    case "tag-prefix":
      return {
        targetFilePath: null,
        additionalTags: typeof value === "string" ? [value] : []
      };
    case "none":
    default:
      return {
        targetFilePath: null,
        additionalTags: []
      };
  }
}

// src/ui/dnd/store.ts
var isDraggingStore = writable(null);
var subtaskDraggingStore = writable(null);

// src/ui/tasks/source_block.ts
function parseSourceTaskLine(input) {
  const match = input.match(sourceTaskLineRegex);
  if (!match) {
    return null;
  }
  const [, indentation, bullet, status, content] = match;
  if (indentation == null || bullet == null || status == null || content == null) {
    return null;
  }
  return { indentation, bullet, status, content };
}
function getSourceNodeText(node) {
  return node.kind === "task" ? node.content : node.rawLine.slice(node.indentation.length);
}
function getRawListItemText(node) {
  var _a5;
  const match = node.rawLine.slice(node.indentation.length).match(/^[-*+]\s+(.+)$/);
  return (_a5 = match == null ? void 0 : match[1]) != null ? _a5 : null;
}
function getVisibleSourceTaskDescendants(nodes) {
  return flattenSourceBlockNodes(nodes).filter(
    (node) => node.kind === "task" && node.taskVisibility === "visible"
  );
}
function flattenSourceBlockNodes(nodes) {
  return nodes.flatMap((node) => [
    node,
    ...flattenSourceBlockNodes(node.sourceChildren)
  ]);
}
var sourceTaskLineRegex = /^(\s*)([-*+])\s\[([^\[\]]*)\]\s(.+)/;

// src/ui/components/TaskLineRow.svelte
var root5 = from_html(`<div class="task-line-actions svelte-1y3uj64"><!></div>`);
var root_13 = from_html(`<div><div class="task-line-marker svelte-1y3uj64"><!></div> <div class="task-line-content svelte-1y3uj64"><!></div> <!></div>`);
var $$css5 = {
  hash: "svelte-1y3uj64",
  code: ".task-line-row.svelte-1y3uj64 {--task-line-base-padding-left: calc(var(--size-4-2) + 8px);--task-line-indent-step: 1.65rem;--task-line-marker-size: 20px;--task-line-row-height: 1.3em;--task-line-column-gap: var(--size-2-2);--task-line-block-padding: 0 var(--size-4-2) var(--size-2-1)\n  	calc(\n  		var(--task-line-base-padding-left) +\n  			(var(--task-line-depth) * var(--task-line-indent-step))\n  	);display:grid;grid-template-columns:var(--task-line-marker-size) minmax(0, 1fr);column-gap:var(--task-line-column-gap);align-items:start;padding:var(--task-line-block-padding);}.task-line-row.has-actions.svelte-1y3uj64 {grid-template-columns:var(--task-line-marker-size) minmax(0, 1fr) auto;}.task-line-row.card-variant.svelte-1y3uj64 {--task-line-column-gap: var(--size-2-3);--task-line-row-height: var(--task-content-line-height, 1.5rem);--task-line-block-padding: var(--size-4-2) var(--size-4-2)\n  	var(--size-4-2)\n  	calc(\n  		var(--task-line-base-padding-left) +\n  			(var(--task-line-depth) * var(--task-line-indent-step))\n  	);}.task-line-marker.svelte-1y3uj64,\n.task-line-actions.svelte-1y3uj64 {display:flex;align-items:center;justify-content:center;min-width:0;height:var(--task-line-row-height);}.task-line-content.svelte-1y3uj64 {display:block;min-width:0;min-height:var(--task-line-row-height);}.task-line-actions.svelte-1y3uj64 {justify-content:flex-end;}"
};
function TaskLineRow($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: TaskLineRow, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css5);
  let depth = prop($$props, "depth", 12, 0);
  let hasActions = prop($$props, "hasActions", 12, false);
  let variant = prop($$props, "variant", 12, "source");
  var $$exports = {
    get depth() {
      return depth();
    },
    set depth($$value) {
      depth($$value);
      flushSync();
    },
    get hasActions() {
      return hasActions();
    },
    set hasActions($$value) {
      hasActions($$value);
      flushSync();
    },
    get variant() {
      return variant();
    },
    set variant($$value) {
      variant($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  var div = root_13();
  let classes;
  let styles;
  var div_1 = child(div);
  var node = child(div_1);
  slot(node, $$props, "marker", {}, null);
  reset(div_1);
  var div_2 = sibling(div_1, 2);
  var node_1 = child(div_2);
  slot(node_1, $$props, "default", {}, null);
  reset(div_2);
  var node_2 = sibling(div_2, 2);
  {
    var consequent = ($$anchor2) => {
      var div_3 = root5();
      var node_3 = child(div_3);
      slot(node_3, $$props, "actions", {}, null);
      reset(div_3);
      append($$anchor2, div_3);
    };
    if_block(node_2, ($$render) => {
      if (hasActions()) $$render(consequent);
    });
  }
  reset(div);
  template_effect(() => {
    classes = set_class(div, 1, "task-line-row svelte-1y3uj64", null, classes, {
      "has-actions": hasActions(),
      "card-variant": variant() === "card"
    });
    styles = set_style(div, "", styles, { "--task-line-depth": depth() });
  });
  append($$anchor, div);
  return pop($$exports);
}

// src/ui/components/TaskSourceRow.svelte
var import_obsidian4 = require("obsidian");

// src/ui/components/TaskSourceStatusButton.svelte
var root6 = from_html(`<button role="checkbox" aria-label="Advance subtask status"><!></button>`);
var $$css6 = {
  hash: "svelte-74sw79",
  code: ".icon-button.source-row-status.svelte-74sw79 {display:flex;justify-content:center;align-items:center;width:20px;height:20px;padding:0;border:none;background:transparent;cursor:pointer;border-radius:var(--radius-s);box-shadow:none;overflow:visible;}.icon-button.source-row-status.svelte-74sw79:hover, .icon-button.source-row-status.svelte-74sw79:active {background:transparent;box-shadow:none;}.icon-button.source-row-status.svelte-74sw79:disabled {cursor:default;opacity:0.35;}.icon-button.source-row-status.usesStatusMarker.svelte-74sw79 {color:var(--text-normal);}.icon-button.source-row-status.is-done.svelte-74sw79 svg {color:var(--interactive-accent);}"
};
function TaskSourceStatusButton($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: TaskSourceStatusButton, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css6);
  const isDone = mutable_source();
  const isIgnored = mutable_source();
  const isChecked = mutable_source();
  const displayStatusIsCustom = mutable_source();
  let task = prop($$props, "task", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let node = prop($$props, "node", 12);
  let isSelectionMode = prop($$props, "isSelectionMode", 12, false);
  function toggleStatus() {
    void taskActions().toggleSourceTaskStatus(task().id, node().rowIndex);
  }
  function handleKeydown(e) {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      toggleStatus();
    }
  }
  legacy_pre_effect(() => (deep_read_state(task()), deep_read_state(node())), () => {
    set(isDone, task().isSourceTaskStatusDone(node().status));
  });
  legacy_pre_effect(() => deep_read_state(node()), () => {
    set(isIgnored, node().taskVisibility === "ignored");
  });
  legacy_pre_effect(() => (get(isDone), get(isIgnored)), () => {
    set(isChecked, get(isDone) || get(isIgnored));
  });
  legacy_pre_effect(() => deep_read_state(node()), () => {
    set(displayStatusIsCustom, node().status !== " ");
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get task() {
      return task();
    },
    set task($$value) {
      task($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get node() {
      return node();
    },
    set node($$value) {
      node($$value);
      flushSync();
    },
    get isSelectionMode() {
      return isSelectionMode();
    },
    set isSelectionMode($$value) {
      isSelectionMode($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var button = root6();
  let classes;
  var node_1 = child(button);
  TaskStatusMarker(node_1, {
    get status() {
      return deep_read_state(node()), untrack(() => node().status);
    },
    get isDone() {
      return get(isDone);
    },
    size: 16
  });
  reset(button);
  template_effect(() => {
    classes = set_class(button, 1, "icon-button source-row-status svelte-74sw79", null, classes, {
      "is-done": get(isDone),
      usesStatusMarker: get(displayStatusIsCustom)
    });
    set_attribute2(button, "aria-checked", get(isChecked));
    button.disabled = isSelectionMode();
    set_attribute2(button, "tabindex", isSelectionMode() ? -1 : 0);
  });
  event("click", button, stopPropagation(toggleStatus));
  event("keydown", button, stopPropagation(handleKeydown));
  append($$anchor, button);
  return pop($$exports);
}

// src/ui/components/TaskSourceRow.svelte
var root7 = from_html(`<textarea class="svelte-smkg1f"></textarea>`);
var root_14 = from_html(`<button type="button" class="source-row-preview svelte-smkg1f"> </button>`);
var root_23 = from_html(`<span class="source-row-bullet svelte-smkg1f" aria-hidden="true"></span>`);
var root_32 = from_html(`<button type="button" class="delete-subtask-btn svelte-smkg1f" aria-label="Delete subtask" title="Delete subtask"><!></button>`);
var root_42 = from_html(`<div><!> <!></div>`);
var $$css7 = {
  hash: "svelte-smkg1f",
  code: '.source-row.svelte-smkg1f {--source-row-line-height: 1.3;position:relative;}.source-row.is-dragging.svelte-smkg1f {opacity:0.4;}.source-row.drop-before.svelte-smkg1f::before, .source-row.drop-after.svelte-smkg1f::before {content:"";position:absolute;left:calc(var(--task-line-base-padding-left, 20px) + var(--drag-indicator-depth, 0) * var(--task-line-indent-step, 26px));right:8px;height:2px;background:var(--interactive-accent);pointer-events:none;}.source-row.drop-before.svelte-smkg1f::after, .source-row.drop-after.svelte-smkg1f::after {content:"";position:absolute;left:calc(var(--task-line-base-padding-left, 20px) + var(--drag-indicator-depth, 0) * var(--task-line-indent-step, 26px) - 8px);width:10px;height:10px;border-radius:999px;background:var(--interactive-accent);pointer-events:none;}.source-row.drop-before.svelte-smkg1f::before {top:-1px;}.source-row.drop-before.svelte-smkg1f::after {top:-5px;}.source-row.drop-after.svelte-smkg1f::before {bottom:-1px;}.source-row.drop-after.svelte-smkg1f::after {bottom:-5px;}.delete-subtask-btn.svelte-smkg1f {display:flex;justify-content:center;align-items:center;width:20px;height:20px;padding:0;border:none;background:transparent;cursor:pointer;color:var(--text-muted);opacity:0;transition:opacity 0.15s ease, color 0.15s ease;box-shadow:none;}.delete-subtask-btn.svelte-smkg1f:hover {color:var(--text-error, var(--text-accent));background:transparent;box-shadow:none;}.source-row.svelte-smkg1f:hover .delete-subtask-btn:where(.svelte-smkg1f) {opacity:0.8;}.delete-subtask-btn.svelte-smkg1f:hover {opacity:1 !important;}.source-row-preview.svelte-smkg1f {display:block;width:100%;height:auto;min-height:var(--task-line-row-height, 1.5rem);appearance:none;padding:0;border:none;background:transparent;box-shadow:none;color:var(--text-normal);font:inherit;line-height:var(--source-row-line-height);text-align:left;white-space:pre-wrap;overflow-wrap:anywhere;cursor:text;}.source-row-preview.svelte-smkg1f:hover, .source-row-preview.svelte-smkg1f:active {background:transparent;box-shadow:none;}.source-row-preview.svelte-smkg1f:focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}textarea.svelte-smkg1f {cursor:text;background-color:var(--color-base-25);width:100%;min-height:1.6rem;resize:none;}.source-row-bullet.svelte-smkg1f {display:block;width:8px;height:8px;border-radius:50%;background:var(--text-muted);}.is-ignored-task.svelte-smkg1f .source-row-preview:where(.svelte-smkg1f) {color:var(--text-normal);}'
};
function TaskSourceRow($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: TaskSourceRow, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css7);
  const $subtaskDraggingStore = () => store_get(subtaskDraggingStore, "$subtaskDraggingStore", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const rawListItemText = mutable_source();
  const editText = mutable_source();
  const previewText = mutable_source();
  let app = prop($$props, "app", 12);
  let task = prop($$props, "task", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let node = prop($$props, "node", 12);
  let isSelectionMode = prop($$props, "isSelectionMode", 12, false);
  let depth = prop($$props, "depth", 12, 0);
  let isEditing = mutable_source(false);
  let isDragging = mutable_source(false);
  let isDraggedOver = mutable_source(false);
  let dropBefore = mutable_source(false);
  let dropAfter = mutable_source(false);
  let dragIndicatorDepth = mutable_source(depth());
  function startEditing() {
    set(isEditing, true);
  }
  function finishEditing(e) {
    const next2 = e.currentTarget.value;
    set(isEditing, false);
    if (next2 !== get(editText)) {
      void taskActions().updateSourceBlockRow(task().id, node().rowIndex, next2);
    }
  }
  function handleTextareaKeydown(e) {
    var _a5;
    if (e.key === "Enter" && !e.shiftKey || e.key === "Escape") {
      e.preventDefault();
      (_a5 = e.currentTarget) == null ? void 0 : _a5.blur();
      if (e.key === "Escape") {
        set(isEditing, false);
      }
    }
  }
  function handlePreviewKeydown(e) {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      startEditing();
    }
  }
  function focusAndAutosize(node2) {
    function resize() {
      node2.style.height = "0px";
      node2.style.height = `${node2.scrollHeight}px`;
    }
    const focusTimer = setTimeout(() => node2.focus(), 0);
    node2.addEventListener("input", resize);
    resize();
    return {
      destroy() {
        clearTimeout(focusTimer);
        node2.removeEventListener("input", resize);
      }
    };
  }
  class ConfirmDeleteSubtaskModal extends import_obsidian4.Modal {
    constructor(app2, subtaskText, onConfirm) {
      super(app2);
      this.subtaskText = subtaskText;
      this.onConfirm = onConfirm;
    }
    onOpen() {
      this.contentEl.addClass("task-list-kanban-confirm-modal");
      this.contentEl.createEl("h2", { text: "Delete subtask?" });
      this.contentEl.createEl("p", {
        text: `Are you sure you want to delete "${this.subtaskText}" and all its nested items? This action cannot be undone.`
      });
      const actions = this.contentEl.createDiv({ cls: "confirm-modal-actions" });
      const cancelButton = actions.createEl("button", { text: "Cancel" });
      cancelButton.addEventListener("click", () => this.close());
      const deleteButton = actions.createEl("button", { text: "Delete", cls: "mod-warning" });
      deleteButton.addEventListener("click", () => {
        this.onConfirm();
        this.close();
      });
      window.requestAnimationFrame(() => cancelButton.focus());
    }
    onClose() {
      this.contentEl.empty();
    }
  }
  function handleDeleteClick() {
    const text2 = node().kind === "task" ? node().content : node().rawLine.trim();
    new ConfirmDeleteSubtaskModal(app(), text2, () => {
      void taskActions().deleteSourceBlockRow(task().id, node().rowIndex);
    }).open();
  }
  function handleDragStart(e) {
    e.stopPropagation();
    set(isDragging, true);
    subtaskDraggingStore.set({
      taskId: task().id,
      draggedRowIndex: node().rowIndex,
      draggedIndentation: node().indentation
    });
    if (e.dataTransfer) {
      e.dataTransfer.setData("text/plain", `${task().id}:${node().rowIndex}`);
      e.dataTransfer.dropEffect = "move";
    }
  }
  function handleDragEnd(e) {
    e.stopPropagation();
    set(isDragging, false);
    subtaskDraggingStore.set(null);
  }
  function handleDragOver(e) {
    if (!$subtaskDraggingStore() || $subtaskDraggingStore().taskId !== task().id) return;
    if ($subtaskDraggingStore().draggedRowIndex === node().rowIndex) return;
    e.preventDefault();
    e.stopPropagation();
    set(isDraggedOver, true);
    const rect = e.currentTarget.getBoundingClientRect();
    const relativeY = e.clientY - rect.top;
    set(dropBefore, relativeY < rect.height / 2);
    set(dropAfter, !get(dropBefore));
    const mouseX = e.clientX - rect.left;
    const hoveredRowDepth = depth();
    const maxDepth = get(dropBefore) ? hoveredRowDepth : hoveredRowDepth + 1;
    set(dragIndicatorDepth, Math.min(maxDepth, Math.max(1, Math.floor((mouseX - 20) / 26))));
  }
  function handleDragLeave(e) {
    e.stopPropagation();
    set(isDraggedOver, false);
    set(dropBefore, false);
    set(dropAfter, false);
  }
  function handleDrop(e) {
    if (!$subtaskDraggingStore() || $subtaskDraggingStore().taskId !== task().id) return;
    e.preventDefault();
    e.stopPropagation();
    set(isDraggedOver, false);
    const draggedRowIndex = $subtaskDraggingStore().draggedRowIndex;
    subtaskDraggingStore.set(null);
    const position = get(dropBefore) ? "before" : "after";
    void taskActions().moveSourceBlockRow(task().id, draggedRowIndex, node().rowIndex, position, get(dragIndicatorDepth));
    set(dropBefore, false);
    set(dropAfter, false);
  }
  legacy_pre_effect(() => (deep_read_state(node()), getRawListItemText), () => {
    set(rawListItemText, node().kind === "raw" ? getRawListItemText(node()) : null);
  });
  legacy_pre_effect(
    () => (get(rawListItemText), getSourceNodeText, deep_read_state(node())),
    () => {
      var _a5;
      set(editText, ((_a5 = get(rawListItemText)) != null ? _a5 : getSourceNodeText(node())).replaceAll("<br />", "\n"));
    }
  );
  legacy_pre_effect(() => (get(rawListItemText), get(editText)), () => {
    var _a5;
    set(previewText, ((_a5 = get(rawListItemText)) != null ? _a5 : get(editText)).replaceAll("<br />", "\n"));
  });
  legacy_pre_effect(() => $subtaskDraggingStore(), () => {
    if (!$subtaskDraggingStore()) {
      set(isDraggedOver, false);
      set(dropBefore, false);
      set(dropAfter, false);
    }
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get app() {
      return app();
    },
    set app($$value) {
      app($$value);
      flushSync();
    },
    get task() {
      return task();
    },
    set task($$value) {
      task($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get node() {
      return node();
    },
    set node($$value) {
      node($$value);
      flushSync();
    },
    get isSelectionMode() {
      return isSelectionMode();
    },
    set isSelectionMode($$value) {
      isSelectionMode($$value);
      flushSync();
    },
    get depth() {
      return depth();
    },
    set depth($$value) {
      depth($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root_42();
  let classes;
  let styles;
  var node_1 = child(div);
  TaskLineRow(node_1, {
    get depth() {
      return depth();
    },
    hasActions: true,
    children: ($$anchor2, $$slotProps) => {
      var fragment = comment();
      var node_2 = first_child(fragment);
      {
        var consequent = ($$anchor3) => {
          var textarea = root7();
          remove_textarea_child(textarea);
          action(textarea, ($$node) => focusAndAutosize == null ? void 0 : focusAndAutosize($$node));
          effect(() => event("keydown", textarea, handleTextareaKeydown));
          effect(() => event("blur", textarea, finishEditing));
          template_effect(() => set_value(textarea, get(editText)));
          append($$anchor3, textarea);
        };
        var alternate = ($$anchor3) => {
          var button = root_14();
          var text_1 = child(button, true);
          reset(button);
          template_effect(() => set_text(text_1, get(previewText)));
          event("click", button, stopPropagation(startEditing));
          event("keydown", button, stopPropagation(handlePreviewKeydown));
          append($$anchor3, button);
        };
        if_block(node_2, ($$render) => {
          if (get(isEditing)) $$render(consequent);
          else $$render(alternate, -1);
        });
      }
      append($$anchor2, fragment);
    },
    $$slots: {
      default: true,
      marker: ($$anchor2, $$slotProps) => {
        var fragment_1 = comment();
        var node_3 = first_child(fragment_1);
        {
          var consequent_1 = ($$anchor3) => {
            TaskSourceStatusButton($$anchor3, {
              get task() {
                return task();
              },
              get taskActions() {
                return taskActions();
              },
              get node() {
                return node();
              },
              get isSelectionMode() {
                return isSelectionMode();
              }
            });
          };
          var consequent_2 = ($$anchor3) => {
            var span = root_23();
            append($$anchor3, span);
          };
          if_block(node_3, ($$render) => {
            if (deep_read_state(node()), untrack(() => node().kind === "task")) $$render(consequent_1);
            else if (get(rawListItemText) !== null) $$render(consequent_2, 1);
          });
        }
        append($$anchor2, fragment_1);
      },
      actions: ($$anchor2, $$slotProps) => {
        var fragment_3 = comment();
        var node_4 = first_child(fragment_3);
        {
          var consequent_3 = ($$anchor3) => {
            var button_1 = root_32();
            var node_5 = child(button_1);
            Icon(node_5, { name: "lucide-x", size: 14, opacity: 0.6 });
            reset(button_1);
            event("click", button_1, stopPropagation(handleDeleteClick));
            append($$anchor3, button_1);
          };
          if_block(node_4, ($$render) => {
            if (!isSelectionMode()) $$render(consequent_3);
          });
        }
        append($$anchor2, fragment_3);
      }
    }
  });
  var node_6 = sibling(node_1, 2);
  slot(node_6, $$props, "default", {}, null);
  reset(div);
  template_effect(() => {
    classes = set_class(div, 1, "source-row svelte-smkg1f", null, classes, {
      "is-ignored-task": node().kind === "task" && node().taskVisibility === "ignored",
      "is-raw-list-item": get(rawListItemText) !== null,
      "is-dragging": get(isDragging),
      "is-dragged-over": get(isDraggedOver),
      "drop-before": get(isDraggedOver) && get(dropBefore),
      "drop-after": get(isDraggedOver) && get(dropAfter)
    });
    set_attribute2(div, "draggable", !get(isEditing));
    styles = set_style(div, "", styles, { "--drag-indicator-depth": get(dragIndicatorDepth) });
  });
  event("dragstart", div, handleDragStart);
  event("dragend", div, handleDragEnd);
  event("dragover", div, handleDragOver);
  event("dragleave", div, handleDragLeave);
  event("drop", div, handleDrop);
  append($$anchor, div);
  var $$pop = pop($$exports);
  $$cleanup();
  return $$pop;
}

// src/ui/components/TaskSourceRows.svelte
function TaskSourceRows($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: TaskSourceRows, ...$$anchor });
  push($$props, false);
  let app = prop($$props, "app", 12);
  let task = prop($$props, "task", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let nodes = prop($$props, "nodes", 28, () => []);
  let isSelectionMode = prop($$props, "isSelectionMode", 12, false);
  let depth = prop($$props, "depth", 12, 0);
  var $$exports = {
    get app() {
      return app();
    },
    set app($$value) {
      app($$value);
      flushSync();
    },
    get task() {
      return task();
    },
    set task($$value) {
      task($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get nodes() {
      return nodes();
    },
    set nodes($$value) {
      nodes($$value);
      flushSync();
    },
    get isSelectionMode() {
      return isSelectionMode();
    },
    set isSelectionMode($$value) {
      isSelectionMode($$value);
      flushSync();
    },
    get depth() {
      return depth();
    },
    set depth($$value) {
      depth($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  var fragment = comment();
  var node_1 = first_child(fragment);
  each(node_1, 1, nodes, (node) => node.rowIndex, ($$anchor2, node) => {
    TaskSourceRow($$anchor2, {
      get app() {
        return app();
      },
      get task() {
        return task();
      },
      get taskActions() {
        return taskActions();
      },
      get node() {
        return get(node);
      },
      get isSelectionMode() {
        return isSelectionMode();
      },
      get depth() {
        return depth();
      },
      children: ($$anchor3, $$slotProps) => {
        var fragment_2 = comment();
        var node_2 = first_child(fragment_2);
        {
          var consequent = ($$anchor4) => {
            var fragment_3 = comment();
            var node_3 = first_child(fragment_3);
            {
              let $0 = derived_safe_equal(() => depth() + 1);
              TaskSourceRows(node_3, {
                get app() {
                  return app();
                },
                get task() {
                  return task();
                },
                get taskActions() {
                  return taskActions();
                },
                get nodes() {
                  return get(node), untrack(() => get(node).sourceChildren);
                },
                get isSelectionMode() {
                  return isSelectionMode();
                },
                get depth() {
                  return get($0);
                }
              });
            }
            append($$anchor4, fragment_3);
          };
          if_block(node_2, ($$render) => {
            if (get(node), untrack(() => get(node).sourceChildren.length > 0)) $$render(consequent);
          });
        }
        append($$anchor3, fragment_2);
      },
      $$slots: { default: true }
    });
  });
  append($$anchor, fragment);
  return pop($$exports);
}

// src/ui/components/task_menu.svelte
var import_obsidian5 = require("obsidian");
function Task_menu($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Task_menu, ...$$anchor });
  push($$props, false);
  const $columnTagTableStore = () => store_get(columnTagTableStore(), "$columnTagTableStore", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let task = prop($$props, "task", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
  let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
  function showMenu(e) {
    const menu = new import_obsidian5.Menu();
    const target = e.target;
    if (!target) {
      return;
    }
    const boundingRect = target.getBoundingClientRect();
    const y = boundingRect.top + boundingRect.height / 2;
    const x = boundingRect.left + boundingRect.width / 2;
    menu.addItem((i) => {
      i.setTitle(`Go to file`).onClick(() => taskActions().viewFile(task().id));
    });
    menu.addSeparator();
    for (const [tag2, label] of Object.entries($columnTagTableStore())) {
      menu.addItem((i) => {
        i.setTitle(`Move to ${label}`).onClick(() => taskActions().changeColumn(task().id, tag2));
        if (task().column === tag2) {
          i.setDisabled(true);
        }
      });
    }
    menu.addItem((i) => {
      i.setTitle(`Move to ${resolveDefaultColumnName("done", void 0, doneColumnName())}`).onClick(() => taskActions().markDone(task().id));
      if (task().done) {
        i.setDisabled(true);
      }
    });
    menu.addSeparator();
    menu.addItem((i) => {
      i.setTitle(`Duplicate task`).onClick(() => taskActions().duplicateTask(task().id));
    });
    menu.addItem((i) => {
      if (task().isCancelled) {
        i.setTitle(`Restore task`).onClick(() => taskActions().restoreTasks([task().id]));
      } else {
        i.setTitle(`Cancel task`).onClick(() => taskActions().cancelTasks([task().id]));
      }
    });
    menu.addItem((i) => {
      i.setTitle(`Archive task`).onClick(() => taskActions().archiveTasks([task().id]));
    });
    menu.addItem((i) => {
      i.setTitle(`Delete task`).onClick(() => taskActions().deleteTask(task().id));
    });
    menu.showAtPosition({ x, y });
  }
  var $$exports = {
    get task() {
      return task();
    },
    set task($$value) {
      task($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get columnTagTableStore() {
      return columnTagTableStore();
    },
    set columnTagTableStore($$value) {
      columnTagTableStore($$value);
      flushSync();
    },
    get doneColumnName() {
      return doneColumnName();
    },
    set doneColumnName($$value) {
      doneColumnName($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  Icon_button($$anchor, { icon: "lucide-more-vertical", $$events: { click: showMenu } });
  var $$pop = pop($$exports);
  $$cleanup();
  return $$pop;
}

// src/parsing/properties/none_schema.ts
var NoneSchema = class {
  constructor() {
    this.id = "none" /* None */;
    this.label = "None";
  }
  parseProperties(rawLine) {
    return createPropertyMapWithStatus(rawLine);
  }
  knownKeys() {
    return [
      {
        key: UNIVERSAL_STATUS_PROPERTY_KEY,
        label: "Status",
        type: "text"
      }
    ];
  }
};

// src/parsing/properties/dataview_schema.ts
var DATAVIEW_KEY_PATTERN = "[a-zA-Z0-9_-]+";
var ENCLOSED_DATAVIEW_REGEX = /\[\s*([a-zA-Z0-9_-]+)\s*::\s*([^\]]*?)\s*\]|\(\s*([a-zA-Z0-9_-]+)\s*::\s*([^\)]*?)\s*\)/g;
var BARE_DATAVIEW_MARKER_REGEX = new RegExp(`(^|\\s)(${DATAVIEW_KEY_PATTERN})\\s*::\\s*`, "g");
function parseDataviewValue(value) {
  const trimmed = value.trim();
  const parsedDate = parseIsoDate(trimmed);
  if (parsedDate) {
    return parsedDate;
  }
  const parsedNumber = parseNumber(trimmed);
  if (parsedNumber !== null) {
    return parsedNumber;
  }
  return trimmed;
}
function isInsideRange(index2, ranges) {
  return ranges.some((range) => index2 >= range.start && index2 < range.end);
}
function parseEnclosedFields(rawLine) {
  return [...rawLine.matchAll(ENCLOSED_DATAVIEW_REGEX)].flatMap((match) => {
    var _a5, _b3, _c2;
    const index2 = (_a5 = match.index) != null ? _a5 : Number.MAX_SAFE_INTEGER;
    const key2 = (_b3 = match[1]) != null ? _b3 : match[3];
    const rawValueText = (_c2 = match[2]) != null ? _c2 : match[4];
    if (!key2 || rawValueText === void 0) return [];
    return [{
      index: index2,
      endIndex: index2 + match[0].length,
      key: key2,
      rawValue: match[0],
      rawValueText
    }];
  });
}
function parseBareFields(rawLine, enclosedFields) {
  const enclosedRanges = enclosedFields.map((field) => ({ start: field.index, end: field.endIndex }));
  const markers = [...rawLine.matchAll(BARE_DATAVIEW_MARKER_REGEX)].map((match) => {
    var _a5, _b3, _c2;
    const prefix = (_a5 = match[1]) != null ? _a5 : "";
    const index2 = ((_b3 = match.index) != null ? _b3 : 0) + prefix.length;
    return {
      index: index2,
      valueStart: ((_c2 = match.index) != null ? _c2 : 0) + match[0].length,
      key: match[2]
    };
  }).filter((marker) => marker.key && !isInsideRange(marker.index, enclosedRanges));
  return markers.flatMap((marker, markerIndex) => {
    var _a5, _b3, _c2;
    if (!marker.key) return [];
    const nextMarkerIndex = (_b3 = (_a5 = markers[markerIndex + 1]) == null ? void 0 : _a5.index) != null ? _b3 : Number.MAX_SAFE_INTEGER;
    const nextEnclosedIndex = (_c2 = enclosedFields.map((field) => field.index).filter((index2) => index2 > marker.valueStart).sort((a, b) => a - b)[0]) != null ? _c2 : Number.MAX_SAFE_INTEGER;
    const endIndex = Math.min(nextMarkerIndex, nextEnclosedIndex, rawLine.length);
    const rawValueText = rawLine.slice(marker.valueStart, endIndex).trim();
    const rawValue = rawLine.slice(marker.index, endIndex).trimEnd();
    if (!rawValueText) return [];
    return [{
      index: marker.index,
      endIndex: marker.index + rawValue.length,
      key: marker.key,
      rawValue,
      rawValueText
    }];
  });
}
var DataviewSchema = class {
  constructor() {
    this.id = "dataview" /* Dataview */;
    this.label = "Dataview";
  }
  parseProperties(rawLine) {
    const properties = createPropertyMapWithStatus(rawLine);
    const enclosedFields = parseEnclosedFields(rawLine);
    const fields = [
      ...enclosedFields,
      ...parseBareFields(rawLine, enclosedFields)
    ].sort((a, b) => a.index - b.index);
    for (const field of fields) {
      if (!properties.has(field.key)) {
        properties.set(field.key, {
          key: field.key,
          rawValue: field.rawValue,
          value: parseDataviewValue(field.rawValueText),
          startIndex: field.index,
          endIndex: field.endIndex
        });
      }
    }
    return properties;
  }
  knownKeys() {
    return [
      { key: UNIVERSAL_STATUS_PROPERTY_KEY, label: "Status", type: "text" },
      { key: "due", label: "Due", type: "date" },
      { key: "scheduled", label: "Scheduled", type: "date" },
      { key: "start", label: "Start", type: "date" },
      { key: "done", label: "Done", type: "date", aliases: getPropertyAliases("done") },
      { key: "completion", label: "Completion", type: "date" },
      { key: "created", label: "Created", type: "date" },
      { key: "priority", label: "Priority", type: "text" },
      { key: "repeat", label: "Repeat", type: "text", aliases: getPropertyAliases("repeat") }
    ];
  }
};

// src/parsing/properties/comparators.ts
var ColumnOrderMode = /* @__PURE__ */ ((ColumnOrderMode2) => {
  ColumnOrderMode2["FileOrder"] = "file";
  ColumnOrderMode2["TaskName"] = "task-name";
  ColumnOrderMode2["Property"] = "property";
  ColumnOrderMode2["Manual"] = "manual";
  return ColumnOrderMode2;
})(ColumnOrderMode || {});
function compareValues(a, b) {
  if (a instanceof Date && b instanceof Date) {
    return a.getTime() - b.getTime();
  }
  if (typeof a === "number" && typeof b === "number") {
    return a - b;
  }
  return String(a).localeCompare(String(b));
}
function compareByProperty(a, b, key2, direction, options2 = {}) {
  var _a5, _b3, _c2, _d, _e, _f;
  const aValue = (_b3 = (_a5 = a.properties.get(key2)) == null ? void 0 : _a5.value) != null ? _b3 : null;
  const bValue = (_d = (_c2 = b.properties.get(key2)) == null ? void 0 : _c2.value) != null ? _d : null;
  if (aValue === null && bValue === null) return 0;
  if (aValue === null) return direction === "desc" ? -1 : 1;
  if (bValue === null) return direction === "desc" ? 1 : -1;
  if (key2 === UNIVERSAL_STATUS_PROPERTY_KEY) {
    return compareStatusMarkerValues(
      aValue,
      bValue,
      (_e = options2.statusMarkerOrder) != null ? _e : "",
      (_f = options2.doneStatusMarkers) != null ? _f : "",
      direction
    );
  }
  const result = compareValues(aValue, bValue);
  return direction === "desc" ? -result : result;
}
function compareStatusMarkerValues(a, b, statusMarkerOrder, doneStatusMarkers = "", direction = "asc") {
  const aMarker = String(a);
  const bMarker = String(b);
  const doneRankByMarker = createMarkerRankMap(doneStatusMarkers);
  const aDoneRank = doneRankByMarker.get(aMarker);
  const bDoneRank = doneRankByMarker.get(bMarker);
  if (aDoneRank !== void 0 && bDoneRank !== void 0) {
    return aDoneRank - bDoneRank;
  }
  if (aDoneRank !== void 0) return 1;
  if (bDoneRank !== void 0) return -1;
  const rankByMarker = createStatusMarkerRankMap(statusMarkerOrder);
  const aRank = rankByMarker.get(aMarker);
  const bRank = rankByMarker.get(bMarker);
  let result;
  if (aRank !== void 0 && bRank !== void 0) {
    result = aRank - bRank;
  } else if (aRank !== void 0) {
    result = -1;
  } else if (bRank !== void 0) {
    result = 1;
  } else {
    result = aMarker.localeCompare(bMarker);
  }
  return direction === "desc" ? -result : result;
}
function createStatusMarkerRankMap(statusMarkerOrder) {
  return createMarkerRankMap(getOrderedStatusMarkers(statusMarkerOrder).join(""));
}
function getOrderedStatusMarkers(statusMarkerOrder) {
  const orderedMarkers = Array.from(statusMarkerOrder);
  if (!orderedMarkers.includes(" ")) {
    orderedMarkers.unshift(" ");
  }
  return orderedMarkers;
}
function createMarkerRankMap(markers) {
  const rankByMarker = /* @__PURE__ */ new Map();
  for (const marker of Array.from(markers)) {
    if (!rankByMarker.has(marker)) {
      rankByMarker.set(marker, rankByMarker.size);
    }
  }
  return rankByMarker;
}

// src/parsing/properties/write.ts
var TASKS_WRITERS = {
  due: "\u{1F4C5}",
  scheduled: "\u23F3",
  start: "\u{1F6EB}",
  done: "\u2705"
};
var DATAVIEW_WRITERS = {
  due: "due",
  scheduled: "scheduled",
  start: "start",
  completion: "completion"
};
var DATAVIEW_PRIORITY_KEY = "priority";
var TRAILING_BLOCK_LINK_REGEX = /(\s\^[a-zA-Z0-9-]+)$/;
var TasksPluginWriteAdapter = class {
  constructor() {
    this.schema = "tasks" /* TasksPlugin */;
    this.propertySchema = new TasksPluginSchema();
  }
  addCompletionDateIfMissing(rawLine, date) {
    if (this.propertySchema.parseProperties(rawLine).has("done")) {
      return rawLine;
    }
    return appendBeforeBlockLink(rawLine, `${TASKS_WRITERS.done} ${date}`);
  }
  upsertDate(rawLine, key2, date) {
    var _a5;
    const marker = (_a5 = markerForExistingTasksProperty(rawLine, key2)) != null ? _a5 : TASKS_WRITERS[key2];
    const property = this.propertySchema.parseProperties(rawLine).get(key2);
    return upsertProperty(rawLine, property, `${marker} ${date}`);
  }
  removeDate(rawLine, key2) {
    const propertyKey = key2 === "completion" ? "done" : key2;
    const property = this.propertySchema.parseProperties(rawLine).get(propertyKey);
    return property ? removeProperty(rawLine, property) : rawLine;
  }
  upsertPriority(rawLine, priority) {
    const option = getTasksPriorityOption(priority);
    if (!option) {
      return rawLine;
    }
    const property = this.propertySchema.parseProperties(rawLine).get("priority");
    return upsertProperty(rawLine, property, option.emoji);
  }
  removePriority(rawLine) {
    const property = this.propertySchema.parseProperties(rawLine).get("priority");
    return property ? removeProperty(rawLine, property) : rawLine;
  }
};
var DataviewWriteAdapter = class {
  constructor() {
    this.schema = "dataview" /* Dataview */;
    this.propertySchema = new DataviewSchema();
  }
  addCompletionDateIfMissing(rawLine, date) {
    if (hasDataviewCompletionProperty(rawLine, this.propertySchema)) {
      return rawLine;
    }
    return appendBeforeBlockLink(rawLine, formatDataviewField("completion", date));
  }
  upsertDate(rawLine, key2, date) {
    const property = this.propertySchema.parseProperties(rawLine).get(key2);
    return upsertProperty(rawLine, property, formatDataviewField(DATAVIEW_WRITERS[key2], date));
  }
  removeDate(rawLine, key2) {
    const property = this.propertySchema.parseProperties(rawLine).get(key2);
    return property ? removeProperty(rawLine, property) : rawLine;
  }
  upsertPriority(rawLine, priority) {
    const normalizedPriority = priority.trim();
    if (!normalizedPriority) {
      return rawLine;
    }
    const property = this.propertySchema.parseProperties(rawLine).get(DATAVIEW_PRIORITY_KEY);
    return upsertProperty(rawLine, property, formatDataviewField(DATAVIEW_PRIORITY_KEY, normalizedPriority));
  }
  removePriority(rawLine) {
    const property = this.propertySchema.parseProperties(rawLine).get(DATAVIEW_PRIORITY_KEY);
    return property ? removeProperty(rawLine, property) : rawLine;
  }
};
var WRITE_ADAPTERS = {
  ["tasks" /* TasksPlugin */]: new TasksPluginWriteAdapter(),
  ["dataview" /* Dataview */]: new DataviewWriteAdapter()
};
function getPropertyWriteAdapter(schema) {
  if (schema === "tasks" /* TasksPlugin */ || schema === "dataview" /* Dataview */) {
    return WRITE_ADAPTERS[schema];
  }
  return null;
}
function formatLocalDate(date = /* @__PURE__ */ new Date()) {
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, "0");
  const day = `${date.getDate()}`.padStart(2, "0");
  return `${year}-${month}-${day}`;
}
function formatDataviewField(key2, date) {
  return `[${key2}:: ${date}]`;
}
function upsertProperty(rawLine, property, replacement) {
  if (!property) {
    return appendBeforeBlockLink(rawLine, replacement);
  }
  return replaceProperty(rawLine, property, replacement);
}
function replaceProperty(rawLine, property, replacement) {
  return `${rawLine.slice(0, property.startIndex)}${replacement}${rawLine.slice(property.endIndex)}`;
}
function removeProperty(rawLine, property) {
  const next2 = `${rawLine.slice(0, property.startIndex)}${rawLine.slice(property.endIndex)}`;
  return normalizeWhitespaceAroundIndex(next2, property.startIndex);
}
function appendBeforeBlockLink(rawLine, metadata) {
  const match = rawLine.match(TRAILING_BLOCK_LINK_REGEX);
  if (!(match == null ? void 0 : match.index)) {
    return `${rawLine.trimEnd()} ${metadata}`;
  }
  const body = rawLine.slice(0, match.index).trimEnd();
  return `${body} ${metadata}${match[0]}`;
}
function normalizeWhitespaceAroundIndex(rawLine, index2) {
  var _a5, _b3;
  let start = Math.max(0, index2);
  while (start > 0 && /[ \t]/.test((_a5 = rawLine[start - 1]) != null ? _a5 : "")) {
    start -= 1;
  }
  let end = Math.min(rawLine.length, index2);
  while (end < rawLine.length && /[ \t]/.test((_b3 = rawLine[end]) != null ? _b3 : "")) {
    end += 1;
  }
  const before = rawLine.slice(0, start);
  const after = rawLine.slice(end);
  const separator = before && after ? " " : "";
  return `${before}${separator}${after}`.trimEnd();
}
function markerForExistingTasksProperty(rawLine, key2) {
  const property = new TasksPluginSchema().parseProperties(rawLine).get(key2);
  if (!property) return void 0;
  const marker = Array.from(property.rawValue.trim())[0];
  return marker;
}
function hasDataviewCompletionProperty(rawLine, schema) {
  const properties = schema.parseProperties(rawLine);
  return properties.has("completion") || properties.has("done");
}

// src/parsing/properties/index.ts
var SCHEMA_IMPLS = {
  ["none" /* None */]: new NoneSchema(),
  ["tasks" /* TasksPlugin */]: new TasksPluginSchema(),
  ["dataview" /* Dataview */]: new DataviewSchema()
};
function getSchemaImpl(option) {
  var _a5;
  return (_a5 = SCHEMA_IMPLS[option]) != null ? _a5 : SCHEMA_IMPLS["none" /* None */];
}

// src/ui/components/DateInputFields.svelte
var root8 = from_html(`<label class="date-input-field svelte-4hxhuo"><span> </span> <input type="date" class="svelte-4hxhuo"/></label>`);
var root_15 = from_html(`<button class="done-date-editing svelte-4hxhuo" type="button">Done</button>`);
var root_24 = from_html(`<div class="date-input-fields svelte-4hxhuo" role="group" aria-label="Edit task dates" draggable="false"><!> <!></div>`);
var $$css8 = {
  hash: "svelte-4hxhuo",
  code: ".date-input-fields.svelte-4hxhuo {display:flex;flex-wrap:wrap;align-items:end;gap:var(--size-2-2);width:100%;}.date-input-field.svelte-4hxhuo {display:flex;flex-direction:column;gap:2px;min-width:116px;flex:1 1 116px;color:var(--text-muted);font-size:var(--font-smallest);text-transform:uppercase;}.date-input-field.svelte-4hxhuo input:where(.svelte-4hxhuo) {width:100%;min-height:28px;font-size:var(--font-ui-smaller);text-transform:none;}.done-date-editing.svelte-4hxhuo {display:inline-flex;align-items:center;gap:var(--size-2-1);min-height:28px;padding:1px var(--size-2-2);border:var(--border-width) solid var(--background-modifier-border);border-radius:var(--radius-s);background:var(--background-secondary-alt);color:var(--text-muted);box-shadow:none;line-height:var(--line-height-tight);}.done-date-editing.svelte-4hxhuo:hover {border-color:var(--text-muted);color:var(--text-normal);background:var(--background-secondary);box-shadow:none;}"
};
function DateInputFields($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: DateInputFields, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css8);
  let values = prop($$props, "values", 12);
  let onDateChange = prop($$props, "onDateChange", 12);
  let showDoneButton = prop($$props, "showDoneButton", 12, false);
  let onDone = prop($$props, "onDone", 12, () => {
  });
  const editableDateFields = [
    { key: "due", label: "Due" },
    { key: "scheduled", label: "Scheduled" },
    { key: "start", label: "Start" }
  ];
  var $$exports = {
    get values() {
      return values();
    },
    set values($$value) {
      values($$value);
      flushSync();
    },
    get onDateChange() {
      return onDateChange();
    },
    set onDateChange($$value) {
      onDateChange($$value);
      flushSync();
    },
    get showDoneButton() {
      return showDoneButton();
    },
    set showDoneButton($$value) {
      showDoneButton($$value);
      flushSync();
    },
    get onDone() {
      return onDone();
    },
    set onDone($$value) {
      onDone($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root_24();
  var node = child(div);
  each(node, 1, () => editableDateFields, (field) => field.key, ($$anchor2, field) => {
    var label = root8();
    var span = child(label);
    var text2 = child(span, true);
    reset(span);
    var input = sibling(span, 2);
    remove_input_defaults(input);
    reset(label);
    template_effect(() => {
      set_text(text2, (get(field), untrack(() => get(field).label)));
      set_value(input, (deep_read_state(values()), get(field), untrack(() => values()[get(field).key])));
    });
    event("mousedown", input, stopPropagation(function($$arg) {
      bubble_event.call(this, $$props, $$arg);
    }));
    event("mouseup", input, stopPropagation(function($$arg) {
      bubble_event.call(this, $$props, $$arg);
    }));
    event("click", input, stopPropagation(function($$arg) {
      bubble_event.call(this, $$props, $$arg);
    }));
    event("change", input, (event2) => onDateChange()(get(field).key, event2.currentTarget.value));
    event("keydown", input, stopPropagation(function($$arg) {
      bubble_event.call(this, $$props, $$arg);
    }));
    append($$anchor2, label);
  });
  var node_1 = sibling(node, 2);
  {
    var consequent = ($$anchor2) => {
      var button = root_15();
      event("mousedown", button, stopPropagation(function($$arg) {
        bubble_event.call(this, $$props, $$arg);
      }));
      event("mouseup", button, stopPropagation(function($$arg) {
        bubble_event.call(this, $$props, $$arg);
      }));
      event("click", button, function(...$$args) {
        var _a5;
        (_a5 = onDone()) == null ? void 0 : _a5.apply(this, $$args);
      });
      event("keydown", button, stopPropagation(function($$arg) {
        bubble_event.call(this, $$props, $$arg);
      }));
      append($$anchor2, button);
    };
    if_block(node_1, ($$render) => {
      if (showDoneButton()) $$render(consequent);
    });
  }
  reset(div);
  append($$anchor, div);
  return pop($$exports);
}

// src/ui/components/TaskDateFields.svelte
var root9 = from_html(`<div class="task-date-fields read-mode svelte-1ml44qr" role="group" aria-label="Task dates" draggable="false"><button class="add-date-button svelte-1ml44qr" type="button" title="Edit task dates"><span aria-hidden="true" class="svelte-1ml44qr">+</span> Date</button></div>`);
var root_16 = from_html(`<div class="task-date-fields edit-mode svelte-1ml44qr"><!></div>`);
var $$css9 = {
  hash: "svelte-1ml44qr",
  code: ".task-date-fields.svelte-1ml44qr {display:contents;font-size:var(--font-ui-smaller);}.add-date-button.svelte-1ml44qr {display:inline-flex;align-items:center;gap:var(--size-2-1);height:auto;min-height:0;padding:0 var(--size-2-2);margin:0;border:none;border-radius:var(--radius-s);background:transparent;color:var(--text-accent);box-shadow:none;font-size:inherit;font-weight:var(--font-medium);line-height:inherit;}.add-date-button.svelte-1ml44qr span:where(.svelte-1ml44qr) {font-size:inherit;line-height:1;}.add-date-button.svelte-1ml44qr:hover {background:transparent;color:var(--text-accent-hover);box-shadow:none;}.edit-mode.svelte-1ml44qr {display:flex;width:100%;padding-top:var(--size-2-1);border-top:var(--border-width) solid var(--background-modifier-border);}"
};
function TaskDateFields($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: TaskDateFields, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css9);
  const dateEditingEnabled = mutable_source();
  const dateValues = mutable_source();
  const showDateInputs = mutable_source();
  const showReadChips = mutable_source();
  let task = prop($$props, "task", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
  let isTaskEditing = prop($$props, "isTaskEditing", 12, false);
  let isEditingDates = prop($$props, "isEditingDates", 12, false);
  const editableDateFields = [
    { key: "due", label: "Due", shortLabel: "Due" },
    { key: "scheduled", label: "Scheduled", shortLabel: "Sched" },
    { key: "start", label: "Start", shortLabel: "Start" }
  ];
  let isDateEditing = mutable_source(false);
  let draftDateValues = mutable_source({ due: "", scheduled: "", start: "" });
  let wasShowingDateInputs = mutable_source(false);
  function getDateValue(key2) {
    const property = getPropertyByKey(task().properties, key2);
    return (property == null ? void 0 : property.value) instanceof Date ? formatLocalDate(property.value) : "";
  }
  function openDateEditor() {
    set(draftDateValues, { ...get(dateValues) });
    set(isDateEditing, true);
  }
  function handleDraftDateChange(key2, value) {
    set(draftDateValues, { ...get(draftDateValues), [key2]: value });
  }
  async function saveDraftDates() {
    var _a5;
    for (const field of editableDateFields) {
      const key2 = field.key;
      const nextValue = (_a5 = get(draftDateValues)[key2]) != null ? _a5 : "";
      if (nextValue === get(dateValues)[key2]) {
        continue;
      }
      if (nextValue) {
        await taskActions().setDateProperty(task().id, key2, nextValue);
      } else {
        await taskActions().clearDateProperty(task().id, key2);
      }
    }
    set(isDateEditing, false);
  }
  legacy_pre_effect(
    () => (getPropertyWriteAdapter, deep_read_state(propertySchemaOption())),
    () => {
      set(dateEditingEnabled, getPropertyWriteAdapter(propertySchemaOption()) !== null);
    }
  );
  legacy_pre_effect(() => {
  }, () => {
    set(dateValues, Object.fromEntries(editableDateFields.map((field) => [field.key, getDateValue(field.key)])));
  });
  legacy_pre_effect(
    () => (get(dateEditingEnabled), deep_read_state(isTaskEditing()), get(isDateEditing)),
    () => {
      set(showDateInputs, get(dateEditingEnabled) && (isTaskEditing() || get(isDateEditing)));
    }
  );
  legacy_pre_effect(() => (get(dateEditingEnabled), get(showDateInputs)), () => {
    set(showReadChips, get(dateEditingEnabled) && !get(showDateInputs));
  });
  legacy_pre_effect(() => get(showDateInputs), () => {
    isEditingDates(get(showDateInputs));
  });
  legacy_pre_effect(
    () => (get(showDateInputs), get(wasShowingDateInputs), get(dateValues)),
    () => {
      if (get(showDateInputs) && !get(wasShowingDateInputs)) {
        set(draftDateValues, { ...get(dateValues) });
      }
      set(wasShowingDateInputs, get(showDateInputs));
    }
  );
  legacy_pre_effect_reset();
  var $$exports = {
    get task() {
      return task();
    },
    set task($$value) {
      task($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get propertySchemaOption() {
      return propertySchemaOption();
    },
    set propertySchemaOption($$value) {
      propertySchemaOption($$value);
      flushSync();
    },
    get isTaskEditing() {
      return isTaskEditing();
    },
    set isTaskEditing($$value) {
      isTaskEditing($$value);
      flushSync();
    },
    get isEditingDates() {
      return isEditingDates();
    },
    set isEditingDates($$value) {
      isEditingDates($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root9();
      var button = child(div);
      reset(div);
      event("mousedown", button, stopPropagation(function($$arg) {
        bubble_event.call(this, $$props, $$arg);
      }));
      event("mouseup", button, stopPropagation(function($$arg) {
        bubble_event.call(this, $$props, $$arg);
      }));
      event("click", button, openDateEditor);
      event("keydown", button, stopPropagation(function($$arg) {
        bubble_event.call(this, $$props, $$arg);
      }));
      append($$anchor2, div);
    };
    var consequent_1 = ($$anchor2) => {
      var div_1 = root_16();
      var node_1 = child(div_1);
      DateInputFields(node_1, {
        get values() {
          return get(draftDateValues);
        },
        onDateChange: handleDraftDateChange,
        showDoneButton: true,
        onDone: saveDraftDates
      });
      reset(div_1);
      append($$anchor2, div_1);
    };
    if_block(node, ($$render) => {
      if (get(showReadChips)) $$render(consequent);
      else if (get(showDateInputs)) $$render(consequent_1, 1);
    });
  }
  append($$anchor, fragment);
  return pop($$exports);
}

// src/ui/components/task.svelte
var import_obsidian6 = require("obsidian");

// node_modules/zod/lib/index.mjs
var util;
(function(util2) {
  util2.assertEqual = (val) => val;
  function assertIs(_arg) {
  }
  util2.assertIs = assertIs;
  function assertNever(_x) {
    throw new Error();
  }
  util2.assertNever = assertNever;
  util2.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
    const filtered = {};
    for (const k of validKeys) {
      filtered[k] = obj[k];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e) {
      return obj[e];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys = [];
    for (const key2 in object) {
      if (Object.prototype.hasOwnProperty.call(object, key2)) {
        keys.push(key2);
      }
    }
    return keys;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  util2.joinValues = joinValues;
  util2.jsonStringifyReplacer = (_, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType = (data) => {
  const t = typeof data;
  switch (t) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
};
var ZodIssueCode = util.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
var quotelessJson = (obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
};
var ZodError = class _ZodError extends Error {
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  get errors() {
    return this.issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue) {
      return issue.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = (error) => {
      for (const issue of error.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < issue.path.length) {
            const el = issue.path[i];
            const terminal = i === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof _ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
        fieldErrors[sub.path[0]].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
};
ZodError.create = (issues) => {
  const error = new ZodError(issues);
  return error;
};
var errorMap = (issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode.invalid_type:
      if (issue.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = `Invalid input: must include "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return { message };
};
var overrideErrorMap = errorMap;
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}
var makeIssue = (params) => {
  const { data, path, errorMaps, issueData } = params;
  const fullPath = [...path, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m) => !!m).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      ctx.schemaErrorMap,
      overrideMap,
      overrideMap === errorMap ? void 0 : errorMap
      // then global default map
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}
var ParseStatus = class _ParseStatus {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s of results) {
      if (s.status === "aborted")
        return INVALID;
      if (s.status === "dirty")
        status.dirty();
      arrayValue.push(s.value);
    }
    return { status: status.value, value: arrayValue };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key2 = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key: key2,
        value
      });
    }
    return _ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key: key2, value } = pair;
      if (key2.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key2.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key2.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key2.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
};
var INVALID = Object.freeze({
  status: "aborted"
});
var DIRTY2 = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
function __classPrivateFieldGet(receiver, state2, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state2.get(receiver);
}
function __classPrivateFieldSet(receiver, state2, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state2.set(receiver, value), value;
}
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache;
var _ZodNativeEnum_cache;
var ParseInputLazyPath = class {
  constructor(parent, value, path, key2) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path;
    this._key = key2;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (this._key instanceof Array) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
var handleResult = (ctx, result) => {
  if (isValid(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error = new ZodError(ctx.common.issues);
        this._error = error;
        return this._error;
      }
    };
  }
};
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    var _a5, _b3;
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a5 = message !== null && message !== void 0 ? message : required_error) !== null && _a5 !== void 0 ? _a5 : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b3 = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b3 !== void 0 ? _b3 : ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
var ZodType = class {
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
  }
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    var _a5;
    const ctx = {
      common: {
        issues: [],
        async: (_a5 = params === null || params === void 0 ? void 0 : params.async) !== null && _a5 !== void 0 ? _a5 : false,
        contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
      },
      path: (params === null || params === void 0 ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const result = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
        async: true
      },
      path: (params === null || params === void 0 ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = (val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    };
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      });
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data) => {
          if (!data) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this, this._def);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
  if (args.precision) {
    regex = `${regex}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    regex = `${regex}(\\.\\d+)?`;
  }
  return regex;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
var ZodString = class _ZodString extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch (_a5) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex = datetimeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex = dateRegex;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex = timeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex, validation, message) {
    return this.refinement((data) => regex.test(data), {
      validation,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check) {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  }
  ip(options2) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options2) });
  }
  datetime(options2) {
    var _a5, _b3;
    if (typeof options2 === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options2
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof (options2 === null || options2 === void 0 ? void 0 : options2.precision) === "undefined" ? null : options2 === null || options2 === void 0 ? void 0 : options2.precision,
      offset: (_a5 = options2 === null || options2 === void 0 ? void 0 : options2.offset) !== null && _a5 !== void 0 ? _a5 : false,
      local: (_b3 = options2 === null || options2 === void 0 ? void 0 : options2.local) !== null && _b3 !== void 0 ? _b3 : false,
      ...errorUtil.errToObj(options2 === null || options2 === void 0 ? void 0 : options2.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options2) {
    if (typeof options2 === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options2
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof (options2 === null || options2 === void 0 ? void 0 : options2.precision) === "undefined" ? null : options2 === null || options2 === void 0 ? void 0 : options2.precision,
      ...errorUtil.errToObj(options2 === null || options2 === void 0 ? void 0 : options2.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options2) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options2 === null || options2 === void 0 ? void 0 : options2.position,
      ...errorUtil.errToObj(options2 === null || options2 === void 0 ? void 0 : options2.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  /**
   * @deprecated Use z.string().min(1) instead.
   * @see {@link ZodString.min}
   */
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get minLength() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxLength() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
};
ZodString.create = (params) => {
  var _a5;
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: (_a5 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a5 !== void 0 ? _a5 : false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}
var ZodNumber = class _ZodNumber extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxValue() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max2 = null, min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      } else if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return Number.isFinite(min2) && Number.isFinite(max2);
  }
};
ZodNumber.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
var ZodBigInt = class _ZodBigInt extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = BigInt(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.bigint,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxValue() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
};
ZodBigInt.create = (params) => {
  var _a5;
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: (_a5 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a5 !== void 0 ? _a5 : false,
    ...processCreateParams(params)
  });
};
var ZodBoolean = class extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
var ZodDate = class _ZodDate extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new _ZodDate({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2 != null ? new Date(min2) : null;
  }
  get maxDate() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2 != null ? new Date(max2) : null;
  }
};
ZodDate.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};
var ZodSymbol = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};
var ZodUndefined = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};
var ZodNull = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};
var ZodAny = class extends ZodType {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
};
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};
var ZodUnknown = class extends ZodType {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
};
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};
var ZodNever = class extends ZodType {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
};
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};
var ZodVoid = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};
var ZodArray = class _ZodArray extends ZodType {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
      })).then((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
    });
    return ParseStatus.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new _ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new _ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new _ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodArray.create = (schema, params) => {
  return new ZodArray({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key2 in schema.shape) {
      const fieldSchema = schema.shape[key2];
      newShape[key2] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
var ZodObject = class _ZodObject extends ZodType {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util.objectKeys(shape);
    return this._cached = { shape, keys };
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key2 in ctx.data) {
        if (!shapeKeys.includes(key2)) {
          extraKeys.push(key2);
        }
      }
    }
    const pairs = [];
    for (const key2 of shapeKeys) {
      const keyValidator = shape[key2];
      const value = ctx.data[key2];
      pairs.push({
        key: { status: "valid", value: key2 },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key2)),
        alwaysSet: key2 in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key2 of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key2 },
            value: { status: "valid", value: ctx.data[key2] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") ;
      else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key2 of extraKeys) {
        const value = ctx.data[key2];
        pairs.push({
          key: { status: "valid", value: key2 },
          value: catchall._parse(
            new ParseInputLazyPath(ctx, value, ctx.path, key2)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key2 in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key2 = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key: key2,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: (issue, ctx) => {
          var _a5, _b3, _c2, _d;
          const defaultError = (_c2 = (_b3 = (_a5 = this._def).errorMap) === null || _b3 === void 0 ? void 0 : _b3.call(_a5, issue, ctx).message) !== null && _c2 !== void 0 ? _c2 : ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new _ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new _ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key2, schema) {
    return this.augment({ [key2]: schema });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index2) {
    return new _ZodObject({
      ...this._def,
      catchall: index2
    });
  }
  pick(mask) {
    const shape = {};
    util.objectKeys(mask).forEach((key2) => {
      if (mask[key2] && this.shape[key2]) {
        shape[key2] = this.shape[key2];
      }
    });
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    util.objectKeys(this.shape).forEach((key2) => {
      if (!mask[key2]) {
        shape[key2] = this.shape[key2];
      }
    });
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key2) => {
      const fieldSchema = this.shape[key2];
      if (mask && !mask[key2]) {
        newShape[key2] = fieldSchema;
      } else {
        newShape[key2] = fieldSchema.optional();
      }
    });
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key2) => {
      if (mask && !mask[key2]) {
        newShape[key2] = this.shape[key2];
      } else {
        const fieldSchema = this.shape[key2];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key2] = newField;
      }
    });
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
};
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
var ZodUnion = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options2 = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return Promise.all(options2.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options2) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
};
ZodUnion.create = (types, params) => {
  return new ZodUnion({
    options: types,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
var getDiscriminator = (type) => {
  if (type instanceof ZodLazy) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral) {
    return [type.value];
  } else if (type instanceof ZodEnum) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [void 0];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [void 0, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
};
var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options2, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options2) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new _ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options: options2,
      optionsMap,
      ...processCreateParams(params)
    });
  }
};
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key2) => bKeys.indexOf(key2) !== -1);
    const newObj = { ...a, ...b };
    for (const key2 of sharedKeys) {
      const sharedValue = mergeValues(a[key2], b[key2]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key2] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index2 = 0; index2 < a.length; index2++) {
      const itemA = a[index2];
      const itemB = b[index2];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
var ZodIntersection = class extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    };
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
};
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};
var ZodTuple = class _ZodTuple extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x) => !!x);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new _ZodTuple({
      ...this._def,
      rest
    });
  }
};
ZodTuple.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};
var ZodRecord = class _ZodRecord extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key2 in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, key2)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key2], ctx.path, key2)),
        alwaysSet: key2 in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType) {
      return new _ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new _ZodRecord({
      keyType: ZodString.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
};
var ZodMap = class extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key2, value], index2) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, [index2, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key2 = await pair.key;
          const value = await pair.value;
          if (key2.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key2.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key2.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key2 = pair.key;
        const value = pair.value;
        if (key2.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key2.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key2.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
};
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};
var ZodSet = class _ZodSet extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element2 of elements2) {
        if (element2.status === "aborted")
          return INVALID;
        if (element2.status === "dirty")
          status.dirty();
        parsedSet.add(element2.value);
      }
      return { status: status.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new _ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new _ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size2, message) {
    return this.min(size2, message).max(size2, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};
var ZodFunction = class _ZodFunction extends ZodType {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          ctx.schemaErrorMap,
          getErrorMap(),
          errorMap
        ].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error
        }
      });
    }
    function makeReturnsIssue(returns, error) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          ctx.schemaErrorMap,
          getErrorMap(),
          errorMap
        ].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error
        }
      });
    }
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      const me = this;
      return OK(async function(...args) {
        const error = new ZodError([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
          error.addIssue(makeArgsIssue(args, e));
          throw error;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
          error.addIssue(makeReturnsIssue(result, e));
          throw error;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK(function(...args) {
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new _ZodFunction({
      ...this._def,
      args: ZodTuple.create(items).rest(ZodUnknown.create())
    });
  }
  returns(returnType) {
    return new _ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new _ZodFunction({
      args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
      returns: returns || ZodUnknown.create(),
      typeName: ZodFirstPartyTypeKind.ZodFunction,
      ...processCreateParams(params)
    });
  }
};
var ZodLazy = class extends ZodType {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
};
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};
var ZodLiteral = class extends ZodType {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
};
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
var ZodEnum = class _ZodEnum extends ZodType {
  constructor() {
    super(...arguments);
    _ZodEnum_cache.set(this, void 0);
  }
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
      __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values, newDef = this._def) {
    return _ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
};
_ZodEnum_cache = /* @__PURE__ */ new WeakMap();
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
  constructor() {
    super(...arguments);
    _ZodNativeEnum_cache.set(this, void 0);
  }
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
      __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
};
_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
var ZodPromise = class extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
};
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};
var ZodEffects = class extends ZodType {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect2 = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect2.type === "preprocess") {
      const processed = effect2.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID;
          if (result.status === "dirty")
            return DIRTY2(result.value);
          if (status.value === "dirty")
            return DIRTY2(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID;
        if (result.status === "dirty")
          return DIRTY2(result.value);
        if (status.value === "dirty")
          return DIRTY2(result.value);
        return result;
      }
    }
    if (effect2.type === "refinement") {
      const executeRefinement = (acc) => {
        const result = effect2.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID;
        if (inner.status === "dirty")
          status.dirty();
        executeRefinement(inner.value);
        return { status: status.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID;
          if (inner.status === "dirty")
            status.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status.value, value: inner.value };
          });
        });
      }
    }
    if (effect2.type === "transform") {
      if (ctx.common.async === false) {
        const base = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base))
          return base;
        const result = effect2.transform(base.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
          if (!isValid(base))
            return base;
          return Promise.resolve(effect2.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
        });
      }
    }
    util.assertNever(effect2);
  }
};
ZodEffects.create = (schema, effect2, params) => {
  return new ZodEffects({
    schema,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect: effect2,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  return new ZodEffects({
    schema,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params)
  });
};
var ZodOptional = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};
var ZodNullable = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};
var ZodDefault = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
var ZodCatch = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
};
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
var ZodNaN = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
};
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
var BRAND = /* @__PURE__ */ Symbol("zod_brand");
var ZodBranded = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
};
var ZodPipeline = class _ZodPipeline extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY2(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a, b) {
    return new _ZodPipeline({
      in: a,
      out: b,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
};
var ZodReadonly = class extends ZodType {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = (data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    };
    return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
function custom(check, params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      var _a5, _b3;
      if (!check(data)) {
        const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
        const _fatal = (_b3 = (_a5 = p.fatal) !== null && _a5 !== void 0 ? _a5 : fatal) !== null && _b3 !== void 0 ? _b3 : true;
        const p2 = typeof p === "string" ? { message: p } : p;
        ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
      }
    });
  return ZodAny.create();
}
var late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
  ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
  string: ((arg) => ZodString.create({ ...arg, coerce: true })),
  number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
  boolean: ((arg) => ZodBoolean.create({
    ...arg,
    coerce: true
  })),
  bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
  date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
};
var NEVER = INVALID;
var z = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  defaultErrorMap: errorMap,
  setErrorMap,
  getErrorMap,
  makeIssue,
  EMPTY_PATH,
  addIssueToContext,
  ParseStatus,
  INVALID,
  DIRTY: DIRTY2,
  OK,
  isAborted,
  isDirty,
  isValid,
  isAsync,
  get util() {
    return util;
  },
  get objectUtil() {
    return objectUtil;
  },
  ZodParsedType,
  getParsedType,
  ZodType,
  datetimeRegex,
  ZodString,
  ZodNumber,
  ZodBigInt,
  ZodBoolean,
  ZodDate,
  ZodSymbol,
  ZodUndefined,
  ZodNull,
  ZodAny,
  ZodUnknown,
  ZodNever,
  ZodVoid,
  ZodArray,
  ZodObject,
  ZodUnion,
  ZodDiscriminatedUnion,
  ZodIntersection,
  ZodTuple,
  ZodRecord,
  ZodMap,
  ZodSet,
  ZodFunction,
  ZodLazy,
  ZodLiteral,
  ZodEnum,
  ZodNativeEnum,
  ZodPromise,
  ZodEffects,
  ZodTransformer: ZodEffects,
  ZodOptional,
  ZodNullable,
  ZodDefault,
  ZodCatch,
  ZodNaN,
  BRAND,
  ZodBranded,
  ZodPipeline,
  ZodReadonly,
  custom,
  Schema: ZodType,
  ZodSchema: ZodType,
  late,
  get ZodFirstPartyTypeKind() {
    return ZodFirstPartyTypeKind;
  },
  coerce,
  any: anyType,
  array: arrayType,
  bigint: bigIntType,
  boolean: booleanType,
  date: dateType,
  discriminatedUnion: discriminatedUnionType,
  effect: effectsType,
  "enum": enumType,
  "function": functionType,
  "instanceof": instanceOfType,
  intersection: intersectionType,
  lazy: lazyType,
  literal: literalType,
  map: mapType,
  nan: nanType,
  nativeEnum: nativeEnumType,
  never: neverType,
  "null": nullType,
  nullable: nullableType,
  number: numberType,
  object: objectType,
  oboolean,
  onumber,
  optional: optionalType,
  ostring,
  pipeline: pipelineType,
  preprocess: preprocessType,
  promise: promiseType,
  record: recordType,
  set: setType,
  strictObject: strictObjectType,
  string: stringType,
  symbol: symbolType,
  transformer: effectsType,
  tuple: tupleType,
  "undefined": undefinedType,
  union: unionType,
  unknown: unknownType,
  "void": voidType,
  NEVER,
  ZodIssueCode,
  quotelessJson,
  ZodError
});

// src/ui/tasks/task.ts
var import_sha256 = __toESM(require_sha256());

// src/parsing/tags/tags.ts
function getTagsFromContent(content) {
  const tags = /* @__PURE__ */ new Set();
  const matches = content.matchAll(tagsRegex);
  for (const match of matches) {
    if (match[1] && tagNonNumericTest.test(match[1])) {
      tags.add(match[1]);
    }
  }
  return tags;
}
function isValidTag(tag2) {
  return /^[-_/\p{L}\p{N}]+$/u.test(tag2);
}
var tagsRegex = /#([-_/\p{L}\p{N}]+)/gu;
var tagNonNumericTest = /\p{L}/u;

// src/ui/tasks/task.ts
var DEFAULT_DONE_STATUS_MARKERS = "xX";
var DEFAULT_IGNORED_STATUS_MARKERS = "";
var DEFAULT_CANCELLED_STATUS_MARKERS = "-";
function validateStatusMarkers(markers) {
  const errors = [];
  const chars = Array.from(markers);
  const seen = /* @__PURE__ */ new Set();
  for (let i = 0; i < chars.length; i++) {
    const char = chars[i];
    if (!char) continue;
    if (seen.has(char)) {
      errors.push(`Duplicate marker '${char}' at position ${i + 1}`);
      continue;
    }
    seen.add(char);
    if (/\s/.test(char)) {
      errors.push(`Marker at position ${i + 1} is whitespace`);
    }
    if (char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) {
      errors.push(`Marker at position ${i + 1} is a control character`);
    }
  }
  return errors;
}
function validateTypedStatusMarkers(markers, label, allowEmpty) {
  if (!markers || markers.length === 0) {
    return allowEmpty ? [] : [`${label} status markers cannot be empty`];
  }
  return validateStatusMarkers(markers);
}
function validateDoneStatusMarkers(markers) {
  return validateTypedStatusMarkers(markers, "Done", false);
}
function validateIgnoredStatusMarkers(markers) {
  return validateTypedStatusMarkers(markers, "Ignored", true);
}
function validateCancelledStatusMarkers(markers) {
  return validateTypedStatusMarkers(markers, "Cancelled", false);
}
function validateStatusMarkerOrder(markers) {
  const errors = [];
  const chars = Array.from(markers);
  const seen = /* @__PURE__ */ new Set();
  for (let i = 0; i < chars.length; i++) {
    const char = chars[i];
    if (char !== " " && /\s/.test(char)) {
      errors.push(`Marker at position ${i + 1} is whitespace`);
    }
    if (seen.has(char)) {
      errors.push(`Duplicate marker '${char}' at position ${i + 1}`);
    }
    seen.add(char);
  }
  return errors;
}
function isStatusMatch(statusContent, markers) {
  if (!statusContent || !markers) return false;
  const contentChars = Array.from(statusContent);
  const markersChars = Array.from(markers);
  if (contentChars.length !== 1) {
    return false;
  }
  const singleChar = contentChars[0];
  if (!singleChar) return false;
  return markersChars.includes(singleChar);
}
function getNextStatusMarker(currentStatus, doneStatusMarkers, statusMarkerOrder) {
  var _a5;
  if (isStatusMatch(currentStatus, doneStatusMarkers)) {
    return { status: " ", done: false };
  }
  const orderedMarkers = getOrderedStatusMarkers(statusMarkerOrder);
  const currentIndex = orderedMarkers.indexOf(currentStatus);
  const nextMarker = currentIndex >= 0 ? orderedMarkers[currentIndex + 1] : void 0;
  if (!nextMarker || isStatusMatch(nextMarker, doneStatusMarkers)) {
    return {
      status: (_a5 = Array.from(doneStatusMarkers)[0]) != null ? _a5 : "x",
      done: true
    };
  }
  return { status: nextMarker, done: false };
}
var Task = class {
  constructor(rawContent, fileHandle, rowIndex, context, sourceChildren = []) {
    this.rowIndex = rowIndex;
    this._deleted = false;
    var _a5, _b3;
    const [, blockLink] = (_a5 = rawContent.match(blockLinkRegexp)) != null ? _a5 : [];
    this.blockLink = blockLink;
    const match = (blockLink ? rawContent.replace(blockLinkRegexp, "") : rawContent).match(taskStringRegex);
    if (!match) {
      throw new Error(
        "Attempted to create a task from invalid raw content"
      );
    }
    const [, indentation, status, content] = match;
    if (!content) {
      throw new Error("Content not found in raw content");
    }
    this.sourceChildren = sourceChildren;
    const tags = getTagsFromContent(content);
    this._id = (0, import_sha256.default)(content + fileHandle.path + rowIndex).toString();
    this.content = content;
    this._displayStatus = status || " ";
    this._done = isStatusMatch(this._displayStatus, context.doneStatusMarkers);
    this._path = fileHandle.path;
    this._indentation = indentation || "";
    this.properties = context.propertySchema.parseProperties(rawContent);
    this.propertySchemaOption = context.propertySchema.id;
    const priorityMatches = getTaskPriorityMatchValues(rawContent);
    const matchedColumn = resolveMatchedColumnDefinition(context.columnDefinitions, {
      tags,
      status: this._displayStatus,
      priority: getTaskPriorityMatchValue(this.propertySchemaOption, this.properties),
      prioritySchema: this.propertySchemaOption === "tasks" /* TasksPlugin */ ? "tasks" /* TasksPlugin */ : this.propertySchemaOption === "dataview" /* Dataview */ ? "dataview" /* Dataview */ : void 0,
      priorities: priorityMatches
    });
    for (const tag2 of tags) {
      if (tag2 === "done") {
        if (!this._column) {
          this._column = "done";
        }
        tags.delete(tag2);
        if (!context.consolidateTags) {
          this.content = this.stripTagFromContent(this.content, tag2);
        }
        continue;
      }
      if (matchedColumn && isPlacementTag(matchedColumn, tag2)) {
        if (!this._column) {
          this._column = matchedColumn.id;
        }
        tags.delete(tag2);
        if (!context.consolidateTags) {
          this.content = this.stripTagFromContent(this.content, tag2);
        }
      }
      if (context.consolidateTags) {
        this.content = this.stripTagFromContent(this.content, tag2);
      }
    }
    if (matchedColumn && usesStatusMatching(matchedColumn) && !this._column) {
      this._column = matchedColumn.id;
    }
    if (matchedColumn && usesPriorityMatching(matchedColumn) && !this._column) {
      this._column = matchedColumn.id;
    }
    this._tags = tags;
    this.blockLink = blockLink;
    this.consolidateTags = context.consolidateTags;
    this.sourceColumnDefinitions = context.columnDefinitions;
    this.columnDefinitions = (_b3 = context.columnWriteDefinitions) != null ? _b3 : context.columnDefinitions;
    this.columnPlacementTagTable = context.columnPlacementTagTable;
    this.doneStatusMarkers = context.doneStatusMarkers;
    this.cancelledStatusMarkers = context.cancelledStatusMarkers;
    this.ignoredStatusMarkers = context.ignoredStatusMarkers;
    if (this._done) {
      this._column = void 0;
    }
  }
  get id() {
    return this._id;
  }
  get done() {
    return this._done;
  }
  set done(done) {
    var _a5;
    this._done = done;
    this._column = void 0;
    this._displayStatus = (_a5 = Array.from(this.doneStatusMarkers)[0]) != null ? _a5 : "x";
  }
  get isCancelled() {
    return isStatusMatch(this._displayStatus, this.cancelledStatusMarkers);
  }
  undone() {
    this._done = false;
    this._displayStatus = " ";
  }
  cycleStatus(statusMarkerOrder) {
    const next2 = getNextStatusMarker(
      this._displayStatus,
      this.doneStatusMarkers,
      statusMarkerOrder
    );
    if (next2.done) {
      this.done = true;
      return true;
    }
    this._done = false;
    this._displayStatus = next2.status;
    return false;
  }
  get displayStatus() {
    return this._displayStatus;
  }
  get path() {
    return this._path;
  }
  get indentation() {
    return this._indentation;
  }
  get column() {
    return this._column;
  }
  set column(column) {
    if (column === "done") {
      this.done = true;
      return;
    }
    const wasDone = this._done;
    if (column === "uncategorised") {
      this.moveToUncategorised();
      if (wasDone) {
        this._displayStatus = " ";
      }
      return;
    }
    this._done = false;
    if (wasDone) {
      this._displayStatus = " ";
    }
    this.moveToColumn(column);
  }
  get tags() {
    return this._tags;
  }
  getPlacementTagsForColumn(column) {
    var _a5;
    return ((_a5 = this.columnPlacementTagTable[column]) != null ? _a5 : []).filter((tag2) => isValidTag(tag2));
  }
  getCurrentPlacementTags() {
    if (!this.column || this.column === "archived" || this.column === "done" || this.column === "uncategorised") {
      return [];
    }
    return this.getPlacementTagsForColumn(this.column);
  }
  getColumnDefinition(column, definitions = this.columnDefinitions) {
    if (!column) return void 0;
    return definitions.find((definition) => definition.id === column);
  }
  moveToColumn(column) {
    const sourceColumn = this.getColumnDefinition(
      this._column && this._column !== "archived" && this._column !== "done" && this._column !== "uncategorised" ? this._column : void 0,
      this.sourceColumnDefinitions
    );
    const destinationColumn = this.getColumnDefinition(column);
    if (sourceColumn && usesStatusMatching(sourceColumn)) {
      this._displayStatus = " ";
    }
    const sourcePrioritySchema = getColumnPrioritySchema(sourceColumn);
    if (sourceColumn && sourcePrioritySchema) {
      this.removePriorityPlacement(sourcePrioritySchema);
    }
    const destinationStatus = destinationColumn ? getColumnStatus(destinationColumn) : void 0;
    if (destinationStatus) {
      this._displayStatus = destinationStatus;
    }
    const destinationPriority = getColumnPriority(destinationColumn);
    if (destinationPriority && destinationColumn) {
      this.writePriorityPlacement(destinationPriority, getColumnPrioritySchema(destinationColumn));
    }
    this._column = column;
  }
  moveToUncategorised() {
    const sourceColumn = this.getColumnDefinition(
      this._column && this._column !== "archived" && this._column !== "done" && this._column !== "uncategorised" ? this._column : void 0,
      this.sourceColumnDefinitions
    );
    if (sourceColumn && usesStatusMatching(sourceColumn)) {
      this._displayStatus = " ";
    }
    const sourcePrioritySchema = getColumnPrioritySchema(sourceColumn);
    if (sourceColumn && sourcePrioritySchema) {
      this.removePriorityPlacement(sourcePrioritySchema);
    }
    this._column = void 0;
    this._done = false;
  }
  stripTagFromContent(value, tag2) {
    const escapedTag = escapeRegExp2(tag2);
    return value.replace(new RegExp(`(^|\\s)#${escapedTag}(?=$|\\s|[^-_/\\p{L}\\p{N}])`, "gu"), "$1").replace(/[ \t]{2,}/g, " ").trim();
  }
  replaceTag(oldTag, newTag) {
    if (oldTag) {
      this._tags.delete(oldTag);
      this.content = this.stripTagFromContent(this.content, oldTag);
    }
    if (newTag) {
      this._tags.add(newTag);
      const contentTags = Array.from(getTagsFromContent(this.content)).map((tag2) => tag2.toLowerCase());
      if (!this.consolidateTags && !contentTags.includes(newTag.toLowerCase())) {
        this.content = `${this.content.trim()} #${newTag}`.trim();
      }
    }
  }
  stripPlacementTags(value, placementTags) {
    return placementTags.reduce((nextValue, tag2) => this.stripTagFromContent(nextValue, tag2), value);
  }
  transformContentWithPropertyWriter(transform) {
    const rawLine = `- [ ] ${this.content.trim()}`;
    const transformed = transform(rawLine);
    const match = transformed.match(taskStringRegex);
    if (match == null ? void 0 : match[3]) {
      this.content = match[3];
    }
  }
  removePriorityPlacement(schema = getPriorityColumnContextSchema(this.propertySchemaOption)) {
    if (!schema) return;
    const adapter = getPropertyWriteAdapter(schema);
    if (!adapter) return;
    this.transformContentWithPropertyWriter((rawLine) => adapter.removePriority(rawLine));
  }
  writePriorityPlacement(priority, schema = getPriorityColumnContextSchema(this.propertySchemaOption)) {
    if (!schema) return;
    const adapter = getPropertyWriteAdapter(schema);
    if (!adapter) return;
    this.transformContentWithPropertyWriter((rawLine) => adapter.upsertPriority(rawLine, priority));
  }
  serialise() {
    if (this._deleted) {
      return "";
    }
    const placementTags = this.getCurrentPlacementTags();
    const currentColumnDefinition = this.getColumnDefinition(
      this.column && this.column !== "archived" && this.column !== "done" && this.column !== "uncategorised" ? this.column : void 0
    );
    const usesStatusPlacement = !!currentColumnDefinition && usesStatusMatching(currentColumnDefinition);
    const usesPriorityPlacement = !!currentColumnDefinition && usesPriorityMatching(currentColumnDefinition);
    const serialisedContent = placementTags.length > 0 ? this.stripPlacementTags(this.content.trim(), placementTags) : this.content.trim();
    const serialisedTags = this.consolidateTags ? Array.from(this.tags).filter((tag2) => !placementTags.includes(tag2)) : [];
    return [
      this.indentation,
      `- [${this._displayStatus}] `,
      serialisedContent,
      this.consolidateTags && serialisedTags.length > 0 ? ` ${serialisedTags.map((tag2) => `#${tag2}`).join(" ")}` : "",
      this.column ? this.column === "archived" ? ` #${this.column}` : usesStatusPlacement || usesPriorityPlacement ? "" : placementTags.length > 0 ? ` ${placementTags.map((tag2) => `#${tag2}`).join(" ")}` : ` #${this.column}` : "",
      this.blockLink ? ` ^${this.blockLink}` : ""
    ].join("").trimEnd();
  }
  get sourceBlockLineCount() {
    return 1 + flattenSourceBlockNodes(this.sourceChildren).length;
  }
  sourceBlockRows(serializedParent = this.serialise()) {
    return [
      serializedParent,
      ...flattenSourceBlockNodes(this.sourceChildren).map((node) => node.rawLine)
    ];
  }
  updateSourceBlockRowContent(rowIndex, content) {
    const node = this.findSourceBlockNode(rowIndex);
    if (!node) {
      return null;
    }
    if (node.kind === "raw") {
      if (content === "") {
        return "";
      }
      const rawListItemMatch = node.rawLine.slice(node.indentation.length).match(/^([-*+]\s+)(.+)$/);
      if (rawListItemMatch && !/^[-*+]\s+/.test(content)) {
        return `${node.indentation}${rawListItemMatch[1]}${content}`;
      }
      return `${node.indentation}${content}`;
    }
    const parsed = parseSourceTaskLine(node.rawLine);
    if (!parsed) {
      return null;
    }
    return `${parsed.indentation}${parsed.bullet} [${parsed.status}] ${content}`;
  }
  cycleSourceTaskRowStatus(rowIndex, statusMarkerOrder) {
    const node = this.findSourceBlockNode(rowIndex);
    if (!node || node.kind !== "task") {
      return null;
    }
    const parsed = parseSourceTaskLine(node.rawLine);
    if (!parsed) {
      return null;
    }
    const next2 = getNextStatusMarker(
      parsed.status || " ",
      this.doneStatusMarkers,
      statusMarkerOrder
    );
    return `${parsed.indentation}${parsed.bullet} [${next2.status}] ${parsed.content}`;
  }
  isSourceTaskStatusDone(status) {
    return isStatusMatch(status, this.doneStatusMarkers);
  }
  findSourceBlockNode(rowIndex) {
    var _a5;
    return (_a5 = flattenSourceBlockNodes(this.sourceChildren).find((node) => node.rowIndex === rowIndex)) != null ? _a5 : null;
  }
  serialiseForColumn(column) {
    const originalColumn = this._column;
    const originalDone = this._done;
    const originalDisplayStatus = this._displayStatus;
    const originalContent = this.content;
    if (column === "done") {
      this.done = true;
    } else if (column === "uncategorised") {
      this.moveToUncategorised();
    } else {
      this.column = column;
    }
    try {
      return this.serialise();
    } finally {
      this._column = originalColumn;
      this._done = originalDone;
      this._displayStatus = originalDisplayStatus;
      this.content = originalContent;
    }
  }
  archive() {
    const sourceColumn = this.getColumnDefinition(
      this._column && this._column !== "archived" && this._column !== "done" && this._column !== "uncategorised" ? this._column : void 0,
      this.sourceColumnDefinitions
    );
    const sourcePrioritySchema = getColumnPrioritySchema(sourceColumn);
    if (sourceColumn && sourcePrioritySchema) {
      this.removePriorityPlacement(sourcePrioritySchema);
    }
    if (!this._done) {
      this._displayStatus = "x";
    }
    this._done = true;
    this._column = "archived";
  }
  cancel() {
    var _a5;
    this._displayStatus = (_a5 = Array.from(this.cancelledStatusMarkers)[0]) != null ? _a5 : "-";
  }
  restore() {
    this._displayStatus = " ";
  }
  delete() {
    this._deleted = true;
  }
};
function isTrackedTaskString(input, ignoredStatusMarkers = DEFAULT_IGNORED_STATUS_MARKERS) {
  if (input.includes("#archived")) {
    return false;
  }
  const parsed = parseSourceTaskLine(input);
  if (!parsed) {
    return false;
  }
  if (isStatusMatch(parsed.status, ignoredStatusMarkers)) {
    return false;
  }
  return true;
}
var taskStringRegex = /^(\s*)[-*+]\s\[([^\[\]]*)\]\s(.+)/;
var blockLinkRegexp = /\s\^([a-zA-Z0-9-]+)$/;
function escapeRegExp2(input) {
  return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getTaskPriorityMatchValue(propertySchemaOption, properties) {
  const priority = properties.get("priority");
  if (propertySchemaOption === "tasks" /* TasksPlugin */ && typeof (priority == null ? void 0 : priority.value) === "number") {
    return getTasksPriorityValueFromWeight(priority.value);
  }
  if (propertySchemaOption === "dataview" /* Dataview */ && typeof (priority == null ? void 0 : priority.value) === "string") {
    return priority.value.trim();
  }
  return void 0;
}
function getPriorityColumnContextSchema(propertySchemaOption) {
  return propertySchemaOption === "tasks" /* TasksPlugin */ || propertySchemaOption === "dataview" /* Dataview */ ? propertySchemaOption : void 0;
}
function getTaskPriorityMatchValues(rawLine) {
  return {
    ["tasks" /* TasksPlugin */]: getTaskPriorityMatchValue(
      "tasks" /* TasksPlugin */,
      getSchemaImpl("tasks" /* TasksPlugin */).parseProperties(rawLine)
    ),
    ["dataview" /* Dataview */]: getTaskPriorityMatchValue(
      "dataview" /* Dataview */,
      getSchemaImpl("dataview" /* Dataview */).parseProperties(rawLine)
    )
  };
}

// src/ui/tasks/task_grouping.ts
var DEFAULT_GROUP_BUCKET_ID = "__default__";
function deriveGroupBuckets(tasks, source2, excludedTags = [], statusMarkerOrder = "", doneStatusMarkers = "", groupDirection = "asc") {
  var _a5;
  if (source2.kind === "file") {
    const paths = [...new Set(tasks.map((task) => task.path))].sort(
      (a, b) => a.localeCompare(b)
    );
    if (paths.length === 0) {
      return [
        {
          id: DEFAULT_GROUP_BUCKET_ID,
          label: "No files",
          value: null,
          source: source2,
          isDefault: true
        }
      ];
    }
    const buckets = paths.map((path) => ({
      id: createFileGroupBucketId(path),
      label: path,
      value: path,
      source: source2,
      isDefault: false
    }));
    return applyGroupDirection(buckets, groupDirection);
  }
  if (source2.kind === "tag-prefix") {
    const prefix = normalizeTagPrefix(source2.prefix);
    const excludeSet = createNormalizedTagSet(excludedTags);
    const tagMap = /* @__PURE__ */ new Map();
    for (const task of tasks) {
      for (const tag2 of task.tags) {
        if (isTagExcluded(tag2, excludeSet)) continue;
        if (prefix) {
          if (tag2.toLowerCase().startsWith(prefix)) {
            const suffix = tag2.slice(prefix.length);
            const key2 = suffix.toLowerCase();
            if (suffix && !tagMap.has(key2)) {
              tagMap.set(key2, tag2);
            }
          }
        } else {
          const key2 = tag2.toLowerCase();
          if (!tagMap.has(key2)) {
            tagMap.set(key2, tag2);
          }
        }
      }
    }
    const sortedFullTags = Array.from(tagMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map((entry) => entry[1]);
    const buckets = sortedFullTags.map((fullTag) => {
      const label = prefix ? fullTag.slice(prefix.length) : fullTag;
      return {
        id: createTagPrefixGroupBucketId(prefix, label.toLowerCase()),
        label,
        value: fullTag,
        source: { kind: "tag-prefix", prefix },
        isDefault: false
      };
    });
    buckets.push({
      id: createTagPrefixUnassignedGroupBucketId(prefix),
      label: "Unassigned",
      value: null,
      source: { kind: "tag-prefix", prefix },
      isDefault: true
    });
    return applyGroupDirection(buckets, groupDirection);
  }
  if (source2.kind === "property") {
    const valueMap = /* @__PURE__ */ new Map();
    let hasMissingValue = false;
    for (const task of tasks) {
      const property = task.properties.get(source2.key);
      const value = (_a5 = property == null ? void 0 : property.value) != null ? _a5 : null;
      if (value === null) {
        hasMissingValue = true;
        continue;
      }
      const key2 = propertyValueKey(value);
      if (!valueMap.has(key2)) {
        valueMap.set(key2, {
          value,
          label: property ? formatPropertyGroupLabel(property) : formatPropertyValueLabel(value)
        });
      }
    }
    const buckets = Array.from(valueMap.values()).sort((a, b) => comparePropertyGroupValues(
      source2.key,
      a.value,
      b.value,
      statusMarkerOrder,
      doneStatusMarkers
    )).map((entry) => ({
      id: createPropertyGroupBucketId(source2.key, entry.value),
      label: entry.label,
      value: entry.value,
      source: source2,
      isDefault: false
    }));
    if (hasMissingValue || buckets.length === 0) {
      buckets.push({
        id: createPropertyMissingGroupBucketId(source2.key),
        label: "Unassigned",
        value: null,
        source: source2,
        isDefault: true
      });
    }
    return applyGroupDirection(buckets, groupDirection);
  }
  return [
    {
      id: DEFAULT_GROUP_BUCKET_ID,
      label: "Default",
      value: null,
      source: source2,
      isDefault: true
    }
  ];
}
function applyGroupDirection(buckets, groupDirection) {
  return groupDirection === "desc" ? [...buckets].reverse() : buckets;
}
function getTaskTagGroupValue(task, source2, excludedTags = []) {
  return resolveTaskGroupTag(task, normalizeTagPrefix(source2.prefix), createNormalizedTagSet(excludedTags));
}
function resolveTaskGroupTag(task, prefix, excludeSet) {
  var _a5;
  const candidateTags = Array.from(task.tags).filter((tag2) => !isTagExcluded(tag2, excludeSet)).filter((tag2) => {
    if (!prefix) return true;
    return tag2.toLowerCase().startsWith(prefix) && tag2.slice(prefix.length).length > 0;
  });
  return (_a5 = candidateTags.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))[0]) != null ? _a5 : null;
}
function createGroupAssigner(buckets, source2, excludedTags = []) {
  var _a5;
  const defaultBucketId = (_a5 = buckets.find((bucket) => bucket.isDefault)) == null ? void 0 : _a5.id;
  if (source2.kind === "tag-prefix") {
    const prefix = normalizeTagPrefix(source2.prefix);
    const excludeSet = createNormalizedTagSet(excludedTags);
    const idByValue = /* @__PURE__ */ new Map();
    for (const bucket of buckets) {
      if (!bucket.isDefault && typeof bucket.value === "string") {
        idByValue.set(bucket.value.toLowerCase(), bucket.id);
      }
    }
    return (task) => {
      var _a6;
      const groupTag = resolveTaskGroupTag(task, prefix, excludeSet);
      if (groupTag === null) return defaultBucketId;
      return (_a6 = idByValue.get(groupTag.toLowerCase())) != null ? _a6 : defaultBucketId;
    };
  }
  if (source2.kind === "file") {
    const idByPath = /* @__PURE__ */ new Map();
    for (const bucket of buckets) {
      if (typeof bucket.value === "string") idByPath.set(bucket.value, bucket.id);
    }
    return (task) => {
      var _a6;
      return (_a6 = idByPath.get(task.path)) != null ? _a6 : defaultBucketId;
    };
  }
  if (source2.kind === "property") {
    const idByValue = /* @__PURE__ */ new Map();
    for (const bucket of buckets) {
      if (!bucket.isDefault && bucket.value !== null) {
        idByValue.set(propertyValueKey(bucket.value), bucket.id);
      }
    }
    return (task) => {
      var _a6, _b3, _c2;
      const value = (_b3 = (_a6 = task.properties.get(source2.key)) == null ? void 0 : _a6.value) != null ? _b3 : null;
      if (value === null) return defaultBucketId;
      return (_c2 = idByValue.get(propertyValueKey(value))) != null ? _c2 : defaultBucketId;
    };
  }
  return () => defaultBucketId;
}
function createFileGroupBucketId(path) {
  return `file:${path}`;
}
function createTagPrefixGroupBucketId(prefix, label) {
  return `tag-prefix:${prefix}:${label}`;
}
function createTagPrefixUnassignedGroupBucketId(prefix) {
  return createTagPrefixGroupBucketId(prefix, "__unassigned__");
}
function createPropertyGroupBucketId(key2, value) {
  return `property:${key2}:${propertyValueKey(value)}`;
}
function createPropertyMissingGroupBucketId(key2) {
  return `property:${key2}:__missing__`;
}
function propertyValueKey(value) {
  if (value instanceof Date) {
    return `date:${value.getTime()}`;
  }
  return `${typeof value}:${String(value).toLowerCase()}`;
}
function comparePropertyGroupValues(key2, a, b, statusMarkerOrder, doneStatusMarkers) {
  if (key2 === "priority") {
    return comparePriorityGroupValues(a, b);
  }
  if (key2 === UNIVERSAL_STATUS_PROPERTY_KEY) {
    return compareStatusMarkerValues(a, b, statusMarkerOrder, doneStatusMarkers);
  }
  return compareValues(a, b);
}
function comparePriorityGroupValues(a, b) {
  const aRank = priorityRank(a);
  const bRank = priorityRank(b);
  if (aRank !== null && bRank !== null && aRank !== bRank) {
    return bRank - aRank;
  }
  if (aRank !== null && bRank === null) return -1;
  if (aRank === null && bRank !== null) return 1;
  return compareValues(a, b);
}
function priorityRank(value) {
  if (typeof value === "number") {
    return value;
  }
  if (typeof value !== "string") {
    return null;
  }
  switch (value.trim().toLowerCase()) {
    case "highest":
      return 5;
    case "high":
      return 4;
    case "medium":
      return 3;
    case "low":
      return 2;
    case "lowest":
      return 1;
    default:
      return null;
  }
}
function formatPropertyGroupLabel(property) {
  if (property.key === "priority") {
    if (typeof property.value === "number") {
      return property.rawValue || formatPropertyValueLabel(property.value);
    }
    if (property.value !== null) {
      return String(property.value);
    }
    return property.rawValue;
  }
  return property.value === null ? property.rawValue : formatPropertyValueLabel(property.value);
}
function formatPropertyValueLabel(value) {
  if (value instanceof Date) {
    return value.toISOString().slice(0, 10);
  }
  return String(value);
}
function normalizeTagPrefix(prefix) {
  var _a5;
  return (_a5 = prefix == null ? void 0 : prefix.trim().replace(/^#/, "").toLowerCase()) != null ? _a5 : "";
}
function createNormalizedTagSet(tags) {
  return new Set(tags.map((tag2) => tag2.trim().replace(/^#/, "").toLowerCase()).filter(Boolean));
}
function isTagExcluded(tag2, excludeSet) {
  return excludeSet.has(tag2.toLowerCase());
}

// src/ui/settings/settings_store.ts
var VisibilityOption = /* @__PURE__ */ ((VisibilityOption2) => {
  VisibilityOption2["Auto"] = "auto";
  VisibilityOption2["NeverShow"] = "never";
  VisibilityOption2["AlwaysShow"] = "always";
  return VisibilityOption2;
})(VisibilityOption || {});
var ScopeOption = /* @__PURE__ */ ((ScopeOption2) => {
  ScopeOption2["Folder"] = "folder";
  ScopeOption2["Everywhere"] = "everywhere";
  ScopeOption2["SelectedFolders"] = "selectedFolders";
  return ScopeOption2;
})(ScopeOption || {});
var FlowDirection = /* @__PURE__ */ ((FlowDirection2) => {
  FlowDirection2["LeftToRight"] = "ltr";
  FlowDirection2["RightToLeft"] = "rtl";
  FlowDirection2["TopToBottom"] = "ttb";
  FlowDirection2["BottomToTop"] = "btt";
  return FlowDirection2;
})(FlowDirection || {});
var PropertyDisplayMode = /* @__PURE__ */ ((PropertyDisplayMode2) => {
  PropertyDisplayMode2["None"] = "none";
  PropertyDisplayMode2["Pretty"] = "pretty";
  PropertyDisplayMode2["Debug"] = "debug";
  return PropertyDisplayMode2;
})(PropertyDisplayMode || {});
var contentValueSchema = z.object({
  text: z.string()
});
var tagValueSchema = z.object({
  tags: z.array(z.string())
});
var fileValueSchema = z.object({
  filepaths: z.array(z.string())
});
var savedFilterSchema = z.object({
  id: z.string(),
  content: contentValueSchema.optional(),
  tag: tagValueSchema.optional(),
  file: fileValueSchema.optional()
});
var groupSourceSchema = z.union([
  z.object({ kind: z.literal("none") }),
  z.object({ kind: z.literal("file") }),
  z.object({ kind: z.literal("tag-prefix"), prefix: z.string().optional() }),
  z.object({ kind: z.literal("property"), key: z.string() })
]).catch({ kind: "none" });
var savedGroupingSchema = z.object({
  id: z.string(),
  name: z.string(),
  source: groupSourceSchema
});
var columnDefinitionSchema = z.object({
  id: z.string(),
  label: z.string(),
  color: z.string().optional(),
  matchMode: z.enum(["name", "tags", "status", "priority"]).default("name"),
  matchTags: z.array(z.string()).default([]),
  matchStatus: z.string().optional(),
  matchPriority: z.string().optional(),
  matchPropertySchema: z.enum(["tasks" /* TasksPlugin */, "dataview" /* Dataview */]).optional()
});
var manualOrderEntriesSchema = z.array(z.string());
var manualOrderCellSchema = z.record(z.string(), manualOrderEntriesSchema);
var manualOrderSchema = z.preprocess((value) => {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }
  const record = value;
  const hasFlatEntries = Object.values(record).some((entry) => Array.isArray(entry));
  if (hasFlatEntries) {
    const migrated = {};
    for (const [columnTag, entries] of Object.entries(record)) {
      if (Array.isArray(entries)) {
        migrated[columnTag] = entries;
      }
    }
    return { [DEFAULT_GROUP_BUCKET_ID]: migrated };
  }
  return value;
}, z.record(z.string(), manualOrderCellSchema));
var settingsObject = z.object({
  columns: z.array(z.union([z.string(), columnDefinitionSchema])),
  scope: z.nativeEnum(ScopeOption).catch("folder" /* Folder */),
  showFilepath: z.boolean().default(true).optional(),
  consolidateTags: z.boolean().default(false).optional(),
  uncategorizedVisibility: z.nativeEnum(VisibilityOption).catch("auto" /* Auto */).optional(),
  doneVisibility: z.nativeEnum(VisibilityOption).catch("always" /* AlwaysShow */).optional(),
  doneStatusMarkers: z.string().default(DEFAULT_DONE_STATUS_MARKERS).optional(),
  cancelledStatusMarkers: z.string().default(DEFAULT_CANCELLED_STATUS_MARKERS).optional(),
  ignoredStatusMarkers: z.string().default(DEFAULT_IGNORED_STATUS_MARKERS).optional(),
  statusMarkerOrder: z.string().default("").optional(),
  savedFilters: z.array(savedFilterSchema).default([]).optional(),
  savedGroupings: z.array(savedGroupingSchema).default([]).optional(),
  lastContentFilter: z.string().optional(),
  lastTagFilter: z.array(z.string()).optional(),
  lastFileFilter: z.array(z.string()).optional(),
  filtersExpanded: z.boolean().default(true).optional(),
  filtersSidebarExpanded: z.boolean().default(true).optional(),
  filtersSidebarWidth: z.number().default(280).optional(),
  columnWidth: z.number().min(200).max(600).catch(300).optional(),
  flowDirection: z.nativeEnum(FlowDirection).catch("ltr" /* LeftToRight */).optional(),
  collapsedColumns: z.array(z.string()).default([]).optional(),
  defaultTaskFile: z.string().default("").optional(),
  lastUsedTaskFile: z.string().default("").optional(),
  scopeFolders: z.array(z.string()).default([]).optional(),
  excludePaths: z.array(z.string()).default([]).optional(),
  excludedTags: z.array(z.string()).default([]).optional(),
  excludedTaskTags: z.array(z.string()).default([]).optional(),
  uncategorizedColumnName: z.string().default("Uncategorized").optional(),
  doneColumnName: z.string().default("Done").optional(),
  groupSource: groupSourceSchema.default({ kind: "none" }).optional(),
  propertySchema: z.nativeEnum(PropertySchemaOption).catch("none" /* None */).optional(),
  propertyDisplay: z.nativeEnum(PropertyDisplayMode).catch("none" /* None */).optional(),
  treatNestedTasksAsSubtasks: z.boolean().default(false).optional(),
  columnOrderMode: z.nativeEnum(ColumnOrderMode).catch("file" /* FileOrder */).optional(),
  sortProperty: z.string().nullable().default(null).optional(),
  sortDirection: z.enum(["asc", "desc"]).catch("asc").optional(),
  groupDirection: z.enum(["asc", "desc"]).catch("asc").optional(),
  // Cell-local manual ordering: group bucket id -> column id -> `path::blockLink`.
  // Stored alongside display settings in the board's frontmatter (the plugin has
  // no separate data file), but kept as its own field so it is never conflated
  // with display configuration. Legacy column-local records are migrated under
  // the default group bucket id at parse time.
  manualOrder: manualOrderSchema.default({}).optional()
});
var defaultSettings = {
  columns: createDefaultColumns(["Later", "Soonish", "Next week", "This week", "Today", "Pending"]),
  scope: "folder" /* Folder */,
  showFilepath: true,
  consolidateTags: false,
  uncategorizedVisibility: "auto" /* Auto */,
  doneVisibility: "always" /* AlwaysShow */,
  doneStatusMarkers: DEFAULT_DONE_STATUS_MARKERS,
  cancelledStatusMarkers: DEFAULT_CANCELLED_STATUS_MARKERS,
  ignoredStatusMarkers: DEFAULT_IGNORED_STATUS_MARKERS,
  statusMarkerOrder: "",
  savedFilters: [],
  lastContentFilter: "",
  lastTagFilter: [],
  lastFileFilter: [],
  columnWidth: 300,
  flowDirection: "ltr" /* LeftToRight */,
  collapsedColumns: [],
  defaultTaskFile: "",
  lastUsedTaskFile: "",
  scopeFolders: [],
  excludePaths: [],
  excludedTags: [],
  excludedTaskTags: [],
  uncategorizedColumnName: "Uncategorized",
  doneColumnName: "Done",
  groupSource: { kind: "none" },
  propertySchema: "none" /* None */,
  propertyDisplay: "none" /* None */,
  treatNestedTasksAsSubtasks: false,
  columnOrderMode: "file" /* FileOrder */,
  sortProperty: null,
  sortDirection: "asc",
  groupDirection: "asc",
  manualOrder: {}
};
var createSettingsStore = () => writable(defaultSettings);
function parseSettingsString(str2) {
  var _a5, _b3;
  try {
    const parsed = JSON.parse(str2);
    const partial = settingsObject.partial().parse(parsed);
    const columns = migrateColumnDefinitions(
      (_a5 = partial.columns) != null ? _a5 : defaultSettings.columns
    );
    const propertyDisplay = (_b3 = partial.propertyDisplay) != null ? _b3 : typeof (parsed == null ? void 0 : parsed.showProperties) === "boolean" ? parsed.showProperties ? "debug" /* Debug */ : "none" /* None */ : defaultSettings.propertyDisplay;
    return {
      ...defaultSettings,
      ...partial,
      columns,
      propertyDisplay,
      collapsedColumns: migrateCollapsedColumns(partial.collapsedColumns, columns)
    };
  } catch (e) {
    return defaultSettings;
  }
}
function toSettingsString(settings) {
  return JSON.stringify(settings);
}
function createDefaultColumns(labels) {
  const usedIds = /* @__PURE__ */ new Set();
  return labels.map((label) => ({
    id: createColumnId(label, usedIds),
    label,
    matchMode: "name",
    matchTags: [],
    matchStatus: void 0,
    matchPriority: void 0,
    matchPropertySchema: void 0
  }));
}

// src/ui/components/task_markdown.ts
function renderTaskMarkdownSource({
  content,
  displayStatus,
  blockLink,
  excludedTags = []
}) {
  let contentWithBlockLink = (content + (blockLink ? ` ^${blockLink}` : "")).replaceAll("<br />", "\n");
  for (const tag2 of excludedTags) {
    contentWithBlockLink = stripTagFromRenderedContent(contentWithBlockLink, tag2);
  }
  const indentedContinuationLines = contentWithBlockLink.replaceAll("\n", "\n  ");
  return `- [${displayStatus || " "}] ${indentedContinuationLines}`;
}
function stripTagFromRenderedContent(content, tag2) {
  const normalizedTag = tag2.trim().replace(/^#/, "");
  if (!normalizedTag) return content;
  const escapedTag = normalizedTag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return content.replace(new RegExp(`(^|\\s)#${escapedTag}(?=$|\\s|[^-_/\\p{L}\\p{N}])`, "giu"), "$1").trim();
}

// src/ui/components/task.svelte
var root10 = from_html(`<textarea></textarea>`);
var root_17 = from_html(`<div role="button" class="content-preview markdown-rendered svelte-1fvsaoa" tabindex="0"></div>`);
var root_25 = from_html(`<div><span role="button" tabindex="0"> </span> <div class="task-progress-bar-container svelte-1fvsaoa"><div class="task-progress-bar svelte-1fvsaoa"></div></div> <span class="task-progress-text svelte-1fvsaoa"> </span></div>`);
var root_33 = from_html(`<div class="task-row-content svelte-1fvsaoa"><!> <!></div>`);
var root_43 = from_html(`<button role="checkbox" tabindex="0"><!></button>`);
var root_52 = from_html(`<button role="checkbox" aria-label="Advance status" tabindex="0"><!></button>`);
var root_62 = from_html(`<button class="icon-button pin-marker svelte-1fvsaoa" aria-label="Unpin task (return to file order)" title="Pinned \u2014 click to unpin" tabindex="0"><!></button>`);
var root_72 = from_html(`<span class="drag-handle svelte-1fvsaoa" title="Drag to reorder" aria-hidden="true"><!></span>`);
var root_8 = from_html(`<!> <!> <!>`, 1);
var root_9 = from_html(`<div class="add-subtask-container svelte-1fvsaoa"><div class="add-subtask-btn svelte-1fvsaoa" role="button" tabindex="0"><span aria-hidden="true" class="svelte-1fvsaoa">+</span> Subtask</div></div>`);
var root_10 = from_html(`<!> <!>`, 1);
var root_11 = from_html(`<span class="svelte-1fvsaoa"><span class="cm-formatting cm-formatting-hashtag cm-hashtag cm-hashtag-begin cm-list-1 svelte-1fvsaoa">#</span><span class="cm-hashtag cm-hashtag-end cm-list-1 svelte-1fvsaoa"> </span></span>`);
var root_122 = from_html(`<div class="task-tags svelte-1fvsaoa"></div>`);
var root_132 = from_html(`<div class="task-properties-debug svelte-1fvsaoa"><pre class="svelte-1fvsaoa"><code> </code></pre></div>`);
var root_142 = from_html(`<span class="task-property-icon svelte-1fvsaoa"> </span>`);
var root_152 = from_html(`<span class="task-property-label svelte-1fvsaoa"> </span>`);
var root_162 = from_html(`<span class="task-property svelte-1fvsaoa"><!> <span class="task-property-value svelte-1fvsaoa"> </span></span>`);
var root_172 = from_html(`<div class="task-properties svelte-1fvsaoa"></div>`);
var root_18 = from_html(`<span><!> <span class="task-property-value svelte-1fvsaoa"> </span></span>`);
var root_19 = from_html(`<div class="task-properties task-date-properties svelte-1fvsaoa"><!></div>`);
var root_20 = from_html(`<div class="task-footer svelte-1fvsaoa"><button class="go-to-file-button svelte-1fvsaoa" aria-label="Go to file" title="Go to file" tabindex="0"><!> <span class="file-path svelte-1fvsaoa"> </span></button></div>`);
var root_21 = from_html(`<div role="group"><!> <!> <!> <!> <!> <!></div>`);
var $$css10 = {
  hash: "svelte-1fvsaoa",
  code: '.task.svelte-1fvsaoa {--task-accent: var(--task-accent-color, var(--background-modifier-border-hover));--task-content-line-height: 1.5rem;--task-footer-line-height: 1.15;--task-footer-block-padding: 2px;position:relative;overflow:hidden;background:var(--background-primary);border-radius:var(--radius-s);border:var(--border-width) solid var(--background-modifier-border);cursor:grab;box-shadow:0 1px 2px rgba(0, 0, 0, 0.06);transition:border-color 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease;}.task.svelte-1fvsaoa::before {content:"";position:absolute;inset:0 auto 0 0;width:8px;background:var(--task-accent);}.task.svelte-1fvsaoa:hover {border-color:color-mix(in srgb, var(--text-muted) 45%, var(--background-modifier-border));box-shadow:0 8px 22px rgba(0, 0, 0, 0.08);transform:translateY(-1px);}.task.is-dragging.svelte-1fvsaoa {opacity:0.15;}.task.is-selected.svelte-1fvsaoa {border-color:var(--interactive-accent);background:color-mix(in srgb, var(--interactive-accent) 8%, var(--background-primary));}.task.svelte-1fvsaoa .task-row-content:where(.svelte-1fvsaoa) {min-width:0;}.task.svelte-1fvsaoa .task-row-content:where(.svelte-1fvsaoa) textarea:where(.svelte-1fvsaoa) {cursor:text;background-color:var(--color-base-25);width:100%;}.task.svelte-1fvsaoa .task-row-content:where(.svelte-1fvsaoa) .content-preview:where(.svelte-1fvsaoa) {min-height:var(--task-content-line-height);}.task.svelte-1fvsaoa .task-row-content:where(.svelte-1fvsaoa) .content-preview:where(.svelte-1fvsaoa):focus {box-shadow:0 0 0 3px var(--background-modifier-border-focus);}.task.svelte-1fvsaoa .icon-button:where(.svelte-1fvsaoa) {display:flex;justify-content:center;align-items:center;width:20px;height:20px;padding:0;border:none;background:transparent;cursor:pointer;border-radius:var(--radius-s);transition:opacity 0.2s ease;box-shadow:none;overflow:visible;}.task.svelte-1fvsaoa .icon-button:where(.svelte-1fvsaoa):hover, .task.svelte-1fvsaoa .icon-button:where(.svelte-1fvsaoa):active {background:transparent;box-shadow:none;}.task.svelte-1fvsaoa .icon-button:where(.svelte-1fvsaoa):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}.task.svelte-1fvsaoa .icon-button.select-task:where(.svelte-1fvsaoa):hover svg {opacity:0.8 !important;color:var(--interactive-accent);}.task.svelte-1fvsaoa .icon-button.select-task.is-selected:where(.svelte-1fvsaoa) svg {color:var(--interactive-accent);}.task.svelte-1fvsaoa .icon-button.pin-marker:where(.svelte-1fvsaoa) svg {color:var(--interactive-accent);}.task.svelte-1fvsaoa .icon-button.pin-marker:where(.svelte-1fvsaoa):hover svg {opacity:1 !important;}.task.svelte-1fvsaoa .icon-button.usesStatusMarker:where(.svelte-1fvsaoa) {color:var(--text-normal);}.task.svelte-1fvsaoa .drag-handle:where(.svelte-1fvsaoa) {display:flex;align-items:center;justify-content:center;width:22px;height:22px;cursor:grab;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) {border-top:var(--border-width) solid var(--background-modifier-border);padding:var(--task-footer-block-padding) var(--size-4-2) var(--task-footer-block-padding) calc(var(--size-4-2) + 8px);font-size:var(--font-ui-smaller);line-height:var(--task-footer-line-height);display:flex;align-items:center;min-height:0;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa) {display:inline-flex;align-items:center;justify-content:flex-start;gap:var(--size-2-1);width:auto;max-width:100%;padding:0;min-height:0;height:auto;border:none;background:transparent;cursor:pointer;text-align:left;box-shadow:none;transition:opacity 0.2s ease;border-radius:var(--radius-s);font:inherit;line-height:inherit;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa):hover {background:transparent;box-shadow:none;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa):hover svg {opacity:1 !important;color:var(--interactive-accent);}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa):hover .file-path:where(.svelte-1fvsaoa) {color:var(--interactive-accent);}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa) .file-path:where(.svelte-1fvsaoa) {margin:0;color:var(--text-muted);transition:color 0.2s ease;overflow-wrap:anywhere;white-space:normal;min-width:0;line-height:inherit;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa) svg {width:1em;height:1em;}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) {display:flex;flex-wrap:wrap;gap:var(--size-2-1);padding:0 var(--size-4-2) var(--size-4-2) calc(var(--size-4-2) + 8px);margin-top:calc(-1 * var(--size-2-2));}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) span:where(.svelte-1fvsaoa) {background-color:var(--background-secondary);color:var(--text-muted);border:1px solid var(--background-modifier-border);border-radius:var(--radius-s);padding:1px 5px;font-size:var(--font-ui-smaller);line-height:1.1;display:inline-flex;align-items:center;transition:color 0.15s ease, border-color 0.15s ease;}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) span:where(.svelte-1fvsaoa):hover {color:var(--text-normal);border-color:var(--text-muted);}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) span:where(.svelte-1fvsaoa) .cm-formatting-hashtag {color:var(--text-accent) !important;font-weight:var(--font-medium);margin-right:1px;}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) span:where(.svelte-1fvsaoa) .cm-hashtag-end {color:inherit !important;}.task.svelte-1fvsaoa .task-properties-debug:where(.svelte-1fvsaoa) {padding:var(--size-2-3) var(--size-4-2) var(--size-2-3) calc(var(--size-4-2) + 8px);border-top:var(--border-width) solid var(--background-modifier-border);background-color:var(--background-secondary-alt);font-size:var(--font-ui-smaller);overflow-x:auto;}.task.svelte-1fvsaoa .task-properties-debug:where(.svelte-1fvsaoa) pre:where(.svelte-1fvsaoa) {margin:0;}.task.svelte-1fvsaoa .task-properties:where(.svelte-1fvsaoa) {display:flex;flex-wrap:wrap;gap:var(--size-2-2);padding:var(--task-footer-block-padding) var(--size-4-2) var(--task-footer-block-padding) calc(var(--size-4-2) + 8px);border-top:var(--border-width) solid var(--background-modifier-border);font-size:var(--font-ui-smaller);line-height:var(--task-footer-line-height);}.task.svelte-1fvsaoa .task-date-properties:where(.svelte-1fvsaoa) {align-items:center;}.task.svelte-1fvsaoa .task-date-properties:where(.svelte-1fvsaoa) .edit-mode {flex-basis:100%;}.task.svelte-1fvsaoa .task-property:where(.svelte-1fvsaoa) {display:inline-flex;align-items:baseline;gap:var(--size-2-1);padding:0 var(--size-2-2);border-radius:var(--radius-s);background-color:var(--background-secondary-alt);line-height:inherit;}.task.svelte-1fvsaoa .task-property-label:where(.svelte-1fvsaoa) {color:var(--text-muted);text-transform:uppercase;font-size:var(--font-smallest);letter-spacing:0.02em;}.task.svelte-1fvsaoa .task-property.dataview-property:where(.svelte-1fvsaoa) .task-property-label:where(.svelte-1fvsaoa) {text-transform:none;letter-spacing:0;}.task.svelte-1fvsaoa .task-property-icon:where(.svelte-1fvsaoa) {font-size:inherit;line-height:1;}.task.svelte-1fvsaoa .task-property-value:where(.svelte-1fvsaoa) {color:var(--text-normal);}.task-row-content img {max-width:100%;max-height:160px;object-fit:contain;}.task-row-content code {white-space:pre-wrap;}.task-row-content .content-preview,\n.task-row-content .content-preview > ul,\n.task-row-content .content-preview > ul > li,\n.task-row-content .content-preview > ul > li > p {margin:0;}.task .task-row-content .content-preview > ul {padding-left:0 !important;margin:0 !important;list-style:none !important;}.task-row-content .content-preview .task-list-item {min-width:0;word-break:break-word;padding-left:0 !important;list-style-type:none !important;}.task-row-content input.task-nested-checkbox {pointer-events:none;}.task-row-content .content-preview .task-list-item > input[type="checkbox"].task-primary-checkbox {display:none !important;}.task-row-content .content-preview .task-list-item > *:not(input[type="checkbox"]) {min-width:0;}.task-progress-wrapper.svelte-1fvsaoa {display:flex;align-items:center;gap:var(--size-4-2);margin-top:var(--size-2-2);margin-bottom:var(--size-2-1);}.task-progress-wrapper.is-complete.svelte-1fvsaoa .task-progress-bar:where(.svelte-1fvsaoa) {background-color:hsl(140, 75%, 45%);background-image:linear-gradient(90deg, hsl(140, 75%, 40%) 0%, hsl(140, 75%, 50%) 100%);box-shadow:0 0 6px hsla(140, 75%, 45%, 0.3);}.task-progress-wrapper.is-complete.svelte-1fvsaoa .task-progress-text:where(.svelte-1fvsaoa) {color:hsl(140, 75%, 45%);font-weight:var(--font-bold);}.task-progress-bar-container.svelte-1fvsaoa {flex:1;height:6px;background-color:var(--background-modifier-border);border-radius:3px;overflow:hidden;box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.05);}.task-progress-bar.svelte-1fvsaoa {height:100%;background-color:var(--interactive-accent);background-image:linear-gradient(90deg, hsla(var(--accent-h, 210), var(--accent-s, 75%), calc(var(--accent-l, 50%) - 5%), 0.95) 0%, var(--interactive-accent) 100%);border-radius:3px;transition:width 0.4s cubic-bezier(0.4, 0, 0.2, 1), background-color 0.3s ease, background-image 0.3s ease;box-shadow:0 1px 2px rgba(0, 0, 0, 0.1);}.task-progress-text.svelte-1fvsaoa {font-size:var(--font-ui-smaller);color:var(--text-muted);font-weight:var(--font-medium);white-space:nowrap;transition:color 0.3s ease;}.subtask-collapse-btn.svelte-1fvsaoa {background:transparent;border:none;box-shadow:none;padding:0;color:var(--text-muted);font-size:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;width:var(--task-line-marker-size, 20px);height:14px;line-height:1;flex-shrink:0;transition:color 0.15s ease;\n  /* Shift to the left under the checkbox */margin-left:calc(-1 * (var(--task-line-marker-size, 20px) + var(--task-line-column-gap, var(--size-2-3))));margin-right:var(--task-line-column-gap, var(--size-2-3));}.subtask-collapse-btn.svelte-1fvsaoa:hover {color:var(--text-normal);background:transparent;}.add-subtask-container.svelte-1fvsaoa {padding:var(--size-2-2) var(--size-4-2) var(--size-2-2) calc(var(--size-4-2) + 8px);}.add-subtask-btn.svelte-1fvsaoa {display:inline-flex;align-items:center;gap:var(--size-2-1);align-self:flex-start;cursor:pointer;border:0;border-radius:var(--radius-s);box-shadow:none;margin:0;min-height:22px;padding:0;background:transparent;background-color:transparent;color:var(--text-accent);font-size:var(--font-ui-smaller);font-weight:var(--font-medium);line-height:1.2;}.add-subtask-btn.svelte-1fvsaoa span:where(.svelte-1fvsaoa) {display:inline-flex;align-items:center;justify-content:center;font-size:var(--font-ui-small);line-height:1;}.add-subtask-btn.svelte-1fvsaoa:hover {color:var(--text-accent-hover);background:transparent;background-color:transparent;}.add-subtask-btn.svelte-1fvsaoa:active {color:var(--text-accent-hover);background:transparent;background-color:transparent;}'
};
function Task2($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Task2, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css10);
  const displayStatusIsCustom = mutable_source();
  const excludedTagNames = mutable_source();
  const visibleTags = mutable_source();
  const shouldconsolidateTags = mutable_source();
  const dateEditingEnabled = mutable_source();
  const displayProperties = mutable_source();
  const dateDisplayProperties = mutable_source();
  const nonDateDisplayProperties = mutable_source();
  const dateProperties = mutable_source();
  const visibleSubtasks = mutable_source();
  const totalSubtasksCount = mutable_source();
  const completedSubtasksCount = mutable_source();
  const completionPercentage = mutable_source();
  let app = prop($$props, "app", 12);
  let task = prop($$props, "task", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
  let showFilepath = prop($$props, "showFilepath", 12);
  let propertyDisplay = prop($$props, "propertyDisplay", 28, () => "none" /* None */);
  let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
  let consolidateTags = prop($$props, "consolidateTags", 12);
  let excludedTags = prop($$props, "excludedTags", 28, () => []);
  let displayColumn = prop($$props, "displayColumn", 12);
  let displaySecondaryId = prop($$props, "displaySecondaryId", 12);
  let isSelectionMode = prop($$props, "isSelectionMode", 12, false);
  let isSelected = prop($$props, "isSelected", 12, false);
  let onToggleSelection = prop($$props, "onToggleSelection", 12, () => {
  });
  let selectedTaskIds = prop($$props, "selectedTaskIds", 28, () => []);
  let taskSecondaryIds = prop($$props, "taskSecondaryIds", 28, () => ({}));
  let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
  let accentColor = prop($$props, "accentColor", 12, void 0);
  let isManualOrder = prop($$props, "isManualOrder", 12, false);
  let isPinned = prop($$props, "isPinned", 12, false);
  let showDragHandle = prop($$props, "showDragHandle", 12, false);
  let onUnpin = prop($$props, "onUnpin", 12, () => {
  });
  let treatNestedTasksAsSubtasks = prop($$props, "treatNestedTasksAsSubtasks", 12, false);
  function handleContentBlur() {
    var _a5;
    set(isEditing, false);
    const content = (_a5 = get(textAreaEl)) == null ? void 0 : _a5.value;
    if (!content) return;
    const updatedContent = content.replaceAll("\n", "<br />");
    taskActions().updateContent(task().id, updatedContent);
  }
  function handleKeypress(e) {
    var _a5;
    if (e.key === "Enter" && !e.shiftKey || e.key === "Escape") {
      (_a5 = get(textAreaEl)) == null ? void 0 : _a5.blur();
    }
  }
  function handleOpenKeypress(e) {
    if (e.key === "Enter" || e.key === " ") {
      handleFocus(e);
    }
  }
  let isEditing = mutable_source(false);
  let isDragging = mutable_source(false);
  let isSubtasksCollapsed = mutable_source(false);
  function toggleSubtasksCollapse() {
    set(isSubtasksCollapsed, !get(isSubtasksCollapsed));
  }
  function handleDragStart(e) {
    handleContentBlur();
    set(isDragging, true);
    const taskIds = isSelectionMode() && isSelected() && selectedTaskIds().length > 0 ? selectedTaskIds() : [task().id];
    isDraggingStore.set({
      fromColumn: displayColumn(),
      fromSecondaryId: displaySecondaryId(),
      draggedTaskIds: taskIds,
      taskSecondaryIds: taskSecondaryIds()
    });
    if (e.dataTransfer) {
      e.dataTransfer.setData("text/plain", task().id);
      e.dataTransfer.dropEffect = "move";
    }
    if (taskIds.length > 1 && e.dataTransfer) {
      const ghost = document.createElement("div");
      ghost.textContent = `Moving ${taskIds.length} tasks`;
      ghost.style.cssText = [
        "position:fixed",
        "top:-9999px",
        "left:-9999px",
        "padding:6px 12px",
        "background:var(--background-secondary-alt)",
        "border:1px solid var(--background-modifier-border)",
        "border-radius:var(--radius-m)",
        "font-size:var(--font-ui-small)",
        "color:var(--text-normal)",
        "box-shadow:var(--shadow-s)",
        "white-space:nowrap"
      ].join(";");
      document.body.appendChild(ghost);
      e.dataTransfer.setDragImage(ghost, 0, 0);
      setTimeout(() => document.body.removeChild(ghost), 0);
    }
  }
  function handleDragEnd() {
    set(isDragging, false);
    isDraggingStore.set(null);
  }
  let textAreaEl = mutable_source();
  let previewContainerEl = mutable_source();
  let markdownComponent;
  let isEditingDates = mutable_source(false);
  const editableDatePropertyKeys = /* @__PURE__ */ new Set(["due", "scheduled", "start"]);
  const interactiveTagNames = /* @__PURE__ */ new Set([
    "a",
    "button",
    "input",
    "select",
    "textarea",
    "label",
    "summary",
    "details"
  ]);
  function eventHasInteractiveTarget(e) {
    if (e instanceof MouseEvent && get(previewContainerEl)) {
      const rect = get(previewContainerEl).getBoundingClientRect();
      const relativeX = e.clientX - rect.left;
      if (relativeX >= 0 && relativeX < 28) {
        return true;
      }
    }
    const path = (e == null ? void 0 : e.composedPath()) || [];
    const currentTarget = e == null ? void 0 : e.currentTarget;
    for (const element2 of path) {
      if (!(element2 instanceof HTMLElement)) {
        continue;
      }
      if (currentTarget instanceof HTMLElement && element2 === currentTarget) {
        continue;
      }
      if (interactiveTagNames.has(element2.tagName.toLowerCase())) {
        return true;
      }
      if (element2.isContentEditable) {
        return true;
      }
      const role = element2.getAttribute("role");
      if (role === "button" || role === "checkbox" || role === "link") {
        return true;
      }
    }
    return false;
  }
  function handleFocus(e) {
    if (eventHasInteractiveTarget(e)) {
      return;
    }
    set(isEditing, true);
    setTimeout(
      () => {
        var _a5;
        (_a5 = get(textAreaEl)) == null ? void 0 : _a5.focus();
      },
      100
    );
  }
  function renderTaskMarkdown() {
    let body = task().content;
    if (task().properties) {
      if (propertyDisplay() === "pretty" /* Pretty */) {
        body = stripDisplayedPropertiesFromContent(body, task().properties);
      } else if (get(dateEditingEnabled)) {
        body = stripDisplayedPropertiesFromContent(body, get(dateProperties));
      }
    }
    return renderTaskMarkdownSource({
      content: body,
      displayStatus: task().displayStatus,
      blockLink: task().blockLink,
      excludedTags: excludedTags()
    });
  }
  async function renderMarkdown(selectionMode) {
    if (!get(previewContainerEl)) return;
    if (markdownComponent) {
      markdownComponent.unload();
    }
    get(previewContainerEl).empty();
    markdownComponent = new import_obsidian6.Component();
    const contentToRender = renderTaskMarkdown();
    await import_obsidian6.MarkdownRenderer.render(app(), contentToRender, get(previewContainerEl), task().path, markdownComponent);
    setupLinkHandlers();
    postProcessRenderedContent(selectionMode);
  }
  function setupLinkHandlers() {
    if (!get(previewContainerEl)) return;
    const internalLinks = get(previewContainerEl).querySelectorAll("a.internal-link");
    internalLinks.forEach((link2) => {
      const anchorEl = link2;
      anchorEl.addEventListener("click", (e) => {
        e.preventDefault();
        e.stopPropagation();
        const linkTarget = anchorEl.getAttribute("data-href");
        if (linkTarget && app()) {
          app().workspace.openLinkText(linkTarget, task().path, import_obsidian6.Keymap.isModEvent(e));
        }
      });
      anchorEl.addEventListener("mouseover", (e) => {
        const linkTarget = anchorEl.getAttribute("data-href");
        if (linkTarget && app() && get(previewContainerEl)) {
          app().workspace.trigger("hover-link", {
            event: e,
            source: "kanban-view",
            hoverParent: get(previewContainerEl),
            targetEl: anchorEl,
            linktext: linkTarget,
            sourcePath: task().path
          });
        }
      });
    });
  }
  function postProcessRenderedContent(selectionMode) {
    if (!get(previewContainerEl)) return;
    function stopPropagation2(e) {
      e.stopPropagation();
    }
    function handlePrimaryCheckboxClick(e) {
      e.preventDefault();
      e.stopPropagation();
      void taskActions().toggleDone(task().id);
    }
    get(previewContainerEl).querySelectorAll("a:not(.internal-link)").forEach((a) => {
      const anchor = a;
      anchor.target = "_blank";
      anchor.rel = "noopener noreferrer";
      anchor.addEventListener("click", stopPropagation2);
      anchor.addEventListener("keypress", stopPropagation2);
    });
    const checkboxes = Array.from(get(previewContainerEl).querySelectorAll('input[type="checkbox"]'));
    const [primaryCheckbox, ...nestedCheckboxes] = checkboxes;
    if (primaryCheckbox) {
      primaryCheckbox.classList.add("task-primary-checkbox");
      primaryCheckbox.addEventListener("mousedown", stopPropagation2);
      primaryCheckbox.addEventListener("mouseup", stopPropagation2);
      primaryCheckbox.addEventListener("keypress", stopPropagation2);
      if (selectionMode) {
        primaryCheckbox.disabled = true;
        primaryCheckbox.tabIndex = -1;
        primaryCheckbox.style.visibility = "hidden";
        primaryCheckbox.setAttribute("aria-hidden", "true");
        primaryCheckbox.addEventListener("click", stopPropagation2);
      } else {
        primaryCheckbox.disabled = false;
        primaryCheckbox.style.removeProperty("visibility");
        primaryCheckbox.removeAttribute("aria-hidden");
        primaryCheckbox.setAttribute("aria-label", "Advance status");
        primaryCheckbox.addEventListener("click", handlePrimaryCheckboxClick);
      }
    }
    nestedCheckboxes.forEach((checkbox) => {
      checkbox.classList.add("task-nested-checkbox");
      checkbox.disabled = true;
      checkbox.tabIndex = -1;
      checkbox.addEventListener("click", stopPropagation2);
      checkbox.addEventListener("keypress", stopPropagation2);
    });
    get(previewContainerEl).querySelectorAll("iframe, audio, video").forEach((el) => {
      el.remove();
    });
  }
  onDestroy(() => {
    if (markdownComponent) {
      markdownComponent.unload();
    }
  });
  function onInput(e) {
    e.currentTarget.style.height = `0px`;
    e.currentTarget.style.height = `${e.currentTarget.scrollHeight}px`;
  }
  legacy_pre_effect(() => deep_read_state(task()), () => {
    set(displayStatusIsCustom, task().displayStatus !== " ");
  });
  legacy_pre_effect(
    () => (deep_read_state(task()), deep_read_state(propertyDisplay()), get(isEditing), get(previewContainerEl), deep_read_state(isSelectionMode())),
    () => {
      if (task() && task().content && task().displayStatus && propertyDisplay() && !get(isEditing) && get(previewContainerEl)) {
        void renderMarkdown(isSelectionMode());
      }
    }
  );
  legacy_pre_effect(() => get(textAreaEl), () => {
    if (get(textAreaEl)) {
      mutate(textAreaEl, get(textAreaEl).style.height = `0px`);
      mutate(textAreaEl, get(textAreaEl).style.height = `${get(textAreaEl).scrollHeight}px`);
    }
  });
  legacy_pre_effect(() => deep_read_state(excludedTags()), () => {
    set(excludedTagNames, excludedTags().map((tag2) => tag2.trim().replace(/^#/, "").toLowerCase()));
  });
  legacy_pre_effect(() => (deep_read_state(task()), get(excludedTagNames)), () => {
    set(visibleTags, Array.from(task().tags).filter((t) => !get(excludedTagNames).includes(t.toLowerCase())));
  });
  legacy_pre_effect(() => (deep_read_state(consolidateTags()), get(visibleTags)), () => {
    set(shouldconsolidateTags, consolidateTags() && get(visibleTags).length > 0);
  });
  legacy_pre_effect(
    () => (getPropertyWriteAdapter, deep_read_state(propertySchemaOption())),
    () => {
      set(dateEditingEnabled, getPropertyWriteAdapter(propertySchemaOption()) !== null);
    }
  );
  legacy_pre_effect(() => (deep_read_state(task()), toDisplayProperties), () => {
    set(displayProperties, task().properties ? toDisplayProperties(task().properties) : []);
  });
  legacy_pre_effect(
    () => (get(dateEditingEnabled), get(displayProperties), deep_read_state(propertySchemaOption()), PropertySchemaOption),
    () => {
      set(dateDisplayProperties, get(dateEditingEnabled) ? get(displayProperties).filter((prop2) => editableDatePropertyKeys.has(prop2.key)).map((prop2) => propertySchemaOption() === "dataview" /* Dataview */ ? { ...prop2, icon: void 0, label: `${prop2.key}::` } : prop2) : []);
    }
  );
  legacy_pre_effect(() => get(displayProperties), () => {
    set(nonDateDisplayProperties, get(displayProperties).filter((prop2) => !editableDatePropertyKeys.has(prop2.key)));
  });
  legacy_pre_effect(() => deep_read_state(task()), () => {
    var _a5, _b3;
    set(dateProperties, new Map(Array.from((_b3 = (_a5 = task().properties) == null ? void 0 : _a5.entries()) != null ? _b3 : []).filter(([key2]) => editableDatePropertyKeys.has(key2))));
  });
  legacy_pre_effect(() => (getVisibleSourceTaskDescendants, deep_read_state(task())), () => {
    set(visibleSubtasks, getVisibleSourceTaskDescendants(task().sourceChildren));
  });
  legacy_pre_effect(() => get(visibleSubtasks), () => {
    set(totalSubtasksCount, get(visibleSubtasks).length);
  });
  legacy_pre_effect(() => (get(visibleSubtasks), deep_read_state(task())), () => {
    set(completedSubtasksCount, get(visibleSubtasks).filter((node) => task().isSourceTaskStatusDone(node.status)).length);
  });
  legacy_pre_effect(() => (get(totalSubtasksCount), get(completedSubtasksCount)), () => {
    set(completionPercentage, get(totalSubtasksCount) > 0 ? Math.round(get(completedSubtasksCount) / get(totalSubtasksCount) * 100) : 0);
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get app() {
      return app();
    },
    set app($$value) {
      app($$value);
      flushSync();
    },
    get task() {
      return task();
    },
    set task($$value) {
      task($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get columnTagTableStore() {
      return columnTagTableStore();
    },
    set columnTagTableStore($$value) {
      columnTagTableStore($$value);
      flushSync();
    },
    get showFilepath() {
      return showFilepath();
    },
    set showFilepath($$value) {
      showFilepath($$value);
      flushSync();
    },
    get propertyDisplay() {
      return propertyDisplay();
    },
    set propertyDisplay($$value) {
      propertyDisplay($$value);
      flushSync();
    },
    get propertySchemaOption() {
      return propertySchemaOption();
    },
    set propertySchemaOption($$value) {
      propertySchemaOption($$value);
      flushSync();
    },
    get consolidateTags() {
      return consolidateTags();
    },
    set consolidateTags($$value) {
      consolidateTags($$value);
      flushSync();
    },
    get excludedTags() {
      return excludedTags();
    },
    set excludedTags($$value) {
      excludedTags($$value);
      flushSync();
    },
    get displayColumn() {
      return displayColumn();
    },
    set displayColumn($$value) {
      displayColumn($$value);
      flushSync();
    },
    get displaySecondaryId() {
      return displaySecondaryId();
    },
    set displaySecondaryId($$value) {
      displaySecondaryId($$value);
      flushSync();
    },
    get isSelectionMode() {
      return isSelectionMode();
    },
    set isSelectionMode($$value) {
      isSelectionMode($$value);
      flushSync();
    },
    get isSelected() {
      return isSelected();
    },
    set isSelected($$value) {
      isSelected($$value);
      flushSync();
    },
    get onToggleSelection() {
      return onToggleSelection();
    },
    set onToggleSelection($$value) {
      onToggleSelection($$value);
      flushSync();
    },
    get selectedTaskIds() {
      return selectedTaskIds();
    },
    set selectedTaskIds($$value) {
      selectedTaskIds($$value);
      flushSync();
    },
    get taskSecondaryIds() {
      return taskSecondaryIds();
    },
    set taskSecondaryIds($$value) {
      taskSecondaryIds($$value);
      flushSync();
    },
    get doneColumnName() {
      return doneColumnName();
    },
    set doneColumnName($$value) {
      doneColumnName($$value);
      flushSync();
    },
    get accentColor() {
      return accentColor();
    },
    set accentColor($$value) {
      accentColor($$value);
      flushSync();
    },
    get isManualOrder() {
      return isManualOrder();
    },
    set isManualOrder($$value) {
      isManualOrder($$value);
      flushSync();
    },
    get isPinned() {
      return isPinned();
    },
    set isPinned($$value) {
      isPinned($$value);
      flushSync();
    },
    get showDragHandle() {
      return showDragHandle();
    },
    set showDragHandle($$value) {
      showDragHandle($$value);
      flushSync();
    },
    get onUnpin() {
      return onUnpin();
    },
    set onUnpin($$value) {
      onUnpin($$value);
      flushSync();
    },
    get treatNestedTasksAsSubtasks() {
      return treatNestedTasksAsSubtasks();
    },
    set treatNestedTasksAsSubtasks($$value) {
      treatNestedTasksAsSubtasks($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root_21();
  let classes;
  let styles;
  var node_1 = child(div);
  TaskLineRow(node_1, {
    variant: "card",
    hasActions: true,
    children: ($$anchor2, $$slotProps) => {
      var div_1 = root_33();
      var node_2 = child(div_1);
      {
        var consequent = ($$anchor3) => {
          var textarea = root10();
          remove_textarea_child(textarea);
          let classes_1;
          bind_this(textarea, ($$value) => set(textAreaEl, $$value), () => get(textAreaEl));
          template_effect(
            ($0) => {
              set_value(textarea, $0);
              classes_1 = set_class(textarea, 1, "svelte-1fvsaoa", null, classes_1, { editing: get(isEditing) });
            },
            [
              () => (deep_read_state(task()), untrack(() => task().content.replaceAll("<br />", "\n")))
            ]
          );
          event("keypress", textarea, handleKeypress);
          event("blur", textarea, handleContentBlur);
          event("input", textarea, onInput);
          append($$anchor3, textarea);
        };
        var alternate = ($$anchor3) => {
          var div_2 = root_17();
          bind_this(div_2, ($$value) => set(previewContainerEl, $$value), () => get(previewContainerEl));
          event("mouseup", div_2, handleFocus);
          event("keypress", div_2, handleOpenKeypress);
          append($$anchor3, div_2);
        };
        if_block(node_2, ($$render) => {
          if (get(isEditing)) $$render(consequent);
          else $$render(alternate, -1);
        });
      }
      var node_3 = sibling(node_2, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var div_3 = root_25();
          let classes_2;
          var span = child(div_3);
          let classes_3;
          var text2 = child(span, true);
          reset(span);
          var div_4 = sibling(span, 2);
          var div_5 = child(div_4);
          reset(div_4);
          var span_1 = sibling(div_4, 2);
          var text_1 = child(span_1);
          reset(span_1);
          reset(div_3);
          template_effect(() => {
            var _a5, _b3, _c2, _d;
            classes_2 = set_class(div_3, 1, "task-progress-wrapper svelte-1fvsaoa", null, classes_2, { "is-complete": get(completionPercentage) === 100 });
            classes_3 = set_class(span, 1, "subtask-collapse-btn svelte-1fvsaoa", null, classes_3, { collapsed: get(isSubtasksCollapsed) });
            set_attribute2(span, "aria-label", get(isSubtasksCollapsed) ? "Expand subtasks" : "Collapse subtasks");
            set_text(text2, get(isSubtasksCollapsed) ? "\u25B6" : "\u25BC");
            set_style(div_5, `width: ${(_a5 = get(completionPercentage)) != null ? _a5 : ""}%`);
            set_text(text_1, `${(_b3 = get(completedSubtasksCount)) != null ? _b3 : ""}/${(_c2 = get(totalSubtasksCount)) != null ? _c2 : ""} (${(_d = get(completionPercentage)) != null ? _d : ""}%)`);
          });
          event("click", span, stopPropagation(toggleSubtasksCollapse));
          event("keydown", span, stopPropagation((e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              toggleSubtasksCollapse();
            }
          }));
          append($$anchor3, div_3);
        };
        if_block(node_3, ($$render) => {
          if (treatNestedTasksAsSubtasks() && get(totalSubtasksCount) > 0) $$render(consequent_1);
        });
      }
      reset(div_1);
      append($$anchor2, div_1);
    },
    $$slots: {
      default: true,
      marker: ($$anchor2, $$slotProps) => {
        var fragment = comment();
        var node_4 = first_child(fragment);
        {
          var consequent_2 = ($$anchor3) => {
            var button = root_43();
            let classes_4;
            var node_5 = child(button);
            {
              let $0 = derived_safe_equal(() => isSelected() ? "lucide-check-circle" : "lucide-circle");
              let $1 = derived_safe_equal(() => isSelected() ? 1 : 0.5);
              Icon(node_5, {
                get name() {
                  return get($0);
                },
                size: 18,
                get opacity() {
                  return get($1);
                }
              });
            }
            reset(button);
            template_effect(() => {
              classes_4 = set_class(button, 1, "icon-button select-task svelte-1fvsaoa", null, classes_4, { "is-selected": isSelected() });
              set_attribute2(button, "aria-label", isSelected() ? "Deselect for bulk actions" : "Select for bulk actions");
              set_attribute2(button, "aria-checked", isSelected());
            });
            event("click", button, function(...$$args) {
              var _a5;
              (_a5 = onToggleSelection()) == null ? void 0 : _a5.apply(this, $$args);
            });
            event("keydown", button, (e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                onToggleSelection()();
              }
            });
            append($$anchor3, button);
          };
          var alternate_1 = ($$anchor3) => {
            var button_1 = root_52();
            let classes_5;
            var node_6 = child(button_1);
            TaskStatusMarker(node_6, {
              get status() {
                return deep_read_state(task()), untrack(() => task().displayStatus);
              },
              get isDone() {
                return deep_read_state(task()), untrack(() => task().done);
              },
              size: 16
            });
            reset(button_1);
            template_effect(() => {
              classes_5 = set_class(button_1, 1, "icon-button toggle-done-task svelte-1fvsaoa", null, classes_5, {
                "is-done": task().done,
                usesStatusMarker: get(displayStatusIsCustom)
              });
              set_attribute2(button_1, "aria-checked", (deep_read_state(task()), untrack(() => task().done)));
            });
            event("click", button_1, () => void taskActions().toggleDone(task().id));
            event("keydown", button_1, (e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                void taskActions().toggleDone(task().id);
              }
            });
            append($$anchor3, button_1);
          };
          if_block(node_4, ($$render) => {
            if (isSelectionMode()) $$render(consequent_2);
            else $$render(alternate_1, -1);
          });
        }
        append($$anchor2, fragment);
      },
      actions: ($$anchor2, $$slotProps) => {
        var fragment_1 = root_8();
        var node_7 = first_child(fragment_1);
        {
          var consequent_3 = ($$anchor3) => {
            var button_2 = root_62();
            var node_8 = child(button_2);
            Icon(node_8, { name: "lucide-pin", size: 16, opacity: 0.9 });
            reset(button_2);
            event("click", button_2, stopPropagation(function(...$$args) {
              var _a5;
              (_a5 = onUnpin()) == null ? void 0 : _a5.apply(this, $$args);
            }));
            event("keydown", button_2, (e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                e.stopPropagation();
                onUnpin()();
              }
            });
            append($$anchor3, button_2);
          };
          if_block(node_7, ($$render) => {
            if (isManualOrder() && isPinned()) $$render(consequent_3);
          });
        }
        var node_9 = sibling(node_7, 2);
        {
          var consequent_4 = ($$anchor3) => {
            var span_2 = root_72();
            var node_10 = child(span_2);
            Icon(node_10, { name: "lucide-grip-vertical", size: 16, opacity: 0.5 });
            reset(span_2);
            append($$anchor3, span_2);
          };
          if_block(node_9, ($$render) => {
            if (isManualOrder() && showDragHandle()) $$render(consequent_4);
          });
        }
        var node_11 = sibling(node_9, 2);
        Task_menu(node_11, {
          get task() {
            return task();
          },
          get taskActions() {
            return taskActions();
          },
          get columnTagTableStore() {
            return columnTagTableStore();
          },
          get doneColumnName() {
            return doneColumnName();
          }
        });
        append($$anchor2, fragment_1);
      }
    }
  });
  var node_12 = sibling(node_1, 2);
  {
    var consequent_7 = ($$anchor2) => {
      var fragment_2 = root_10();
      var node_13 = first_child(fragment_2);
      {
        var consequent_5 = ($$anchor3) => {
          TaskSourceRows($$anchor3, {
            get app() {
              return app();
            },
            get task() {
              return task();
            },
            get taskActions() {
              return taskActions();
            },
            get nodes() {
              return deep_read_state(task()), untrack(() => task().sourceChildren);
            },
            get isSelectionMode() {
              return isSelectionMode();
            },
            depth: 1
          });
        };
        if_block(node_13, ($$render) => {
          if (deep_read_state(task()), untrack(() => task().sourceChildren.length > 0)) $$render(consequent_5);
        });
      }
      var node_14 = sibling(node_13, 2);
      {
        var consequent_6 = ($$anchor3) => {
          var div_6 = root_9();
          var div_7 = child(div_6);
          reset(div_6);
          event("click", div_7, stopPropagation(() => void taskActions().addSourceBlockRow(task().id, task().rowIndex, "child", "task")));
          event("keydown", div_7, stopPropagation((e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              void taskActions().addSourceBlockRow(task().id, task().rowIndex, "child", "task");
            }
          }));
          append($$anchor3, div_6);
        };
        if_block(node_14, ($$render) => {
          if (treatNestedTasksAsSubtasks()) $$render(consequent_6);
        });
      }
      append($$anchor2, fragment_2);
    };
    if_block(node_12, ($$render) => {
      if (!get(isSubtasksCollapsed)) $$render(consequent_7);
    });
  }
  var node_15 = sibling(node_12, 2);
  {
    var consequent_8 = ($$anchor2) => {
      var div_8 = root_122();
      each(div_8, 5, () => get(visibleTags), index, ($$anchor3, tag2) => {
        var span_3 = root_11();
        var span_4 = sibling(child(span_3));
        var text_2 = child(span_4, true);
        reset(span_4);
        reset(span_3);
        template_effect(() => set_text(text_2, get(tag2)));
        append($$anchor3, span_3);
      });
      reset(div_8);
      append($$anchor2, div_8);
    };
    if_block(node_15, ($$render) => {
      if (get(shouldconsolidateTags)) $$render(consequent_8);
    });
  }
  var node_16 = sibling(node_15, 2);
  {
    var consequent_9 = ($$anchor2) => {
      var div_9 = root_132();
      var pre = child(div_9);
      var code = child(pre);
      var text_3 = child(code, true);
      reset(code);
      reset(pre);
      reset(div_9);
      template_effect(($0) => set_text(text_3, $0), [
        () => (deep_read_state(task()), untrack(() => JSON.stringify(Array.from(task().properties.entries()), null, 2)))
      ]);
      append($$anchor2, div_9);
    };
    var consequent_12 = ($$anchor2) => {
      var fragment_4 = comment();
      var node_17 = first_child(fragment_4);
      {
        var consequent_11 = ($$anchor3) => {
          var div_10 = root_172();
          each(div_10, 5, () => get(nonDateDisplayProperties), (prop2) => prop2.key, ($$anchor4, prop2) => {
            var span_5 = root_162();
            var node_18 = child(span_5);
            {
              var consequent_10 = ($$anchor5) => {
                var span_6 = root_142();
                var text_4 = child(span_6, true);
                reset(span_6);
                template_effect(() => {
                  set_attribute2(span_6, "title", (get(prop2), untrack(() => get(prop2).label)));
                  set_attribute2(span_6, "aria-label", (get(prop2), untrack(() => get(prop2).label)));
                  set_text(text_4, (get(prop2), untrack(() => get(prop2).icon)));
                });
                append($$anchor5, span_6);
              };
              var alternate_2 = ($$anchor5) => {
                var span_7 = root_152();
                var text_5 = child(span_7, true);
                reset(span_7);
                template_effect(() => set_text(text_5, (get(prop2), untrack(() => get(prop2).label))));
                append($$anchor5, span_7);
              };
              if_block(node_18, ($$render) => {
                if (get(prop2), untrack(() => get(prop2).icon)) $$render(consequent_10);
                else $$render(alternate_2, -1);
              });
            }
            var span_8 = sibling(node_18, 2);
            var text_6 = child(span_8, true);
            reset(span_8);
            reset(span_5);
            template_effect(() => set_text(text_6, (get(prop2), untrack(() => get(prop2).value))));
            append($$anchor4, span_5);
          });
          reset(div_10);
          append($$anchor3, div_10);
        };
        if_block(node_17, ($$render) => {
          if (get(nonDateDisplayProperties), untrack(() => get(nonDateDisplayProperties).length > 0)) $$render(consequent_11);
        });
      }
      append($$anchor2, fragment_4);
    };
    if_block(node_16, ($$render) => {
      if (deep_read_state(propertyDisplay()), deep_read_state(PropertyDisplayMode), deep_read_state(task()), untrack(() => propertyDisplay() === "debug" /* Debug */ && task().properties && task().properties.size > 0)) $$render(consequent_9);
      else if (deep_read_state(propertyDisplay()), deep_read_state(PropertyDisplayMode), deep_read_state(task()), untrack(() => propertyDisplay() === "pretty" /* Pretty */ && task().properties)) $$render(consequent_12, 1);
    });
  }
  var node_19 = sibling(node_16, 2);
  {
    var consequent_15 = ($$anchor2) => {
      var div_11 = root_19();
      var node_20 = child(div_11);
      {
        var consequent_14 = ($$anchor3) => {
          var fragment_5 = root_10();
          var node_21 = first_child(fragment_5);
          TaskDateFields(node_21, {
            get task() {
              return task();
            },
            get taskActions() {
              return taskActions();
            },
            get propertySchemaOption() {
              return propertySchemaOption();
            },
            get isTaskEditing() {
              return get(isEditing);
            },
            get isEditingDates() {
              return get(isEditingDates);
            },
            set isEditingDates($$value) {
              set(isEditingDates, $$value);
            },
            $$legacy: true
          });
          var node_22 = sibling(node_21, 2);
          each(node_22, 1, () => get(dateDisplayProperties), (prop2) => prop2.key, ($$anchor4, prop2) => {
            var span_9 = root_18();
            let classes_6;
            var node_23 = child(span_9);
            {
              var consequent_13 = ($$anchor5) => {
                var span_10 = root_142();
                var text_7 = child(span_10, true);
                reset(span_10);
                template_effect(() => {
                  set_attribute2(span_10, "title", (get(prop2), untrack(() => get(prop2).label)));
                  set_attribute2(span_10, "aria-label", (get(prop2), untrack(() => get(prop2).label)));
                  set_text(text_7, (get(prop2), untrack(() => get(prop2).icon)));
                });
                append($$anchor5, span_10);
              };
              var alternate_3 = ($$anchor5) => {
                var span_11 = root_152();
                var text_8 = child(span_11, true);
                reset(span_11);
                template_effect(() => set_text(text_8, (get(prop2), untrack(() => get(prop2).label))));
                append($$anchor5, span_11);
              };
              if_block(node_23, ($$render) => {
                if (get(prop2), untrack(() => get(prop2).icon)) $$render(consequent_13);
                else $$render(alternate_3, -1);
              });
            }
            var span_12 = sibling(node_23, 2);
            var text_9 = child(span_12, true);
            reset(span_12);
            reset(span_9);
            template_effect(() => {
              classes_6 = set_class(span_9, 1, "task-property svelte-1fvsaoa", null, classes_6, {
                "dataview-property": propertySchemaOption() === "dataview" /* Dataview */
              });
              set_text(text_9, (get(prop2), untrack(() => get(prop2).value)));
            });
            append($$anchor4, span_9);
          });
          append($$anchor3, fragment_5);
        };
        var alternate_4 = ($$anchor3) => {
          TaskDateFields($$anchor3, {
            get task() {
              return task();
            },
            get taskActions() {
              return taskActions();
            },
            get propertySchemaOption() {
              return propertySchemaOption();
            },
            get isTaskEditing() {
              return get(isEditing);
            },
            get isEditingDates() {
              return get(isEditingDates);
            },
            set isEditingDates($$value) {
              set(isEditingDates, $$value);
            },
            $$legacy: true
          });
        };
        if_block(node_20, ($$render) => {
          if (!get(isEditingDates)) $$render(consequent_14);
          else $$render(alternate_4, -1);
        });
      }
      reset(div_11);
      append($$anchor2, div_11);
    };
    if_block(node_19, ($$render) => {
      if (get(dateEditingEnabled)) $$render(consequent_15);
    });
  }
  var node_24 = sibling(node_19, 2);
  {
    var consequent_16 = ($$anchor2) => {
      var div_12 = root_20();
      var button_3 = child(div_12);
      var node_25 = child(button_3);
      Icon(node_25, { name: "lucide-arrow-up-right", size: 18, opacity: 0.5 });
      var span_13 = sibling(node_25, 2);
      var text_10 = child(span_13, true);
      reset(span_13);
      reset(button_3);
      reset(div_12);
      template_effect(() => set_text(text_10, (deep_read_state(task()), untrack(() => task().path))));
      event("click", button_3, (e) => taskActions().viewFile(task().id, e));
      event("keydown", button_3, (e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          taskActions().viewFile(task().id, e);
        }
      });
      append($$anchor2, div_12);
    };
    if_block(node_24, ($$render) => {
      if (showFilepath()) $$render(consequent_16);
    });
  }
  reset(div);
  template_effect(() => {
    classes = set_class(div, 1, "task svelte-1fvsaoa", null, classes, {
      "is-dragging": get(isDragging),
      "is-selected": isSelectionMode() && isSelected(),
      "is-selection-mode": isSelectionMode()
    });
    set_attribute2(div, "draggable", !get(isEditing));
    styles = set_style(div, "", styles, { "--task-accent-color": accentColor() });
  });
  event("dragstart", div, handleDragStart);
  event("dragend", div, handleDragEnd);
  append($$anchor, div);
  return pop($$exports);
}

// src/ui/tasks/manual_order.ts
function manualOrderKey(path, blockLink) {
  return `${path}::${blockLink}`;
}
function taskKey(task) {
  return task.blockLink ? manualOrderKey(task.path, task.blockLink) : null;
}
function computeDisplayOrder(tasks, entries) {
  if (!entries || entries.length === 0) {
    return tasks;
  }
  const byKey = /* @__PURE__ */ new Map();
  for (const task of tasks) {
    const key2 = taskKey(task);
    if (key2 !== null && !byKey.has(key2)) {
      byKey.set(key2, task);
    }
  }
  const pinned = [];
  const pinnedIds = /* @__PURE__ */ new Set();
  for (const entry of entries) {
    const task = byKey.get(entry);
    if (task && !pinnedIds.has(task.id)) {
      pinned.push(task);
      pinnedIds.add(task.id);
    }
  }
  const tail = tasks.filter((task) => !pinnedIds.has(task.id));
  return [...pinned, ...tail];
}
function computePinnedIds(tasks, entries) {
  const pinned = /* @__PURE__ */ new Set();
  if (!entries || entries.length === 0) {
    return pinned;
  }
  const present = /* @__PURE__ */ new Set();
  for (const task of tasks) {
    const key2 = taskKey(task);
    if (key2 !== null) present.add(key2);
  }
  const entrySet = new Set(entries);
  for (const task of tasks) {
    const key2 = taskKey(task);
    if (key2 !== null && entrySet.has(key2) && present.has(key2)) {
      pinned.add(task.id);
    }
  }
  return pinned;
}
function arrayMove(items, fromIndex, targetIndex) {
  if (fromIndex < 0 || fromIndex >= items.length) {
    return [...items];
  }
  const next2 = [...items];
  const [moved] = next2.splice(fromIndex, 1);
  if (moved === void 0) {
    return next2;
  }
  const clamped = Math.max(0, Math.min(targetIndex, next2.length));
  next2.splice(clamped, 0, moved);
  return next2;
}
function computeDropPlan(displayOrder, draggedId, targetIndex) {
  const fromIndex = displayOrder.findIndex((task) => task.id === draggedId);
  if (fromIndex === -1) {
    return { prefixTasks: [], tasksNeedingBlockLink: [] };
  }
  const reordered = arrayMove(displayOrder, fromIndex, targetIndex);
  const landedIndex = reordered.findIndex((task) => task.id === draggedId);
  const prefixTasks = reordered.slice(0, landedIndex + 1);
  const tasksNeedingBlockLink = prefixTasks.filter((task) => !task.blockLink);
  return { prefixTasks, tasksNeedingBlockLink };
}
function buildOrderEntries(prefixTasks, resolveBlockLink) {
  return prefixTasks.map((task) => manualOrderKey(task.path, resolveBlockLink(task)));
}
function removeEntry(entries, key2) {
  if (!entries || entries.length === 0) {
    return entries != null ? entries : [];
  }
  const next2 = entries.filter((entry) => entry !== key2);
  return next2.length === entries.length ? entries : next2;
}
function collectPresentManualOrderKeys(tasks, assignGroupId) {
  var _a5, _b3, _c2;
  const presentKeysByGroupAndColumn = {};
  for (const task of tasks) {
    if (!task.blockLink || task.column === "archived") {
      continue;
    }
    const groupId = assignGroupId(task);
    if (!groupId) {
      continue;
    }
    const columnTag = task.done || task.column === "done" ? "done" : (_a5 = task.column) != null ? _a5 : "uncategorised";
    const keysByColumn = (_b3 = presentKeysByGroupAndColumn[groupId]) != null ? _b3 : {};
    const keys = (_c2 = keysByColumn[columnTag]) != null ? _c2 : /* @__PURE__ */ new Set();
    keys.add(manualOrderKey(task.path, task.blockLink));
    keysByColumn[columnTag] = keys;
    presentKeysByGroupAndColumn[groupId] = keysByColumn;
  }
  return presentKeysByGroupAndColumn;
}
var BLOCK_LINK_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
function generateBlockLinkId(existing) {
  for (let attempt = 0; attempt < 100; attempt++) {
    let id = "";
    for (let i = 0; i < 6; i++) {
      id += BLOCK_LINK_ALPHABET[Math.floor(Math.random() * BLOCK_LINK_ALPHABET.length)];
    }
    if (!existing.has(id)) {
      return id;
    }
  }
  return `t${Date.now().toString(36)}`;
}
var blockLinkRegexp2 = /\s\^([a-zA-Z0-9-]+)\s*$/;
function ensureRowBlockLink(row, existing) {
  const existingMatch = row.match(blockLinkRegexp2);
  if (existingMatch == null ? void 0 : existingMatch[1]) {
    existing.add(existingMatch[1]);
    return { row, blockLink: existingMatch[1], changed: false };
  }
  const blockLink = generateBlockLinkId(existing);
  existing.add(blockLink);
  return {
    row: `${row.trimEnd()} ^${blockLink}`,
    blockLink,
    changed: true
  };
}

// src/ui/board/BoardCell.svelte
var root11 = from_html(`<span class="file-indicator-label svelte-xi2aql">(default)</span>`);
var root_110 = from_html(`<div class="file-indicator svelte-xi2aql"><span class="file-indicator-arrow svelte-xi2aql">\u2192</span> <span class="file-indicator-name svelte-xi2aql"> </span> <!></div>`);
var root_26 = from_html(`<div class="add-new-controls svelte-xi2aql"><div role="button"><span aria-hidden="true" class="svelte-xi2aql">+</span> Task</div> <!></div> <!>`, 1);
var root_34 = from_html(`<div class="new-task-date-fields svelte-xi2aql"><!></div>`);
var root_44 = from_html(`<div class="new-task-input svelte-xi2aql"><textarea placeholder="Task name..." class="svelte-xi2aql"></textarea> <!></div>`);
var root_53 = from_html(`<div role="presentation"><!></div>`);
var root_63 = from_html(`<div><!> <!> <div class="tasks svelte-xi2aql"></div></div>`);
var $$css11 = {
  hash: "svelte-xi2aql",
  code: '.tasks-wrapper.svelte-xi2aql {display:flex;flex-direction:column;height:100%;min-height:100%;border:var(--border-width) solid transparent;border-radius:var(--radius-s);\n  /* The wrapper should be invisible if collapsed in horizontal mode */}.tasks-wrapper.collapsed.svelte-xi2aql {display:none;}.tasks-wrapper.vertical-collapsed.svelte-xi2aql {display:none;}.tasks-wrapper.vertical-flow.svelte-xi2aql {width:100%;display:flex;flex-direction:column;gap:var(--size-4-2);}.tasks-wrapper.vertical-flow.svelte-xi2aql .tasks:where(.svelte-xi2aql) {order:1;flex-direction:row;flex-wrap:nowrap;align-items:flex-start;min-width:max-content;}.tasks-wrapper.vertical-flow.svelte-xi2aql .tasks:where(.svelte-xi2aql) .task {width:var(--column-width, 300px);flex-shrink:0;}.tasks-wrapper.vertical-flow.svelte-xi2aql .task-slot:where(.svelte-xi2aql) {flex:0 0 var(--column-width, 300px);}.tasks-wrapper.vertical-flow.svelte-xi2aql .new-task-input:where(.svelte-xi2aql) {order:4;width:var(--column-width, 300px);box-sizing:border-box;}.tasks-wrapper.vertical-flow.svelte-xi2aql .add-new-controls:where(.svelte-xi2aql) {order:2;}.tasks-wrapper.vertical-flow.svelte-xi2aql .file-indicator:where(.svelte-xi2aql) {order:3;}.tasks-wrapper.drop-active.svelte-xi2aql .tasks:where(.svelte-xi2aql) {opacity:0.4;}.tasks-wrapper.drop-hover.svelte-xi2aql {border-color:color-mix(in srgb, var(--column-color, var(--interactive-accent)) 75%, transparent);background:color-mix(in srgb, var(--column-color, var(--interactive-accent)) 10%, transparent);}.tasks-wrapper.svelte-xi2aql .tasks:where(.svelte-xi2aql) {display:flex;flex-direction:column;gap:var(--size-4-2);padding-top:var(--size-4-2);}.tasks-wrapper.svelte-xi2aql .task-slot:where(.svelte-xi2aql) {position:relative;}.tasks-wrapper.svelte-xi2aql .task-slot.drop-before:where(.svelte-xi2aql)::before, .tasks-wrapper.svelte-xi2aql .task-slot.drop-after:where(.svelte-xi2aql)::before {content:"";position:absolute;left:8px;right:8px;height:2px;background:var(--column-color, var(--interactive-accent));pointer-events:none;}.tasks-wrapper.svelte-xi2aql .task-slot.drop-before:where(.svelte-xi2aql)::after, .tasks-wrapper.svelte-xi2aql .task-slot.drop-after:where(.svelte-xi2aql)::after {content:"";position:absolute;left:4px;width:10px;height:10px;border-radius:999px;background:var(--column-color, var(--interactive-accent));pointer-events:none;}.tasks-wrapper.svelte-xi2aql .task-slot.drop-before:where(.svelte-xi2aql)::before {top:calc(-1 * var(--size-4-1) - 1px);}.tasks-wrapper.svelte-xi2aql .task-slot.drop-before:where(.svelte-xi2aql)::after {top:calc(-1 * var(--size-4-1) - 5px);}.tasks-wrapper.svelte-xi2aql .task-slot.drop-after:where(.svelte-xi2aql)::before {bottom:calc(-1 * var(--size-4-1) - 1px);}.tasks-wrapper.svelte-xi2aql .task-slot.drop-after:where(.svelte-xi2aql)::after {bottom:calc(-1 * var(--size-4-1) - 5px);}.tasks-wrapper.svelte-xi2aql .new-task-input:where(.svelte-xi2aql) {margin-top:var(--size-4-3);background-color:var(--background-primary);border-radius:var(--radius-s);border:var(--border-width) solid var(--background-modifier-border);padding:var(--size-4-2);}.tasks-wrapper.svelte-xi2aql .new-task-input:where(.svelte-xi2aql) textarea:where(.svelte-xi2aql) {cursor:text;background-color:var(--color-base-25);width:100%;}.tasks-wrapper.svelte-xi2aql .new-task-date-fields:where(.svelte-xi2aql) {margin-top:var(--size-2-3);}.tasks-wrapper.svelte-xi2aql .add-new-btn:where(.svelte-xi2aql) {display:inline-flex;align-items:center;gap:var(--size-2-1);align-self:flex-start;cursor:pointer;border:0;border-radius:var(--radius-s);box-shadow:none;margin:0;min-height:26px;padding:0;background:transparent;background-color:transparent;color:var(--text-accent);font-size:var(--font-ui-small);font-weight:var(--font-medium);line-height:1.2;}.tasks-wrapper.svelte-xi2aql .add-new-btn:where(.svelte-xi2aql) span:where(.svelte-xi2aql) {display:inline-flex;align-items:center;justify-content:center;font-size:var(--font-ui-medium);line-height:1;}.tasks-wrapper.svelte-xi2aql .add-new-btn.disabled:where(.svelte-xi2aql) {cursor:not-allowed;opacity:0.5;color:var(--text-muted);pointer-events:none;}.tasks-wrapper.svelte-xi2aql .add-new-controls:where(.svelte-xi2aql) {display:inline-flex;align-items:center;gap:var(--size-2-1);align-self:flex-start;border:0;background:transparent;box-shadow:none;}.tasks-wrapper.svelte-xi2aql .add-new-picker-btn {flex-shrink:0;width:22px;height:26px;border:0;border-radius:var(--radius-s);box-shadow:none;margin:0;background-color:transparent;color:var(--text-accent);}.tasks-wrapper.svelte-xi2aql .add-new-picker-btn.disabled:where(.svelte-xi2aql) {cursor:not-allowed;opacity:0.5;color:var(--text-muted);pointer-events:none;}.tasks-wrapper.svelte-xi2aql .add-new-btn:where(.svelte-xi2aql),\n.tasks-wrapper.svelte-xi2aql .add-new-picker-btn {background-color:transparent;}.tasks-wrapper.svelte-xi2aql .add-new-btn:where(.svelte-xi2aql):hover:not(.disabled),\n.tasks-wrapper.svelte-xi2aql .add-new-picker-btn:hover:not(.disabled) {background-color:transparent;color:var(--text-accent-hover);}.tasks-wrapper.svelte-xi2aql .add-new-btn:where(.svelte-xi2aql):active:not(.disabled),\n.tasks-wrapper.svelte-xi2aql .add-new-picker-btn:active:not(.disabled) {background-color:transparent;color:var(--text-accent-hover);}.tasks-wrapper.svelte-xi2aql .file-indicator:where(.svelte-xi2aql) {display:flex;align-items:center;gap:var(--size-2-1);font-size:var(--font-ui-small);color:var(--text-muted);margin-top:var(--size-2-1);}.tasks-wrapper.svelte-xi2aql .file-indicator:where(.svelte-xi2aql) .file-indicator-arrow:where(.svelte-xi2aql) {flex-shrink:0;}.tasks-wrapper.svelte-xi2aql .file-indicator:where(.svelte-xi2aql) .file-indicator-name:where(.svelte-xi2aql) {overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.tasks-wrapper.svelte-xi2aql .file-indicator:where(.svelte-xi2aql) .file-indicator-label:where(.svelte-xi2aql) {white-space:nowrap;}'
};
function BoardCell($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: BoardCell, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css11);
  const $selectionModeStore = () => store_get(selectionModeStore, "$selectionModeStore", $$stores);
  const $taskSelectionStore = () => store_get(taskSelectionStore, "$taskSelectionStore", $$stores);
  const $isDraggingStore = () => store_get(isDraggingStore, "$isDraggingStore", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const column = mutable_source();
  const tasks = mutable_source();
  const columnTitle = mutable_source();
  const creationMetadata = mutable_source();
  const fileGroupTargetFile = mutable_source();
  const effectiveTargetTaskFile = mutable_source();
  const effectiveTargetFileIsDefault = mutable_source();
  const isColTag = mutable_source();
  const isSelectMode = mutable_source();
  const columnTaskIds = mutable_source();
  const selectedIds = mutable_source();
  const taskSecondaryIds = mutable_source();
  const pinnedIds = mutable_source();
  const displayIds = mutable_source();
  const isManualReorderDrag = mutable_source();
  const draggingData = mutable_source();
  const hasSelectedTaskOutsideTargetFile = mutable_source();
  const isSameSwimlaneColumnDrop = mutable_source();
  const isFileSwimlaneDrop = mutable_source();
  const isTagSwimlaneDrop = mutable_source();
  const canDrop = mutable_source();
  const canEditNewTaskDates = mutable_source();
  let app = prop($$props, "app", 12);
  let cell = prop($$props, "cell", 12);
  let primaryTasks = prop($$props, "primaryTasks", 28, () => []);
  let secondaryAxisBucket = prop($$props, "secondaryAxisBucket", 12);
  let primaryAxisLabel = prop($$props, "primaryAxisLabel", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
  let showFilepath = prop($$props, "showFilepath", 12);
  let propertyDisplay = prop($$props, "propertyDisplay", 28, () => "none" /* None */);
  let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
  let consolidateTags = prop($$props, "consolidateTags", 12);
  let excludedTags = prop($$props, "excludedTags", 28, () => []);
  let isVerticalFlow = prop($$props, "isVerticalFlow", 12, false);
  let targetTaskFile = prop($$props, "targetTaskFile", 12, null);
  let targetFileIsDefault = prop($$props, "targetFileIsDefault", 12, false);
  let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
  let accentColor = prop($$props, "accentColor", 12, void 0);
  let treatNestedTasksAsSubtasks = prop($$props, "treatNestedTasksAsSubtasks", 12, false);
  let isManualOrder = prop($$props, "isManualOrder", 12, false);
  let manualOrderEntries = prop($$props, "manualOrderEntries", 12, void 0);
  let reorderEnabled = prop($$props, "reorderEnabled", 12, false);
  let isCollapsed = prop($$props, "isCollapsed", 12, false);
  let isDraggedOver = mutable_source(false);
  let reorderOverId = mutable_source(null);
  let reorderPlaceBefore = mutable_source(false);
  function computeTargetIndex(draggedId, overId, placeBefore) {
    const without = get(displayIds).filter((id) => id !== draggedId);
    const overPos = without.indexOf(overId);
    if (overPos === -1) return without.length;
    return placeBefore ? overPos : overPos + 1;
  }
  function handleReorderDragOver(e, overTaskId) {
    if (!get(isManualReorderDrag)) return;
    e.preventDefault();
    e.stopPropagation();
    const target = e.currentTarget;
    const rect = target.getBoundingClientRect();
    set(reorderPlaceBefore, e.clientY < rect.top + rect.height / 2);
    set(reorderOverId, overTaskId);
    if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
  }
  function handleReorderDragLeave() {
    set(reorderOverId, null);
  }
  async function handleReorderDrop(e, overTaskId) {
    if (!get(isManualReorderDrag) || !get(draggingData)) return;
    e.preventDefault();
    e.stopPropagation();
    const draggedId = get(draggingData).draggedTaskIds[0];
    const placeBefore = get(reorderPlaceBefore);
    set(reorderOverId, null);
    if (!draggedId || draggedId === overTaskId) return;
    const targetIndex = computeTargetIndex(draggedId, overTaskId, placeBefore);
    await taskActions().reorderTask(cell().secondaryId, get(column), get(displayIds), draggedId, targetIndex);
  }
  function handleDragOver(e) {
    e.preventDefault();
    if (!get(canDrop)) {
      if (e.dataTransfer) {
        e.dataTransfer.dropEffect = "none";
      }
      return;
    }
    set(isDraggedOver, true);
    if (e.dataTransfer) {
      e.dataTransfer.dropEffect = "move";
    }
  }
  function handleDragLeave(e) {
    set(isDraggedOver, false);
  }
  async function handleDrop(e) {
    var _a5, _b3, _c2, _d;
    e.preventDefault();
    set(isDraggedOver, false);
    if (!get(canDrop) || !get(draggingData)) {
      return;
    }
    const droppedIds = get(draggingData).draggedTaskIds.length > 0 ? get(draggingData).draggedTaskIds : (() => {
      var _a6;
      const id = (_a6 = e.dataTransfer) == null ? void 0 : _a6.getData("text/plain");
      return id ? [id] : [];
    })();
    if (droppedIds.length === 0) return;
    if (get(isFileSwimlaneDrop) && get(fileGroupTargetFile)) {
      const droppedIdsBySourceSwimlane = groupIdsBySecondaryId(droppedIds, get(draggingData).taskSecondaryIds);
      for (const [sourceFilePath, ids] of droppedIdsBySourceSwimlane) {
        if (sourceFilePath === get(fileGroupTargetFile).path) {
          await applyColumnChange(ids);
        } else {
          await taskActions().moveTasksToFile(ids, get(fileGroupTargetFile), get(column));
        }
      }
    } else if (get(isTagSwimlaneDrop)) {
      const source2 = (_a5 = secondaryAxisBucket().meta) == null ? void 0 : _a5.source;
      const prefix = (source2 == null ? void 0 : source2.kind) === "tag-prefix" ? (_b3 = source2.prefix) != null ? _b3 : "" : "";
      await taskActions().updateSwimlaneTag(droppedIds, (_d = (_c2 = secondaryAxisBucket().meta) == null ? void 0 : _c2.value) != null ? _d : null, prefix, excludedTags());
      await applyColumnChange(droppedIds);
    } else {
      await applyColumnChange(droppedIds);
    }
    clearColumnSelections(droppedIds);
  }
  let pendingNewTask = mutable_source(null);
  let pendingCancelled = false;
  let newTaskTextAreaEl = mutable_source();
  let newTaskInputEl = mutable_source();
  const emptyDateValues = { due: "", scheduled: "", start: "" };
  let newTaskDateValues = mutable_source({ ...emptyDateValues });
  async function handleNewTaskSave(event2) {
    var _a5, _b3, _c2;
    const nextTarget = event2 == null ? void 0 : event2.relatedTarget;
    if (nextTarget instanceof Node && ((_a5 = get(newTaskInputEl)) == null ? void 0 : _a5.contains(nextTarget))) {
      return;
    }
    if (pendingCancelled) {
      pendingCancelled = false;
      set(pendingNewTask, null);
      set(newTaskDateValues, { ...emptyDateValues });
      return;
    }
    const content = (_c2 = (_b3 = get(newTaskTextAreaEl)) == null ? void 0 : _b3.value) == null ? void 0 : _c2.trim();
    const file = get(pendingNewTask);
    set(pendingNewTask, null);
    if (!content || !file || !get(isColTag)) {
      set(newTaskDateValues, { ...emptyDateValues });
      return;
    }
    await taskActions().createTask(file, content, get(column), get(creationMetadata).additionalTags, get(newTaskDateValues));
    set(newTaskDateValues, { ...emptyDateValues });
  }
  function handleNewTaskKeydown(e) {
    var _a5, _b3;
    if (e.key === "Escape") {
      e.preventDefault();
      pendingCancelled = true;
      (_a5 = get(newTaskTextAreaEl)) == null ? void 0 : _a5.blur();
    } else if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      (_b3 = get(newTaskTextAreaEl)) == null ? void 0 : _b3.blur();
    }
  }
  function handleAddNewClick(e) {
    if (!get(isColTag)) {
      return;
    }
    set(newTaskDateValues, { ...emptyDateValues });
    if (get(fileGroupTargetFile)) {
      set(pendingNewTask, get(fileGroupTargetFile));
      return;
    }
    taskActions().pickFileForNewTask(get(column), e, (file) => {
      set(newTaskDateValues, { ...emptyDateValues });
      set(pendingNewTask, file);
    });
  }
  function handleChooseTaskFileClick(e) {
    if (!get(isColTag)) {
      return;
    }
    taskActions().pickFileForNewTask(
      get(column),
      e,
      (file) => {
        set(newTaskDateValues, { ...emptyDateValues });
        set(pendingNewTask, file);
      },
      true
    );
  }
  function handleNewTaskDateChange(key2, value) {
    set(newTaskDateValues, { ...get(newTaskDateValues), [key2]: value });
  }
  function groupIdsBySecondaryId(taskIds, taskSecondaryIds2) {
    var _a5, _b3;
    const grouped = /* @__PURE__ */ new Map();
    for (const id of taskIds) {
      const secondaryId = (_a5 = taskSecondaryIds2[id]) != null ? _a5 : "";
      const ids = (_b3 = grouped.get(secondaryId)) != null ? _b3 : [];
      ids.push(id);
      grouped.set(secondaryId, ids);
    }
    return grouped;
  }
  async function applyColumnChange(taskIds) {
    for (const id of taskIds) {
      switch (get(column)) {
        case "done":
          await taskActions().markDone(id);
          break;
        default:
          await taskActions().changeColumn(id, get(column));
          break;
      }
    }
  }
  legacy_pre_effect(() => deep_read_state(cell()), () => {
    set(column, cell().primaryId);
  });
  legacy_pre_effect(() => deep_read_state(cell()), () => {
    set(tasks, cell().tasks);
  });
  legacy_pre_effect(() => deep_read_state(primaryAxisLabel()), () => {
    set(columnTitle, primaryAxisLabel());
  });
  legacy_pre_effect(
    () => (deriveCellCreationMetadata, deep_read_state(secondaryAxisBucket())),
    () => {
      set(creationMetadata, deriveCellCreationMetadata(secondaryAxisBucket()));
    }
  );
  legacy_pre_effect(() => (get(creationMetadata), deep_read_state(app()), import_obsidian7.TFile), () => {
    set(fileGroupTargetFile, (() => {
      if (!get(creationMetadata).targetFilePath) return null;
      const file = app().vault.getAbstractFileByPath(get(creationMetadata).targetFilePath);
      return file instanceof import_obsidian7.TFile ? file : null;
    })());
  });
  legacy_pre_effect(
    () => (get(fileGroupTargetFile), deep_read_state(targetTaskFile())),
    () => {
      var _a5;
      set(effectiveTargetTaskFile, (_a5 = get(fileGroupTargetFile)) != null ? _a5 : targetTaskFile());
    }
  );
  legacy_pre_effect(
    () => (get(fileGroupTargetFile), deep_read_state(targetFileIsDefault())),
    () => {
      set(effectiveTargetFileIsDefault, get(fileGroupTargetFile) ? false : targetFileIsDefault());
    }
  );
  legacy_pre_effect(
    () => (isColumnTag, get(column), deep_read_state(columnTagTableStore())),
    () => {
      set(isColTag, isColumnTag(get(column), columnTagTableStore()));
    }
  );
  legacy_pre_effect(() => (isInSelectionMode, get(column), $selectionModeStore()), () => {
    set(isSelectMode, isInSelectionMode(get(column), $selectionModeStore()));
  });
  legacy_pre_effect(() => deep_read_state(primaryTasks()), () => {
    set(columnTaskIds, primaryTasks().map((t) => t.id));
  });
  legacy_pre_effect(() => (get(columnTaskIds), isTaskSelected, $taskSelectionStore()), () => {
    set(selectedIds, get(columnTaskIds).filter((id) => isTaskSelected(id, $taskSelectionStore())));
  });
  legacy_pre_effect(() => deep_read_state(primaryTasks()), () => {
    set(taskSecondaryIds, Object.fromEntries(primaryTasks().map((task) => [task.id, task.path])));
  });
  legacy_pre_effect(
    () => (deep_read_state(isManualOrder()), computePinnedIds, get(tasks), deep_read_state(manualOrderEntries())),
    () => {
      set(pinnedIds, isManualOrder() ? computePinnedIds(get(tasks), manualOrderEntries()) : /* @__PURE__ */ new Set());
    }
  );
  legacy_pre_effect(() => get(tasks), () => {
    set(displayIds, get(tasks).map((t) => t.id));
  });
  legacy_pre_effect(() => $isDraggingStore(), () => {
    set(draggingData, $isDraggingStore());
  });
  legacy_pre_effect(
    () => (deep_read_state(reorderEnabled()), get(draggingData), get(column), deep_read_state(cell())),
    () => {
      set(isManualReorderDrag, reorderEnabled() && !!get(draggingData) && get(draggingData).fromColumn === get(column) && get(draggingData).fromSecondaryId === cell().secondaryId && get(draggingData).draggedTaskIds.length === 1);
    }
  );
  legacy_pre_effect(() => (get(draggingData), get(fileGroupTargetFile)), () => {
    set(hasSelectedTaskOutsideTargetFile, !!get(draggingData) && !!get(fileGroupTargetFile) && get(draggingData).draggedTaskIds.some((id) => {
      var _a5;
      return ((_a5 = get(draggingData)) == null ? void 0 : _a5.taskSecondaryIds[id]) !== get(fileGroupTargetFile).path;
    }));
  });
  legacy_pre_effect(
    () => (get(draggingData), get(column), deep_read_state(cell())),
    () => {
      set(isSameSwimlaneColumnDrop, !!get(draggingData) && get(draggingData).fromColumn !== get(column) && get(draggingData).fromSecondaryId === cell().secondaryId);
    }
  );
  legacy_pre_effect(
    () => (get(draggingData), get(fileGroupTargetFile), deep_read_state(cell()), get(hasSelectedTaskOutsideTargetFile)),
    () => {
      set(isFileSwimlaneDrop, !!get(draggingData) && !!get(fileGroupTargetFile) && (get(draggingData).fromSecondaryId !== cell().secondaryId || get(hasSelectedTaskOutsideTargetFile)));
    }
  );
  legacy_pre_effect(
    () => (get(draggingData), deep_read_state(secondaryAxisBucket()), deep_read_state(cell())),
    () => {
      var _a5, _b3;
      set(isTagSwimlaneDrop, !!get(draggingData) && ((_b3 = (_a5 = secondaryAxisBucket().meta) == null ? void 0 : _a5.source) == null ? void 0 : _b3.kind) === "tag-prefix" && get(draggingData).fromSecondaryId !== cell().secondaryId);
    }
  );
  legacy_pre_effect(
    () => (get(isSameSwimlaneColumnDrop), get(isFileSwimlaneDrop), get(isTagSwimlaneDrop)),
    () => {
      set(canDrop, get(isSameSwimlaneColumnDrop) || get(isFileSwimlaneDrop) || get(isTagSwimlaneDrop));
    }
  );
  legacy_pre_effect(
    () => (getPropertyWriteAdapter, deep_read_state(propertySchemaOption())),
    () => {
      set(canEditNewTaskDates, getPropertyWriteAdapter(propertySchemaOption()) !== null);
    }
  );
  legacy_pre_effect(() => (get(pendingNewTask), get(newTaskTextAreaEl)), () => {
    if (get(pendingNewTask) && get(newTaskTextAreaEl)) {
      get(newTaskTextAreaEl).focus();
    }
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get app() {
      return app();
    },
    set app($$value) {
      app($$value);
      flushSync();
    },
    get cell() {
      return cell();
    },
    set cell($$value) {
      cell($$value);
      flushSync();
    },
    get primaryTasks() {
      return primaryTasks();
    },
    set primaryTasks($$value) {
      primaryTasks($$value);
      flushSync();
    },
    get secondaryAxisBucket() {
      return secondaryAxisBucket();
    },
    set secondaryAxisBucket($$value) {
      secondaryAxisBucket($$value);
      flushSync();
    },
    get primaryAxisLabel() {
      return primaryAxisLabel();
    },
    set primaryAxisLabel($$value) {
      primaryAxisLabel($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get columnTagTableStore() {
      return columnTagTableStore();
    },
    set columnTagTableStore($$value) {
      columnTagTableStore($$value);
      flushSync();
    },
    get showFilepath() {
      return showFilepath();
    },
    set showFilepath($$value) {
      showFilepath($$value);
      flushSync();
    },
    get propertyDisplay() {
      return propertyDisplay();
    },
    set propertyDisplay($$value) {
      propertyDisplay($$value);
      flushSync();
    },
    get propertySchemaOption() {
      return propertySchemaOption();
    },
    set propertySchemaOption($$value) {
      propertySchemaOption($$value);
      flushSync();
    },
    get consolidateTags() {
      return consolidateTags();
    },
    set consolidateTags($$value) {
      consolidateTags($$value);
      flushSync();
    },
    get excludedTags() {
      return excludedTags();
    },
    set excludedTags($$value) {
      excludedTags($$value);
      flushSync();
    },
    get isVerticalFlow() {
      return isVerticalFlow();
    },
    set isVerticalFlow($$value) {
      isVerticalFlow($$value);
      flushSync();
    },
    get targetTaskFile() {
      return targetTaskFile();
    },
    set targetTaskFile($$value) {
      targetTaskFile($$value);
      flushSync();
    },
    get targetFileIsDefault() {
      return targetFileIsDefault();
    },
    set targetFileIsDefault($$value) {
      targetFileIsDefault($$value);
      flushSync();
    },
    get doneColumnName() {
      return doneColumnName();
    },
    set doneColumnName($$value) {
      doneColumnName($$value);
      flushSync();
    },
    get accentColor() {
      return accentColor();
    },
    set accentColor($$value) {
      accentColor($$value);
      flushSync();
    },
    get treatNestedTasksAsSubtasks() {
      return treatNestedTasksAsSubtasks();
    },
    set treatNestedTasksAsSubtasks($$value) {
      treatNestedTasksAsSubtasks($$value);
      flushSync();
    },
    get isManualOrder() {
      return isManualOrder();
    },
    set isManualOrder($$value) {
      isManualOrder($$value);
      flushSync();
    },
    get manualOrderEntries() {
      return manualOrderEntries();
    },
    set manualOrderEntries($$value) {
      manualOrderEntries($$value);
      flushSync();
    },
    get reorderEnabled() {
      return reorderEnabled();
    },
    set reorderEnabled($$value) {
      reorderEnabled($$value);
      flushSync();
    },
    get isCollapsed() {
      return isCollapsed();
    },
    set isCollapsed($$value) {
      isCollapsed($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root_63();
  let classes;
  var node = child(div);
  {
    var consequent_2 = ($$anchor2) => {
      var fragment = root_26();
      var div_1 = first_child(fragment);
      var div_2 = child(div_1);
      let classes_1;
      var node_1 = sibling(div_2, 2);
      {
        let $0 = derived_safe_equal(() => get(pendingNewTask) ? "disabled" : "");
        let $1 = derived_safe_equal(() => !!get(pendingNewTask));
        Icon_button(node_1, {
          get class() {
            var _a5;
            return `add-new-picker-btn ${(_a5 = get($0)) != null ? _a5 : ""}`;
          },
          icon: "lucide-chevron-down",
          get "aria-label"() {
            var _a5;
            return `Choose file for new task in ${(_a5 = get(columnTitle)) != null ? _a5 : ""}`;
          },
          get disabled() {
            return get($1);
          },
          $$events: {
            click(...$$args) {
              var _a5;
              (_a5 = !get(pendingNewTask) ? handleChooseTaskFileClick : void 0) == null ? void 0 : _a5.apply(this, $$args);
            }
          }
        });
      }
      reset(div_1);
      var node_2 = sibling(div_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var div_3 = root_110();
          var span = sibling(child(div_3), 2);
          var text2 = child(span, true);
          reset(span);
          var node_3 = sibling(span, 2);
          {
            var consequent = ($$anchor4) => {
              var span_1 = root11();
              append($$anchor4, span_1);
            };
            if_block(node_3, ($$render) => {
              if (get(effectiveTargetFileIsDefault)) $$render(consequent);
            });
          }
          reset(div_3);
          template_effect(() => {
            set_attribute2(span, "title", (get(effectiveTargetTaskFile), untrack(() => get(effectiveTargetTaskFile).path)));
            set_text(text2, (get(effectiveTargetTaskFile), untrack(() => get(effectiveTargetTaskFile).name)));
          });
          append($$anchor3, div_3);
        };
        if_block(node_2, ($$render) => {
          if (get(effectiveTargetTaskFile)) $$render(consequent_1);
        });
      }
      template_effect(() => {
        var _a5;
        classes_1 = set_class(div_2, 1, "add-new-btn svelte-xi2aql", null, classes_1, { disabled: !!get(pendingNewTask) });
        set_attribute2(div_2, "tabindex", get(pendingNewTask) ? -1 : 0);
        set_attribute2(div_2, "aria-label", `Add new task to ${(_a5 = get(columnTitle)) != null ? _a5 : ""}`);
        set_attribute2(div_2, "aria-disabled", !!get(pendingNewTask));
      });
      event("click", div_2, function(...$$args) {
        var _a5;
        (_a5 = !get(pendingNewTask) ? handleAddNewClick : void 0) == null ? void 0 : _a5.apply(this, $$args);
      });
      event("keydown", div_2, (e) => {
        if (!get(pendingNewTask) && (e.key === "Enter" || e.key === " ")) {
          e.preventDefault();
          handleAddNewClick();
        }
      });
      append($$anchor2, fragment);
    };
    if_block(node, ($$render) => {
      if (get(isColTag)) $$render(consequent_2);
    });
  }
  var node_4 = sibling(node, 2);
  {
    var consequent_4 = ($$anchor2) => {
      var div_4 = root_44();
      var textarea = child(div_4);
      bind_this(textarea, ($$value) => set(newTaskTextAreaEl, $$value), () => get(newTaskTextAreaEl));
      var node_5 = sibling(textarea, 2);
      {
        var consequent_3 = ($$anchor3) => {
          var div_5 = root_34();
          var node_6 = child(div_5);
          DateInputFields(node_6, {
            get values() {
              return get(newTaskDateValues);
            },
            onDateChange: handleNewTaskDateChange
          });
          reset(div_5);
          append($$anchor3, div_5);
        };
        if_block(node_5, ($$render) => {
          if (get(canEditNewTaskDates)) $$render(consequent_3);
        });
      }
      reset(div_4);
      bind_this(div_4, ($$value) => set(newTaskInputEl, $$value), () => get(newTaskInputEl));
      event("keydown", textarea, handleNewTaskKeydown);
      event("focusout", div_4, handleNewTaskSave);
      append($$anchor2, div_4);
    };
    if_block(node_4, ($$render) => {
      if (get(pendingNewTask)) $$render(consequent_4);
    });
  }
  var div_6 = sibling(node_4, 2);
  each(div_6, 5, () => get(tasks), (task) => task.id, ($$anchor2, task) => {
    var div_7 = root_53();
    let classes_2;
    var node_7 = child(div_7);
    {
      let $0 = derived_safe_equal(() => (deep_read_state(isTaskSelected), get(task), $taskSelectionStore(), untrack(() => isTaskSelected(get(task).id, $taskSelectionStore()))));
      let $1 = derived_safe_equal(() => (get(pinnedIds), get(task), untrack(() => get(pinnedIds).has(get(task).id))));
      Task2(node_7, {
        get app() {
          return app();
        },
        get task() {
          return get(task);
        },
        get taskActions() {
          return taskActions();
        },
        get columnTagTableStore() {
          return columnTagTableStore();
        },
        get showFilepath() {
          return showFilepath();
        },
        get propertyDisplay() {
          return propertyDisplay();
        },
        get propertySchemaOption() {
          return propertySchemaOption();
        },
        get consolidateTags() {
          return consolidateTags();
        },
        get excludedTags() {
          return excludedTags();
        },
        get treatNestedTasksAsSubtasks() {
          return treatNestedTasksAsSubtasks();
        },
        get displayColumn() {
          return get(column);
        },
        get displaySecondaryId() {
          return deep_read_state(cell()), untrack(() => cell().secondaryId);
        },
        get isSelectionMode() {
          return get(isSelectMode);
        },
        get isSelected() {
          return get($0);
        },
        onToggleSelection: () => toggleTaskSelection(get(task).id),
        get selectedTaskIds() {
          return get(selectedIds);
        },
        get taskSecondaryIds() {
          return get(taskSecondaryIds);
        },
        get doneColumnName() {
          return doneColumnName();
        },
        get accentColor() {
          return accentColor();
        },
        get isManualOrder() {
          return isManualOrder();
        },
        get isPinned() {
          return get($1);
        },
        get showDragHandle() {
          return reorderEnabled();
        },
        onUnpin: () => taskActions().unpinTask(cell().secondaryId, get(column), get(task).id)
      });
    }
    reset(div_7);
    template_effect(() => classes_2 = set_class(div_7, 1, "task-slot svelte-xi2aql", null, classes_2, {
      "drop-before": get(isManualReorderDrag) && get(reorderOverId) === get(task).id && get(reorderPlaceBefore),
      "drop-after": get(isManualReorderDrag) && get(reorderOverId) === get(task).id && !get(reorderPlaceBefore)
    }));
    event("dragover", div_7, (e) => handleReorderDragOver(e, get(task).id));
    event("drop", div_7, (e) => handleReorderDrop(e, get(task).id));
    event("dragleave", div_7, handleReorderDragLeave);
    append($$anchor2, div_7);
  });
  reset(div_6);
  reset(div);
  template_effect(() => classes = set_class(div, 1, "tasks-wrapper svelte-xi2aql", null, classes, {
    "vertical-flow": isVerticalFlow(),
    collapsed: isCollapsed() && !isVerticalFlow(),
    "vertical-collapsed": isCollapsed() && isVerticalFlow(),
    "drop-active": !!get(draggingData) && !get(isManualReorderDrag),
    "drop-hover": get(isDraggedOver)
  }));
  event("dragover", div, handleDragOver);
  event("dragleave", div, handleDragLeave);
  event("drop", div, handleDrop);
  append($$anchor, div);
  var $$pop = pop($$exports);
  $$cleanup();
  return $$pop;
}

// src/ui/board/board_matrix_vertical.svelte
var root12 = from_html(`<div><!></div> <div><!></div>`, 1);
var root_111 = from_html(`<div class="matrix-vertical ungrouped-grid svelte-iq029y"></div>`);
var root_27 = from_html(`<div class="group-header-cell svelte-iq029y"><span class="group-label svelte-iq029y"> </span></div>`);
var root_35 = from_html(`<div><!></div>`);
var root_45 = from_html(`<div><!></div> <!>`, 1);
var root_54 = from_html(`<div class="matrix-vertical transposed-grid svelte-iq029y"><div class="matrix-corner svelte-iq029y"></div> <!> <!></div>`);
var $$css12 = {
  hash: "svelte-iq029y",
  code: ".matrix-vertical.svelte-iq029y {--vertical-row-header-width: clamp(220px, 24vw, 280px);padding-bottom:var(--size-4-4);}.matrix-vertical.ungrouped-grid.svelte-iq029y, .matrix-vertical.transposed-grid.svelte-iq029y {display:grid;column-gap:0;row-gap:0;align-items:stretch;min-width:max-content;border:var(--border-width) solid var(--background-modifier-border);border-radius:var(--radius-m);background:var(--background-primary);box-shadow:var(--shadow-s);overflow:visible;}.matrix-vertical.ungrouped-grid.svelte-iq029y {grid-template-columns:var(--vertical-row-header-width) max-content;}.matrix-corner.svelte-iq029y,\n.group-header-cell.svelte-iq029y {position:sticky;top:0;z-index:5;min-height:64px;background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));border-right:var(--border-width) solid var(--background-modifier-border);border-bottom:var(--border-width) solid var(--background-modifier-border);box-shadow:inset 0 var(--border-width) 0 var(--background-modifier-border), inset var(--border-width) 0 0 var(--background-modifier-border);}.matrix-corner.svelte-iq029y {left:0;z-index:8;}.group-header-cell.svelte-iq029y {display:flex;align-items:center;min-width:var(--column-width, 300px);padding:var(--size-4-3) var(--size-4-4);overflow:clip;}.group-header-cell.svelte-iq029y .group-label:where(.svelte-iq029y) {position:sticky;left:calc(var(--vertical-row-header-width) + var(--size-4-4));display:inline-block;max-width:max-content;color:var(--text-normal);font-size:var(--font-ui-medium);font-weight:var(--font-medium);line-height:1.2;white-space:nowrap;}.row-header-wrapper.svelte-iq029y,\n.row-cell.svelte-iq029y {border-bottom:var(--border-width) solid var(--background-modifier-border);}.row-header-wrapper.svelte-iq029y {position:sticky;left:0;z-index:4;display:flex;align-items:stretch;min-height:96px;padding:var(--size-4-2) var(--size-4-3);background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));border-right:var(--border-width) solid var(--background-modifier-border);--column-header-x-padding-override: var(--size-4-3);--column-header-y-padding-override: var(--size-4-2);}.row-header-wrapper.collapsed.svelte-iq029y {min-height:64px;cursor:pointer;}.row-cell.svelte-iq029y {z-index:1;display:flex;align-self:stretch;min-height:96px;min-width:max-content;padding:var(--size-4-2) var(--size-4-4);background:color-mix(in srgb, var(--background-primary) 88%, var(--background-secondary));}.row-cell.collapsed.svelte-iq029y {display:none;}.cell-wrapper.svelte-iq029y {padding:var(--size-4-2) var(--size-4-4);border-bottom:var(--border-width) solid var(--background-modifier-border);}.cell-wrapper.grouped-cell.svelte-iq029y {z-index:1;display:flex;align-self:stretch;min-height:96px;min-width:var(--column-width, 300px);background:color-mix(in srgb, var(--background-primary) 88%, var(--background-secondary));border-right:var(--border-width) solid var(--background-modifier-border);}.cell-wrapper.grouped-cell.collapsed.svelte-iq029y {display:none;}"
};
function Board_matrix_vertical($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Board_matrix_vertical, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css12);
  const tasksByPrimary = mutable_source();
  const showSwimlaneHeaders = mutable_source();
  const ungroupedSecondaryBucket = mutable_source();
  const ungroupedGridTemplateRows = mutable_source();
  const groupedGridTemplateColumns = mutable_source();
  const groupedGridTemplateRows = mutable_source();
  let app = prop($$props, "app", 12);
  let matrix = prop($$props, "matrix", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
  let columnColourTableStore = prop($$props, "columnColourTableStore", 12);
  let columnMatchTagTableStore = prop($$props, "columnMatchTagTableStore", 12);
  let columnSubtitleTableStore = prop($$props, "columnSubtitleTableStore", 12);
  let showFilepath = prop($$props, "showFilepath", 12);
  let propertyDisplay = prop($$props, "propertyDisplay", 28, () => "none" /* None */);
  let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
  let consolidateTags = prop($$props, "consolidateTags", 12);
  let excludedTags = prop($$props, "excludedTags", 28, () => []);
  let targetTaskFile = prop($$props, "targetTaskFile", 12, null);
  let targetFileIsDefault = prop($$props, "targetFileIsDefault", 12, false);
  let onToggleCollapse = prop($$props, "onToggleCollapse", 12);
  let uncategorizedColumnName = prop($$props, "uncategorizedColumnName", 12, void 0);
  let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
  let isManualOrder = prop($$props, "isManualOrder", 12, false);
  let manualOrder = prop($$props, "manualOrder", 28, () => ({}));
  let reorderEnabled = prop($$props, "reorderEnabled", 12, false);
  let treatNestedTasksAsSubtasks = prop($$props, "treatNestedTasksAsSubtasks", 12, false);
  let headerHeight = mutable_source(64);
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    set(tasksByPrimary, Object.fromEntries(matrix().primaryAxis.map((bucket) => [
      bucket.id,
      Object.values(matrix().cells[bucket.id] || {}).flatMap((cell) => cell.tasks)
    ])));
  });
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    var _a5;
    set(showSwimlaneHeaders, matrix().secondaryAxis.length > 1 || matrix().secondaryAxis.length > 0 && !((_a5 = matrix().secondaryAxis[0].meta) == null ? void 0 : _a5.isDefault));
  });
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    set(ungroupedSecondaryBucket, matrix().secondaryAxis[0]);
  });
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    set(ungroupedGridTemplateRows, matrix().primaryAxis.map(() => "max-content").join(" "));
  });
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    set(groupedGridTemplateColumns, [
      "var(--vertical-row-header-width)",
      ...matrix().secondaryAxis.map(() => "max-content")
    ].join(" "));
  });
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    set(groupedGridTemplateRows, [
      "max-content",
      ...matrix().primaryAxis.map(() => "max-content")
    ].join(" "));
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get app() {
      return app();
    },
    set app($$value) {
      app($$value);
      flushSync();
    },
    get matrix() {
      return matrix();
    },
    set matrix($$value) {
      matrix($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get columnTagTableStore() {
      return columnTagTableStore();
    },
    set columnTagTableStore($$value) {
      columnTagTableStore($$value);
      flushSync();
    },
    get columnColourTableStore() {
      return columnColourTableStore();
    },
    set columnColourTableStore($$value) {
      columnColourTableStore($$value);
      flushSync();
    },
    get columnMatchTagTableStore() {
      return columnMatchTagTableStore();
    },
    set columnMatchTagTableStore($$value) {
      columnMatchTagTableStore($$value);
      flushSync();
    },
    get columnSubtitleTableStore() {
      return columnSubtitleTableStore();
    },
    set columnSubtitleTableStore($$value) {
      columnSubtitleTableStore($$value);
      flushSync();
    },
    get showFilepath() {
      return showFilepath();
    },
    set showFilepath($$value) {
      showFilepath($$value);
      flushSync();
    },
    get propertyDisplay() {
      return propertyDisplay();
    },
    set propertyDisplay($$value) {
      propertyDisplay($$value);
      flushSync();
    },
    get propertySchemaOption() {
      return propertySchemaOption();
    },
    set propertySchemaOption($$value) {
      propertySchemaOption($$value);
      flushSync();
    },
    get consolidateTags() {
      return consolidateTags();
    },
    set consolidateTags($$value) {
      consolidateTags($$value);
      flushSync();
    },
    get excludedTags() {
      return excludedTags();
    },
    set excludedTags($$value) {
      excludedTags($$value);
      flushSync();
    },
    get targetTaskFile() {
      return targetTaskFile();
    },
    set targetTaskFile($$value) {
      targetTaskFile($$value);
      flushSync();
    },
    get targetFileIsDefault() {
      return targetFileIsDefault();
    },
    set targetFileIsDefault($$value) {
      targetFileIsDefault($$value);
      flushSync();
    },
    get onToggleCollapse() {
      return onToggleCollapse();
    },
    set onToggleCollapse($$value) {
      onToggleCollapse($$value);
      flushSync();
    },
    get uncategorizedColumnName() {
      return uncategorizedColumnName();
    },
    set uncategorizedColumnName($$value) {
      uncategorizedColumnName($$value);
      flushSync();
    },
    get doneColumnName() {
      return doneColumnName();
    },
    set doneColumnName($$value) {
      doneColumnName($$value);
      flushSync();
    },
    get isManualOrder() {
      return isManualOrder();
    },
    set isManualOrder($$value) {
      isManualOrder($$value);
      flushSync();
    },
    get manualOrder() {
      return manualOrder();
    },
    set manualOrder($$value) {
      manualOrder($$value);
      flushSync();
    },
    get reorderEnabled() {
      return reorderEnabled();
    },
    set reorderEnabled($$value) {
      reorderEnabled($$value);
      flushSync();
    },
    get treatNestedTasksAsSubtasks() {
      return treatNestedTasksAsSubtasks();
    },
    set treatNestedTasksAsSubtasks($$value) {
      treatNestedTasksAsSubtasks($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_111();
      let styles;
      each(
        div,
        7,
        () => (deep_read_state(matrix()), untrack(() => matrix().primaryAxis)),
        (pBucket) => pBucket.id,
        ($$anchor3, pBucket, pIndex) => {
          var fragment_1 = root12();
          var div_1 = first_child(fragment_1);
          let classes;
          let styles_1;
          var node_1 = child(div_1);
          {
            let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
              var _a5;
              return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
            })));
            ColumnHeader(node_1, {
              get column() {
                return get(pBucket), untrack(() => get(pBucket).id);
              },
              get tasks() {
                return get($0);
              },
              get taskActions() {
                return taskActions();
              },
              get columnTagTableStore() {
                return columnTagTableStore();
              },
              get columnColourTableStore() {
                return columnColourTableStore();
              },
              get columnMatchTagTableStore() {
                return columnMatchTagTableStore();
              },
              get columnSubtitleTableStore() {
                return columnSubtitleTableStore();
              },
              isVerticalFlow: true,
              get isCollapsed() {
                return get(pBucket), untrack(() => get(pBucket).collapsed);
              },
              onToggleCollapse: () => onToggleCollapse()(get(pBucket).id),
              get uncategorizedColumnName() {
                return uncategorizedColumnName();
              },
              get doneColumnName() {
                return doneColumnName();
              }
            });
          }
          reset(div_1);
          var div_2 = sibling(div_1, 2);
          let classes_1;
          let styles_2;
          var node_2 = child(div_2);
          {
            let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
              var _a5;
              return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
            })));
            let $1 = derived_safe_equal(() => (get(pBucket), untrack(() => {
              var _a5;
              return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
            })));
            let $2 = derived_safe_equal(() => (deep_read_state(manualOrder()), get(ungroupedSecondaryBucket), get(pBucket), untrack(() => {
              var _a5;
              return (_a5 = manualOrder()[get(ungroupedSecondaryBucket).id]) == null ? void 0 : _a5[get(pBucket).id];
            })));
            BoardCell(node_2, {
              get app() {
                return app();
              },
              get cell() {
                return deep_read_state(matrix()), get(pBucket), get(ungroupedSecondaryBucket), untrack(() => matrix().cells[get(pBucket).id][get(ungroupedSecondaryBucket).id]);
              },
              get primaryTasks() {
                return get($0);
              },
              get secondaryAxisBucket() {
                return get(ungroupedSecondaryBucket);
              },
              get primaryAxisLabel() {
                return get(pBucket), untrack(() => get(pBucket).label);
              },
              get taskActions() {
                return taskActions();
              },
              get columnTagTableStore() {
                return columnTagTableStore();
              },
              get showFilepath() {
                return showFilepath();
              },
              get propertyDisplay() {
                return propertyDisplay();
              },
              get propertySchemaOption() {
                return propertySchemaOption();
              },
              get consolidateTags() {
                return consolidateTags();
              },
              get excludedTags() {
                return excludedTags();
              },
              get treatNestedTasksAsSubtasks() {
                return treatNestedTasksAsSubtasks();
              },
              isVerticalFlow: true,
              get targetTaskFile() {
                return targetTaskFile();
              },
              get targetFileIsDefault() {
                return targetFileIsDefault();
              },
              get doneColumnName() {
                return doneColumnName();
              },
              get isCollapsed() {
                return get(pBucket), untrack(() => get(pBucket).collapsed);
              },
              get accentColor() {
                return get($1);
              },
              get isManualOrder() {
                return isManualOrder();
              },
              get manualOrderEntries() {
                return get($2);
              },
              get reorderEnabled() {
                return reorderEnabled();
              }
            });
          }
          reset(div_2);
          template_effect(() => {
            classes = set_class(div_1, 1, "row-header-wrapper svelte-iq029y", null, classes, { collapsed: get(pBucket).collapsed });
            styles_1 = set_style(div_1, "", styles_1, {
              "grid-column": "1",
              "grid-row": get(pIndex) + 1,
              "--column-color": (get(pBucket), untrack(() => {
                var _a5;
                return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
              }))
            });
            classes_1 = set_class(div_2, 1, "cell-wrapper row-cell svelte-iq029y", null, classes_1, { collapsed: get(pBucket).collapsed });
            styles_2 = set_style(div_2, "", styles_2, {
              "grid-column": "2",
              "grid-row": get(pIndex) + 1,
              "--column-color": (get(pBucket), untrack(() => {
                var _a5;
                return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
              }))
            });
          });
          append($$anchor3, fragment_1);
        }
      );
      reset(div);
      template_effect(() => styles = set_style(div, "", styles, {
        "grid-template-rows": get(ungroupedGridTemplateRows),
        "--header-height": "0px"
      }));
      append($$anchor2, div);
    };
    var alternate = ($$anchor2) => {
      var div_3 = root_54();
      let styles_3;
      var div_4 = child(div_3);
      set_style(div_4, "", {}, { "grid-column": "1", "grid-row": "1" });
      var node_3 = sibling(div_4, 2);
      each(
        node_3,
        3,
        () => (deep_read_state(matrix()), untrack(() => matrix().secondaryAxis)),
        (sBucket) => sBucket.id,
        ($$anchor3, sBucket, sIndex) => {
          var div_5 = root_27();
          let styles_4;
          var span = child(div_5);
          var text2 = child(span, true);
          reset(span);
          reset(div_5);
          template_effect(() => {
            styles_4 = set_style(div_5, "", styles_4, { "grid-column": get(sIndex) + 2, "grid-row": "1" });
            set_attribute2(span, "title", (get(sBucket), untrack(() => get(sBucket).label)));
            set_text(text2, (get(sBucket), untrack(() => get(sBucket).label)));
          });
          append($$anchor3, div_5);
        }
      );
      var node_4 = sibling(node_3, 2);
      each(
        node_4,
        3,
        () => (deep_read_state(matrix()), untrack(() => matrix().primaryAxis)),
        (pBucket) => pBucket.id,
        ($$anchor3, pBucket, pIndex) => {
          var fragment_2 = root_45();
          var div_6 = first_child(fragment_2);
          let classes_2;
          let styles_5;
          var node_5 = child(div_6);
          {
            let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
              var _a5;
              return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
            })));
            ColumnHeader(node_5, {
              get column() {
                return get(pBucket), untrack(() => get(pBucket).id);
              },
              get tasks() {
                return get($0);
              },
              get taskActions() {
                return taskActions();
              },
              get columnTagTableStore() {
                return columnTagTableStore();
              },
              get columnColourTableStore() {
                return columnColourTableStore();
              },
              get columnMatchTagTableStore() {
                return columnMatchTagTableStore();
              },
              get columnSubtitleTableStore() {
                return columnSubtitleTableStore();
              },
              isVerticalFlow: true,
              get isCollapsed() {
                return get(pBucket), untrack(() => get(pBucket).collapsed);
              },
              onToggleCollapse: () => onToggleCollapse()(get(pBucket).id),
              get uncategorizedColumnName() {
                return uncategorizedColumnName();
              },
              get doneColumnName() {
                return doneColumnName();
              }
            });
          }
          reset(div_6);
          var node_6 = sibling(div_6, 2);
          each(
            node_6,
            3,
            () => (deep_read_state(matrix()), untrack(() => matrix().secondaryAxis)),
            (sBucket) => sBucket.id,
            ($$anchor4, sBucket, sIndex) => {
              var div_7 = root_35();
              let classes_3;
              let styles_6;
              var node_7 = child(div_7);
              {
                let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
                  var _a5;
                  return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
                })));
                let $1 = derived_safe_equal(() => (get(pBucket), untrack(() => {
                  var _a5;
                  return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
                })));
                let $2 = derived_safe_equal(() => (deep_read_state(manualOrder()), get(sBucket), get(pBucket), untrack(() => {
                  var _a5;
                  return (_a5 = manualOrder()[get(sBucket).id]) == null ? void 0 : _a5[get(pBucket).id];
                })));
                BoardCell(node_7, {
                  get app() {
                    return app();
                  },
                  get cell() {
                    return deep_read_state(matrix()), get(pBucket), get(sBucket), untrack(() => matrix().cells[get(pBucket).id][get(sBucket).id]);
                  },
                  get primaryTasks() {
                    return get($0);
                  },
                  get secondaryAxisBucket() {
                    return get(sBucket);
                  },
                  get primaryAxisLabel() {
                    return get(pBucket), untrack(() => get(pBucket).label);
                  },
                  get taskActions() {
                    return taskActions();
                  },
                  get columnTagTableStore() {
                    return columnTagTableStore();
                  },
                  get showFilepath() {
                    return showFilepath();
                  },
                  get propertyDisplay() {
                    return propertyDisplay();
                  },
                  get propertySchemaOption() {
                    return propertySchemaOption();
                  },
                  get consolidateTags() {
                    return consolidateTags();
                  },
                  get excludedTags() {
                    return excludedTags();
                  },
                  get treatNestedTasksAsSubtasks() {
                    return treatNestedTasksAsSubtasks();
                  },
                  isVerticalFlow: true,
                  get targetTaskFile() {
                    return targetTaskFile();
                  },
                  get targetFileIsDefault() {
                    return targetFileIsDefault();
                  },
                  get doneColumnName() {
                    return doneColumnName();
                  },
                  get isCollapsed() {
                    return get(pBucket), untrack(() => get(pBucket).collapsed);
                  },
                  get accentColor() {
                    return get($1);
                  },
                  get isManualOrder() {
                    return isManualOrder();
                  },
                  get manualOrderEntries() {
                    return get($2);
                  },
                  get reorderEnabled() {
                    return reorderEnabled();
                  }
                });
              }
              reset(div_7);
              template_effect(() => {
                classes_3 = set_class(div_7, 1, "cell-wrapper grouped-cell svelte-iq029y", null, classes_3, { collapsed: get(pBucket).collapsed });
                styles_6 = set_style(div_7, "", styles_6, {
                  "grid-column": get(sIndex) + 2,
                  "grid-row": get(pIndex) + 2,
                  "--column-color": (get(pBucket), untrack(() => {
                    var _a5;
                    return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
                  }))
                });
              });
              append($$anchor4, div_7);
            }
          );
          template_effect(() => {
            classes_2 = set_class(div_6, 1, "row-header-wrapper svelte-iq029y", null, classes_2, { collapsed: get(pBucket).collapsed });
            styles_5 = set_style(div_6, "", styles_5, {
              "grid-column": "1",
              "grid-row": get(pIndex) + 2,
              "--column-color": (get(pBucket), untrack(() => {
                var _a5;
                return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
              }))
            });
          });
          append($$anchor3, fragment_2);
        }
      );
      reset(div_3);
      template_effect(() => {
        var _a5;
        return styles_3 = set_style(div_3, "", styles_3, {
          "grid-template-columns": get(groupedGridTemplateColumns),
          "grid-template-rows": get(groupedGridTemplateRows),
          "--header-height": `${(_a5 = get(headerHeight)) != null ? _a5 : ""}px`
        });
      });
      bind_element_size(div_4, "clientHeight", ($$value) => set(headerHeight, $$value));
      append($$anchor2, div_3);
    };
    if_block(node, ($$render) => {
      if (!get(showSwimlaneHeaders) && get(ungroupedSecondaryBucket)) $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  append($$anchor, fragment);
  return pop($$exports);
}

// src/ui/board/board_matrix_horizontal.svelte
var root13 = from_html(`<div class="matrix-corner svelte-1j479gc"></div>`);
var root_112 = from_html(`<div><!></div>`);
var root_28 = from_html(`<div class="swimlane-header-cell svelte-1j479gc"><span class="swimlane-label svelte-1j479gc"> </span></div>`);
var root_36 = from_html(`<!> <!>`, 1);
var root_46 = from_html(`<div class="matrix-horizontal svelte-1j479gc"><!> <!> <!></div>`);
var $$css13 = {
  hash: "svelte-1j479gc",
  code: ".matrix-horizontal.svelte-1j479gc {display:grid;column-gap:0;row-gap:0;align-items:stretch;min-width:max-content;padding-bottom:var(--size-4-4);border:var(--border-width) solid var(--background-modifier-border);border-radius:var(--radius-m);background:var(--background-primary);box-shadow:var(--shadow-s);overflow:visible;}.matrix-corner.svelte-1j479gc,\n.header-wrapper.svelte-1j479gc {background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));border-bottom:var(--border-width) solid var(--background-modifier-border);border-right:var(--border-width) solid var(--background-modifier-border);min-height:64px;}.matrix-corner.svelte-1j479gc {position:sticky;left:0;top:0;z-index:7;}.header-wrapper.svelte-1j479gc {position:sticky;top:0;z-index:5;padding:var(--size-4-2) var(--size-4-3);--column-header-x-padding-override: var(--size-4-3);--column-header-y-padding-override: var(--size-4-2);display:flex;align-items:stretch;}.header-wrapper.collapsed.svelte-1j479gc {position:sticky;top:0;display:flex;flex-direction:column;align-self:start;height:100%;min-height:100%;padding:0 var(--size-2-3) var(--size-4-3);--column-header-x-padding-override: var(--size-2-3);--column-header-y-padding-override: 0px;cursor:pointer;z-index:6;}.swimlane-header-cell.svelte-1j479gc {position:sticky;left:0;z-index:3;display:flex;align-items:start;justify-content:center;min-height:188px;padding:var(--size-4-3) var(--size-2-2);background:color-mix(in srgb, var(--background-primary) 82%, var(--background-secondary));border-right:var(--border-width) solid var(--background-modifier-border);border-bottom:var(--border-width) solid var(--background-modifier-border);}.swimlane-header-cell.svelte-1j479gc .swimlane-label:where(.svelte-1j479gc) {position:sticky;top:calc(var(--header-height) + var(--size-4-3));color:var(--text-normal);font-size:var(--font-ui-medium);font-weight:var(--font-medium);line-height:1.2;writing-mode:vertical-rl;text-orientation:mixed;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-height:100%;}.cell-wrapper.svelte-1j479gc {z-index:1;min-height:188px;padding:var(--size-4-2) var(--size-4-4);display:flex;flex-direction:column;align-self:stretch;background:color-mix(in srgb, var(--background-primary) 88%, var(--background-secondary));border-right:var(--border-width) solid var(--background-modifier-border);border-bottom:var(--border-width) solid var(--background-modifier-border);}.cell-wrapper.collapsed.svelte-1j479gc {display:none;}"
};
function Board_matrix_horizontal($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Board_matrix_horizontal, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css13);
  const tasksByPrimary = mutable_source();
  const showSwimlaneHeaders = mutable_source();
  const gridTemplateColumns = mutable_source();
  const primaryGridColumnOffset = mutable_source();
  const gridTemplateRows = mutable_source();
  let app = prop($$props, "app", 12);
  let matrix = prop($$props, "matrix", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
  let columnColourTableStore = prop($$props, "columnColourTableStore", 12);
  let columnMatchTagTableStore = prop($$props, "columnMatchTagTableStore", 12);
  let columnSubtitleTableStore = prop($$props, "columnSubtitleTableStore", 12);
  let showFilepath = prop($$props, "showFilepath", 12);
  let propertyDisplay = prop($$props, "propertyDisplay", 28, () => "none" /* None */);
  let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
  let consolidateTags = prop($$props, "consolidateTags", 12);
  let excludedTags = prop($$props, "excludedTags", 28, () => []);
  let targetTaskFile = prop($$props, "targetTaskFile", 12, null);
  let targetFileIsDefault = prop($$props, "targetFileIsDefault", 12, false);
  let onToggleCollapse = prop($$props, "onToggleCollapse", 12);
  let uncategorizedColumnName = prop($$props, "uncategorizedColumnName", 12, void 0);
  let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
  let columnWidth = prop($$props, "columnWidth", 12, "300px");
  let isManualOrder = prop($$props, "isManualOrder", 12, false);
  let manualOrder = prop($$props, "manualOrder", 28, () => ({}));
  let reorderEnabled = prop($$props, "reorderEnabled", 12, false);
  let treatNestedTasksAsSubtasks = prop($$props, "treatNestedTasksAsSubtasks", 12, false);
  let headerHeight = mutable_source(64);
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    set(tasksByPrimary, Object.fromEntries(matrix().primaryAxis.map((bucket) => [
      bucket.id,
      Object.values(matrix().cells[bucket.id] || {}).flatMap((cell) => cell.tasks)
    ])));
  });
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    var _a5;
    set(showSwimlaneHeaders, matrix().secondaryAxis.length > 1 || matrix().secondaryAxis.length > 0 && !((_a5 = matrix().secondaryAxis[0].meta) == null ? void 0 : _a5.isDefault));
  });
  legacy_pre_effect(
    () => (get(showSwimlaneHeaders), deep_read_state(matrix()), deep_read_state(columnWidth())),
    () => {
      set(gridTemplateColumns, [
        ...get(showSwimlaneHeaders) ? ["56px"] : [],
        ...matrix().primaryAxis.map((b) => b.collapsed ? "48px" : columnWidth())
      ].join(" "));
    }
  );
  legacy_pre_effect(() => get(showSwimlaneHeaders), () => {
    set(primaryGridColumnOffset, get(showSwimlaneHeaders) ? 2 : 1);
  });
  legacy_pre_effect(() => deep_read_state(matrix()), () => {
    set(gridTemplateRows, (() => {
      const rows = ["max-content"];
      for (let i = 0; i < matrix().secondaryAxis.length; i++) {
        rows.push(i === matrix().secondaryAxis.length - 1 ? "minmax(188px, 1fr)" : "minmax(188px, max-content)");
      }
      return rows.join(" ");
    })());
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get app() {
      return app();
    },
    set app($$value) {
      app($$value);
      flushSync();
    },
    get matrix() {
      return matrix();
    },
    set matrix($$value) {
      matrix($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get columnTagTableStore() {
      return columnTagTableStore();
    },
    set columnTagTableStore($$value) {
      columnTagTableStore($$value);
      flushSync();
    },
    get columnColourTableStore() {
      return columnColourTableStore();
    },
    set columnColourTableStore($$value) {
      columnColourTableStore($$value);
      flushSync();
    },
    get columnMatchTagTableStore() {
      return columnMatchTagTableStore();
    },
    set columnMatchTagTableStore($$value) {
      columnMatchTagTableStore($$value);
      flushSync();
    },
    get columnSubtitleTableStore() {
      return columnSubtitleTableStore();
    },
    set columnSubtitleTableStore($$value) {
      columnSubtitleTableStore($$value);
      flushSync();
    },
    get showFilepath() {
      return showFilepath();
    },
    set showFilepath($$value) {
      showFilepath($$value);
      flushSync();
    },
    get propertyDisplay() {
      return propertyDisplay();
    },
    set propertyDisplay($$value) {
      propertyDisplay($$value);
      flushSync();
    },
    get propertySchemaOption() {
      return propertySchemaOption();
    },
    set propertySchemaOption($$value) {
      propertySchemaOption($$value);
      flushSync();
    },
    get consolidateTags() {
      return consolidateTags();
    },
    set consolidateTags($$value) {
      consolidateTags($$value);
      flushSync();
    },
    get excludedTags() {
      return excludedTags();
    },
    set excludedTags($$value) {
      excludedTags($$value);
      flushSync();
    },
    get targetTaskFile() {
      return targetTaskFile();
    },
    set targetTaskFile($$value) {
      targetTaskFile($$value);
      flushSync();
    },
    get targetFileIsDefault() {
      return targetFileIsDefault();
    },
    set targetFileIsDefault($$value) {
      targetFileIsDefault($$value);
      flushSync();
    },
    get onToggleCollapse() {
      return onToggleCollapse();
    },
    set onToggleCollapse($$value) {
      onToggleCollapse($$value);
      flushSync();
    },
    get uncategorizedColumnName() {
      return uncategorizedColumnName();
    },
    set uncategorizedColumnName($$value) {
      uncategorizedColumnName($$value);
      flushSync();
    },
    get doneColumnName() {
      return doneColumnName();
    },
    set doneColumnName($$value) {
      doneColumnName($$value);
      flushSync();
    },
    get columnWidth() {
      return columnWidth();
    },
    set columnWidth($$value) {
      columnWidth($$value);
      flushSync();
    },
    get isManualOrder() {
      return isManualOrder();
    },
    set isManualOrder($$value) {
      isManualOrder($$value);
      flushSync();
    },
    get manualOrder() {
      return manualOrder();
    },
    set manualOrder($$value) {
      manualOrder($$value);
      flushSync();
    },
    get reorderEnabled() {
      return reorderEnabled();
    },
    set reorderEnabled($$value) {
      reorderEnabled($$value);
      flushSync();
    },
    get treatNestedTasksAsSubtasks() {
      return treatNestedTasksAsSubtasks();
    },
    set treatNestedTasksAsSubtasks($$value) {
      treatNestedTasksAsSubtasks($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root_46();
  let styles;
  var node = child(div);
  {
    var consequent = ($$anchor2) => {
      var div_1 = root13();
      set_style(div_1, "", {}, { "grid-column": "1", "grid-row": "1" });
      bind_element_size(div_1, "clientHeight", ($$value) => set(headerHeight, $$value));
      append($$anchor2, div_1);
    };
    if_block(node, ($$render) => {
      if (get(showSwimlaneHeaders)) $$render(consequent);
    });
  }
  var node_1 = sibling(node, 2);
  each(
    node_1,
    3,
    () => (deep_read_state(matrix()), untrack(() => matrix().primaryAxis)),
    (pBucket) => pBucket.id,
    ($$anchor2, pBucket, index2) => {
      var div_2 = root_112();
      let classes;
      let styles_1;
      var node_2 = child(div_2);
      {
        let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
          var _a5;
          return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
        })));
        ColumnHeader(node_2, {
          get column() {
            return get(pBucket), untrack(() => get(pBucket).id);
          },
          get tasks() {
            return get($0);
          },
          get taskActions() {
            return taskActions();
          },
          get columnTagTableStore() {
            return columnTagTableStore();
          },
          get columnColourTableStore() {
            return columnColourTableStore();
          },
          get columnMatchTagTableStore() {
            return columnMatchTagTableStore();
          },
          get columnSubtitleTableStore() {
            return columnSubtitleTableStore();
          },
          isVerticalFlow: false,
          get isCollapsed() {
            return get(pBucket), untrack(() => get(pBucket).collapsed);
          },
          onToggleCollapse: () => onToggleCollapse()(get(pBucket).id),
          get uncategorizedColumnName() {
            return uncategorizedColumnName();
          },
          get doneColumnName() {
            return doneColumnName();
          }
        });
      }
      reset(div_2);
      template_effect(() => {
        classes = set_class(div_2, 1, "header-wrapper svelte-1j479gc", null, classes, { collapsed: get(pBucket).collapsed });
        styles_1 = set_style(div_2, "", styles_1, {
          "grid-column": get(index2) + get(primaryGridColumnOffset),
          "grid-row": (get(pBucket), untrack(() => get(pBucket).collapsed ? "1 / -1" : "1")),
          "--column-color": (get(pBucket), untrack(() => {
            var _a5;
            return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
          }))
        });
      });
      append($$anchor2, div_2);
    }
  );
  var node_3 = sibling(node_1, 2);
  each(
    node_3,
    3,
    () => (deep_read_state(matrix()), untrack(() => matrix().secondaryAxis)),
    (sBucket) => sBucket.id,
    ($$anchor2, sBucket, sIndex) => {
      var fragment = root_36();
      var node_4 = first_child(fragment);
      {
        var consequent_1 = ($$anchor3) => {
          var div_3 = root_28();
          let styles_2;
          var span = child(div_3);
          var text2 = child(span, true);
          reset(span);
          reset(div_3);
          template_effect(() => {
            styles_2 = set_style(div_3, "", styles_2, { "grid-column": "1", "grid-row": get(sIndex) + 2 });
            set_attribute2(span, "title", (get(sBucket), untrack(() => get(sBucket).label)));
            set_text(text2, (get(sBucket), untrack(() => get(sBucket).label)));
          });
          append($$anchor3, div_3);
        };
        if_block(node_4, ($$render) => {
          if (get(showSwimlaneHeaders)) $$render(consequent_1);
        });
      }
      var node_5 = sibling(node_4, 2);
      each(
        node_5,
        3,
        () => (deep_read_state(matrix()), untrack(() => matrix().primaryAxis)),
        (pBucket) => pBucket.id,
        ($$anchor3, pBucket, pIndex) => {
          var div_4 = root_112();
          let classes_1;
          let styles_3;
          var node_6 = child(div_4);
          {
            let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
              var _a5;
              return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
            })));
            let $1 = derived_safe_equal(() => (get(pBucket), untrack(() => {
              var _a5;
              return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
            })));
            let $2 = derived_safe_equal(() => (deep_read_state(manualOrder()), get(sBucket), get(pBucket), untrack(() => {
              var _a5;
              return (_a5 = manualOrder()[get(sBucket).id]) == null ? void 0 : _a5[get(pBucket).id];
            })));
            BoardCell(node_6, {
              get app() {
                return app();
              },
              get cell() {
                return deep_read_state(matrix()), get(pBucket), get(sBucket), untrack(() => matrix().cells[get(pBucket).id][get(sBucket).id]);
              },
              get primaryTasks() {
                return get($0);
              },
              get secondaryAxisBucket() {
                return get(sBucket);
              },
              get primaryAxisLabel() {
                return get(pBucket), untrack(() => get(pBucket).label);
              },
              get taskActions() {
                return taskActions();
              },
              get columnTagTableStore() {
                return columnTagTableStore();
              },
              get showFilepath() {
                return showFilepath();
              },
              get propertyDisplay() {
                return propertyDisplay();
              },
              get propertySchemaOption() {
                return propertySchemaOption();
              },
              get consolidateTags() {
                return consolidateTags();
              },
              get excludedTags() {
                return excludedTags();
              },
              get treatNestedTasksAsSubtasks() {
                return treatNestedTasksAsSubtasks();
              },
              isVerticalFlow: false,
              get targetTaskFile() {
                return targetTaskFile();
              },
              get targetFileIsDefault() {
                return targetFileIsDefault();
              },
              get doneColumnName() {
                return doneColumnName();
              },
              get isCollapsed() {
                return get(pBucket), untrack(() => get(pBucket).collapsed);
              },
              get accentColor() {
                return get($1);
              },
              get isManualOrder() {
                return isManualOrder();
              },
              get manualOrderEntries() {
                return get($2);
              },
              get reorderEnabled() {
                return reorderEnabled();
              }
            });
          }
          reset(div_4);
          template_effect(() => {
            classes_1 = set_class(div_4, 1, "cell-wrapper svelte-1j479gc", null, classes_1, { collapsed: get(pBucket).collapsed });
            styles_3 = set_style(div_4, "", styles_3, {
              "grid-column": get(pIndex) + get(primaryGridColumnOffset),
              "grid-row": get(sIndex) + 2,
              "--column-color": (get(pBucket), untrack(() => {
                var _a5;
                return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
              }))
            });
          });
          append($$anchor3, div_4);
        }
      );
      append($$anchor2, fragment);
    }
  );
  reset(div);
  template_effect(() => {
    var _a5;
    return styles = set_style(div, "", styles, {
      "grid-template-columns": get(gridTemplateColumns),
      "grid-template-rows": get(gridTemplateRows),
      "--header-height": `${(_a5 = get(headerHeight)) != null ? _a5 : ""}px`,
      "--sticky-left-offset": get(showSwimlaneHeaders) ? "56px" : "0px"
    });
  });
  append($$anchor, div);
  return pop($$exports);
}

// src/ui/board/board_matrix.ts
function deriveBoardMatrix(tasks, columns, settings) {
  var _a5, _b3, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
  const tasksByPrimary = {
    uncategorised: [],
    done: []
  };
  for (const column of columns) {
    tasksByPrimary[column.id] = [];
  }
  for (const task of tasks) {
    if (task.done || task.column === "done") {
      tasksByPrimary["done"].push(task);
    } else if (task.column === "archived") {
    } else if (task.column) {
      if (!tasksByPrimary[task.column]) {
        tasksByPrimary[task.column] = [];
      }
      tasksByPrimary[task.column].push(task);
    } else {
      tasksByPrimary["uncategorised"].push(task);
    }
  }
  const orderMode = (_a5 = settings.columnOrderMode) != null ? _a5 : "file" /* FileOrder */;
  const sortProperty = (_b3 = settings.sortProperty) != null ? _b3 : null;
  const sortDirection = (_c2 = settings.sortDirection) != null ? _c2 : "asc";
  const useProperty = orderMode === "property" /* Property */ && !!sortProperty;
  const useManual = orderMode === "manual" /* Manual */;
  const manualOrder = (_d = settings.manualOrder) != null ? _d : {};
  for (const bucketTasks of Object.values(tasksByPrimary)) {
    if (orderMode === "task-name" /* TaskName */) {
      sortTasksByTaskName(bucketTasks, sortDirection);
    } else if (useProperty && sortProperty) {
      sortTasksByProperty(
        bucketTasks,
        sortProperty,
        sortDirection,
        (_e = settings.statusMarkerOrder) != null ? _e : "",
        (_f = settings.doneStatusMarkers) != null ? _f : ""
      );
    } else {
      sortTasksByFile(bucketTasks);
    }
  }
  const collapsedColumns = new Set((_g = settings.collapsedColumns) != null ? _g : []);
  const uncategorizedVisibility = (_h = settings.uncategorizedVisibility) != null ? _h : "auto" /* Auto */;
  const showUncategorizedColumn = uncategorizedVisibility === "always" /* AlwaysShow */ || uncategorizedVisibility === "auto" /* Auto */ && tasksByPrimary["uncategorised"].length > 0;
  const doneVisibility = (_i = settings.doneVisibility) != null ? _i : "always" /* AlwaysShow */;
  const showDoneColumn = doneVisibility === "always" /* AlwaysShow */ || doneVisibility === "auto" /* Auto */ && tasksByPrimary["done"].length > 0;
  const allColumns = [];
  if (showUncategorizedColumn) allColumns.push("uncategorised");
  for (const column of columns) {
    allColumns.push(column.id);
  }
  if (showDoneColumn) allColumns.push("done");
  const flowDirection = (_j = settings.flowDirection) != null ? _j : "ltr" /* LeftToRight */;
  const shouldReverse = flowDirection === "rtl" /* RightToLeft */ || flowDirection === "btt" /* BottomToTop */;
  if (shouldReverse) {
    allColumns.reverse();
  }
  const primaryAxis = allColumns.map((id) => {
    let label = id;
    let color = void 0;
    const colDef = columns.find((c) => c.id === id);
    if (id === "uncategorised") {
      label = settings.uncategorizedColumnName || "Uncategorized";
    } else if (id === "done") {
      label = settings.doneColumnName || "Done";
    } else {
      if (colDef) {
        label = colDef.label;
        color = colDef.color;
      }
    }
    return {
      id,
      label,
      kind: "column",
      collapsed: collapsedColumns.has(id),
      meta: { color }
    };
  });
  const groupSource = (_k = settings.groupSource) != null ? _k : { kind: "none" };
  const groupBuckets = deriveGroupBuckets(
    Object.values(tasksByPrimary).flat(),
    groupSource,
    settings.excludedTags,
    (_l = settings.statusMarkerOrder) != null ? _l : "",
    (_m = settings.doneStatusMarkers) != null ? _m : "",
    (_n = settings.groupDirection) != null ? _n : "asc"
  );
  const assignTaskToBucket = createGroupAssigner(groupBuckets, groupSource, settings.excludedTags);
  const secondaryAxis = groupBuckets.map((bucket) => ({
    id: bucket.id,
    label: bucket.label,
    kind: "group",
    collapsed: false,
    meta: {
      value: bucket.value,
      source: bucket.source,
      isDefault: bucket.isDefault
    }
  }));
  const cells = {};
  for (const primaryBucket of primaryAxis) {
    const pId = primaryBucket.id;
    cells[pId] = {};
    const cellTasksByPrimary = (_o = tasksByPrimary[pId]) != null ? _o : [];
    const cellTasksBySecondary = /* @__PURE__ */ new Map();
    for (const task of cellTasksByPrimary) {
      const sId = assignTaskToBucket(task);
      if (sId === void 0) continue;
      let bucketTasks = cellTasksBySecondary.get(sId);
      if (!bucketTasks) {
        bucketTasks = [];
        cellTasksBySecondary.set(sId, bucketTasks);
      }
      bucketTasks.push(task);
    }
    for (const groupBucket of groupBuckets) {
      const sId = groupBucket.id;
      const cellTasks = (_p = cellTasksBySecondary.get(sId)) != null ? _p : [];
      const orderedCellTasks = useManual ? computeDisplayOrder(cellTasks, (_q = manualOrder[sId]) == null ? void 0 : _q[pId]) : cellTasks;
      cells[pId][sId] = {
        primaryId: pId,
        secondaryId: sId,
        tasks: orderedCellTasks,
        isEmpty: orderedCellTasks.length === 0
      };
    }
  }
  return {
    primaryAxis,
    secondaryAxis,
    cells
  };
}
function sortTasksByFile(tasks) {
  tasks.sort(compareByFile);
}
function compareByFile(a, b) {
  if (a.path === b.path) {
    return a.rowIndex - b.rowIndex;
  }
  return a.path.localeCompare(b.path);
}
function sortTasksByProperty(tasks, key2, direction, statusMarkerOrder, doneStatusMarkers) {
  tasks.sort((a, b) => {
    const result = compareByProperty(a, b, key2, direction, { statusMarkerOrder, doneStatusMarkers });
    return result !== 0 ? result : compareByFile(a, b);
  });
}
function sortTasksByTaskName(tasks, direction) {
  tasks.sort((a, b) => {
    const result = a.content.trim().localeCompare(b.content.trim());
    if (result !== 0) {
      return direction === "desc" ? -result : result;
    }
    return compareByFile(a, b);
  });
}

// node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs
var min = Math.min;
var max = Math.max;
var round = Math.round;
var floor = Math.floor;
var createCoords = (v) => ({
  x: v,
  y: v
});
var oppositeSideMap = {
  left: "right",
  right: "left",
  bottom: "top",
  top: "bottom"
};
var oppositeAlignmentMap = {
  start: "end",
  end: "start"
};
function clamp(start, value, end) {
  return max(start, min(value, end));
}
function evaluate(value, param) {
  return typeof value === "function" ? value(param) : value;
}
function getSide(placement) {
  return placement.split("-")[0];
}
function getAlignment(placement) {
  return placement.split("-")[1];
}
function getOppositeAxis(axis) {
  return axis === "x" ? "y" : "x";
}
function getAxisLength(axis) {
  return axis === "y" ? "height" : "width";
}
function getSideAxis(placement) {
  return ["top", "bottom"].includes(getSide(placement)) ? "y" : "x";
}
function getAlignmentAxis(placement) {
  return getOppositeAxis(getSideAxis(placement));
}
function getAlignmentSides(placement, rects, rtl) {
  if (rtl === void 0) {
    rtl = false;
  }
  const alignment = getAlignment(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const length = getAxisLength(alignmentAxis);
  let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
  if (rects.reference[length] > rects.floating[length]) {
    mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
  }
  return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
}
function getExpandedPlacements(placement) {
  const oppositePlacement = getOppositePlacement(placement);
  return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
}
function getOppositeAlignmentPlacement(placement) {
  return placement.replace(/start|end/g, (alignment) => oppositeAlignmentMap[alignment]);
}
function getSideList(side, isStart, rtl) {
  const lr = ["left", "right"];
  const rl = ["right", "left"];
  const tb = ["top", "bottom"];
  const bt = ["bottom", "top"];
  switch (side) {
    case "top":
    case "bottom":
      if (rtl) return isStart ? rl : lr;
      return isStart ? lr : rl;
    case "left":
    case "right":
      return isStart ? tb : bt;
    default:
      return [];
  }
}
function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
  const alignment = getAlignment(placement);
  let list = getSideList(getSide(placement), direction === "start", rtl);
  if (alignment) {
    list = list.map((side) => side + "-" + alignment);
    if (flipAlignment) {
      list = list.concat(list.map(getOppositeAlignmentPlacement));
    }
  }
  return list;
}
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, (side) => oppositeSideMap[side]);
}
function expandPaddingObject(padding) {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    ...padding
  };
}
function getPaddingObject(padding) {
  return typeof padding !== "number" ? expandPaddingObject(padding) : {
    top: padding,
    right: padding,
    bottom: padding,
    left: padding
  };
}
function rectToClientRect(rect) {
  return {
    ...rect,
    top: rect.y,
    left: rect.x,
    right: rect.x + rect.width,
    bottom: rect.y + rect.height
  };
}

// node_modules/@floating-ui/core/dist/floating-ui.core.mjs
function computeCoordsFromPlacement(_ref, placement, rtl) {
  let {
    reference,
    floating
  } = _ref;
  const sideAxis = getSideAxis(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const alignLength = getAxisLength(alignmentAxis);
  const side = getSide(placement);
  const isVertical = sideAxis === "y";
  const commonX = reference.x + reference.width / 2 - floating.width / 2;
  const commonY = reference.y + reference.height / 2 - floating.height / 2;
  const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
  let coords;
  switch (side) {
    case "top":
      coords = {
        x: commonX,
        y: reference.y - floating.height
      };
      break;
    case "bottom":
      coords = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;
    case "right":
      coords = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;
    case "left":
      coords = {
        x: reference.x - floating.width,
        y: commonY
      };
      break;
    default:
      coords = {
        x: reference.x,
        y: reference.y
      };
  }
  switch (getAlignment(placement)) {
    case "start":
      coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
      break;
    case "end":
      coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
      break;
  }
  return coords;
}
var computePosition = async (reference, floating, config) => {
  const {
    placement = "bottom",
    strategy = "absolute",
    middleware = [],
    platform: platform2
  } = config;
  const validMiddleware = middleware.filter(Boolean);
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(floating));
  let rects = await platform2.getElementRects({
    reference,
    floating,
    strategy
  });
  let {
    x,
    y
  } = computeCoordsFromPlacement(rects, placement, rtl);
  let statefulPlacement = placement;
  let middlewareData = {};
  let resetCount = 0;
  for (let i = 0; i < validMiddleware.length; i++) {
    const {
      name,
      fn
    } = validMiddleware[i];
    const {
      x: nextX,
      y: nextY,
      data,
      reset: reset2
    } = await fn({
      x,
      y,
      initialPlacement: placement,
      placement: statefulPlacement,
      strategy,
      middlewareData,
      rects,
      platform: platform2,
      elements: {
        reference,
        floating
      }
    });
    x = nextX != null ? nextX : x;
    y = nextY != null ? nextY : y;
    middlewareData = {
      ...middlewareData,
      [name]: {
        ...middlewareData[name],
        ...data
      }
    };
    if (reset2 && resetCount <= 50) {
      resetCount++;
      if (typeof reset2 === "object") {
        if (reset2.placement) {
          statefulPlacement = reset2.placement;
        }
        if (reset2.rects) {
          rects = reset2.rects === true ? await platform2.getElementRects({
            reference,
            floating,
            strategy
          }) : reset2.rects;
        }
        ({
          x,
          y
        } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
      }
      i = -1;
    }
  }
  return {
    x,
    y,
    placement: statefulPlacement,
    strategy,
    middlewareData
  };
};
async function detectOverflow(state2, options2) {
  var _await$platform$isEle;
  if (options2 === void 0) {
    options2 = {};
  }
  const {
    x,
    y,
    platform: platform2,
    rects,
    elements,
    strategy
  } = state2;
  const {
    boundary: boundary2 = "clippingAncestors",
    rootBoundary = "viewport",
    elementContext = "floating",
    altBoundary = false,
    padding = 0
  } = evaluate(options2, state2);
  const paddingObject = getPaddingObject(padding);
  const altContext = elementContext === "floating" ? "reference" : "floating";
  const element2 = elements[altBoundary ? altContext : elementContext];
  const clippingClientRect = rectToClientRect(await platform2.getClippingRect({
    element: ((_await$platform$isEle = await (platform2.isElement == null ? void 0 : platform2.isElement(element2))) != null ? _await$platform$isEle : true) ? element2 : element2.contextElement || await (platform2.getDocumentElement == null ? void 0 : platform2.getDocumentElement(elements.floating)),
    boundary: boundary2,
    rootBoundary,
    strategy
  }));
  const rect = elementContext === "floating" ? {
    ...rects.floating,
    x,
    y
  } : rects.reference;
  const offsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(elements.floating));
  const offsetScale = await (platform2.isElement == null ? void 0 : platform2.isElement(offsetParent)) ? await (platform2.getScale == null ? void 0 : platform2.getScale(offsetParent)) || {
    x: 1,
    y: 1
  } : {
    x: 1,
    y: 1
  };
  const elementClientRect = rectToClientRect(platform2.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform2.convertOffsetParentRelativeRectToViewportRelativeRect({
    elements,
    rect,
    offsetParent,
    strategy
  }) : rect);
  return {
    top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
    bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
    left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
    right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
  };
}
var flip = function(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  return {
    name: "flip",
    options: options2,
    async fn(state2) {
      var _middlewareData$arrow, _middlewareData$flip;
      const {
        placement,
        middlewareData,
        rects,
        initialPlacement,
        platform: platform2,
        elements
      } = state2;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = true,
        fallbackPlacements: specifiedFallbackPlacements,
        fallbackStrategy = "bestFit",
        fallbackAxisSideDirection = "none",
        flipAlignment = true,
        ...detectOverflowOptions
      } = evaluate(options2, state2);
      if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      const side = getSide(placement);
      const isBasePlacement = getSide(initialPlacement) === initialPlacement;
      const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
      const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
      if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== "none") {
        fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
      }
      const placements2 = [initialPlacement, ...fallbackPlacements];
      const overflow = await detectOverflow(state2, detectOverflowOptions);
      const overflows = [];
      let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
      if (checkMainAxis) {
        overflows.push(overflow[side]);
      }
      if (checkCrossAxis) {
        const sides2 = getAlignmentSides(placement, rects, rtl);
        overflows.push(overflow[sides2[0]], overflow[sides2[1]]);
      }
      overflowsData = [...overflowsData, {
        placement,
        overflows
      }];
      if (!overflows.every((side2) => side2 <= 0)) {
        var _middlewareData$flip2, _overflowsData$filter;
        const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
        const nextPlacement = placements2[nextIndex];
        if (nextPlacement) {
          return {
            data: {
              index: nextIndex,
              overflows: overflowsData
            },
            reset: {
              placement: nextPlacement
            }
          };
        }
        let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
        if (!resetPlacement) {
          switch (fallbackStrategy) {
            case "bestFit": {
              var _overflowsData$map$so;
              const placement2 = (_overflowsData$map$so = overflowsData.map((d) => [d.placement, d.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0];
              if (placement2) {
                resetPlacement = placement2;
              }
              break;
            }
            case "initialPlacement":
              resetPlacement = initialPlacement;
              break;
          }
        }
        if (placement !== resetPlacement) {
          return {
            reset: {
              placement: resetPlacement
            }
          };
        }
      }
      return {};
    }
  };
};
async function convertValueToCoords(state2, options2) {
  const {
    placement,
    platform: platform2,
    elements
  } = state2;
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
  const side = getSide(placement);
  const alignment = getAlignment(placement);
  const isVertical = getSideAxis(placement) === "y";
  const mainAxisMulti = ["left", "top"].includes(side) ? -1 : 1;
  const crossAxisMulti = rtl && isVertical ? -1 : 1;
  const rawValue = evaluate(options2, state2);
  let {
    mainAxis,
    crossAxis,
    alignmentAxis
  } = typeof rawValue === "number" ? {
    mainAxis: rawValue,
    crossAxis: 0,
    alignmentAxis: null
  } : {
    mainAxis: 0,
    crossAxis: 0,
    alignmentAxis: null,
    ...rawValue
  };
  if (alignment && typeof alignmentAxis === "number") {
    crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
  }
  return isVertical ? {
    x: crossAxis * crossAxisMulti,
    y: mainAxis * mainAxisMulti
  } : {
    x: mainAxis * mainAxisMulti,
    y: crossAxis * crossAxisMulti
  };
}
var offset = function(options2) {
  if (options2 === void 0) {
    options2 = 0;
  }
  return {
    name: "offset",
    options: options2,
    async fn(state2) {
      var _middlewareData$offse, _middlewareData$arrow;
      const {
        x,
        y,
        placement,
        middlewareData
      } = state2;
      const diffCoords = await convertValueToCoords(state2, options2);
      if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      return {
        x: x + diffCoords.x,
        y: y + diffCoords.y,
        data: {
          ...diffCoords,
          placement
        }
      };
    }
  };
};
var shift = function(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  return {
    name: "shift",
    options: options2,
    async fn(state2) {
      const {
        x,
        y,
        placement
      } = state2;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = false,
        limiter = {
          fn: (_ref) => {
            let {
              x: x2,
              y: y2
            } = _ref;
            return {
              x: x2,
              y: y2
            };
          }
        },
        ...detectOverflowOptions
      } = evaluate(options2, state2);
      const coords = {
        x,
        y
      };
      const overflow = await detectOverflow(state2, detectOverflowOptions);
      const crossAxis = getSideAxis(getSide(placement));
      const mainAxis = getOppositeAxis(crossAxis);
      let mainAxisCoord = coords[mainAxis];
      let crossAxisCoord = coords[crossAxis];
      if (checkMainAxis) {
        const minSide = mainAxis === "y" ? "top" : "left";
        const maxSide = mainAxis === "y" ? "bottom" : "right";
        const min2 = mainAxisCoord + overflow[minSide];
        const max2 = mainAxisCoord - overflow[maxSide];
        mainAxisCoord = clamp(min2, mainAxisCoord, max2);
      }
      if (checkCrossAxis) {
        const minSide = crossAxis === "y" ? "top" : "left";
        const maxSide = crossAxis === "y" ? "bottom" : "right";
        const min2 = crossAxisCoord + overflow[minSide];
        const max2 = crossAxisCoord - overflow[maxSide];
        crossAxisCoord = clamp(min2, crossAxisCoord, max2);
      }
      const limitedCoords = limiter.fn({
        ...state2,
        [mainAxis]: mainAxisCoord,
        [crossAxis]: crossAxisCoord
      });
      return {
        ...limitedCoords,
        data: {
          x: limitedCoords.x - x,
          y: limitedCoords.y - y
        }
      };
    }
  };
};

// node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs
function getNodeName(node) {
  if (isNode(node)) {
    return (node.nodeName || "").toLowerCase();
  }
  return "#document";
}
function getWindow(node) {
  var _node$ownerDocument;
  return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node) {
  var _ref;
  return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode(value) {
  return value instanceof Node || value instanceof getWindow(value).Node;
}
function isElement(value) {
  return value instanceof Element || value instanceof getWindow(value).Element;
}
function isHTMLElement(value) {
  return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
}
function isShadowRoot(value) {
  if (typeof ShadowRoot === "undefined") {
    return false;
  }
  return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
}
function isOverflowElement(element2) {
  const {
    overflow,
    overflowX,
    overflowY,
    display
  } = getComputedStyle2(element2);
  return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !["inline", "contents"].includes(display);
}
function isTableElement(element2) {
  return ["table", "td", "th"].includes(getNodeName(element2));
}
function isContainingBlock(element2) {
  const webkit = isWebKit();
  const css = getComputedStyle2(element2);
  return css.transform !== "none" || css.perspective !== "none" || (css.containerType ? css.containerType !== "normal" : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== "none" : false) || !webkit && (css.filter ? css.filter !== "none" : false) || ["transform", "perspective", "filter"].some((value) => (css.willChange || "").includes(value)) || ["paint", "layout", "strict", "content"].some((value) => (css.contain || "").includes(value));
}
function getContainingBlock(element2) {
  let currentNode = getParentNode(element2);
  while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
    if (isContainingBlock(currentNode)) {
      return currentNode;
    } else {
      currentNode = getParentNode(currentNode);
    }
  }
  return null;
}
function isWebKit() {
  if (typeof CSS === "undefined" || !CSS.supports) return false;
  return CSS.supports("-webkit-backdrop-filter", "none");
}
function isLastTraversableNode(node) {
  return ["html", "body", "#document"].includes(getNodeName(node));
}
function getComputedStyle2(element2) {
  return getWindow(element2).getComputedStyle(element2);
}
function getNodeScroll(element2) {
  if (isElement(element2)) {
    return {
      scrollLeft: element2.scrollLeft,
      scrollTop: element2.scrollTop
    };
  }
  return {
    scrollLeft: element2.pageXOffset,
    scrollTop: element2.pageYOffset
  };
}
function getParentNode(node) {
  if (getNodeName(node) === "html") {
    return node;
  }
  const result = (
    // Step into the shadow DOM of the parent of a slotted node.
    node.assignedSlot || // DOM Element detected.
    node.parentNode || // ShadowRoot detected.
    isShadowRoot(node) && node.host || // Fallback.
    getDocumentElement(node)
  );
  return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node) {
  const parentNode = getParentNode(node);
  if (isLastTraversableNode(parentNode)) {
    return node.ownerDocument ? node.ownerDocument.body : node.body;
  }
  if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
    return parentNode;
  }
  return getNearestOverflowAncestor(parentNode);
}
function getOverflowAncestors(node, list, traverseIframes) {
  var _node$ownerDocument2;
  if (list === void 0) {
    list = [];
  }
  if (traverseIframes === void 0) {
    traverseIframes = true;
  }
  const scrollableAncestor = getNearestOverflowAncestor(node);
  const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
  const win = getWindow(scrollableAncestor);
  if (isBody) {
    return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : []);
  }
  return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}

// node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs
function getCssDimensions(element2) {
  const css = getComputedStyle2(element2);
  let width = parseFloat(css.width) || 0;
  let height = parseFloat(css.height) || 0;
  const hasOffset = isHTMLElement(element2);
  const offsetWidth = hasOffset ? element2.offsetWidth : width;
  const offsetHeight = hasOffset ? element2.offsetHeight : height;
  const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
  if (shouldFallback) {
    width = offsetWidth;
    height = offsetHeight;
  }
  return {
    width,
    height,
    $: shouldFallback
  };
}
function unwrapElement(element2) {
  return !isElement(element2) ? element2.contextElement : element2;
}
function getScale(element2) {
  const domElement = unwrapElement(element2);
  if (!isHTMLElement(domElement)) {
    return createCoords(1);
  }
  const rect = domElement.getBoundingClientRect();
  const {
    width,
    height,
    $
  } = getCssDimensions(domElement);
  let x = ($ ? round(rect.width) : rect.width) / width;
  let y = ($ ? round(rect.height) : rect.height) / height;
  if (!x || !Number.isFinite(x)) {
    x = 1;
  }
  if (!y || !Number.isFinite(y)) {
    y = 1;
  }
  return {
    x,
    y
  };
}
var noOffsets = /* @__PURE__ */ createCoords(0);
function getVisualOffsets(element2) {
  const win = getWindow(element2);
  if (!isWebKit() || !win.visualViewport) {
    return noOffsets;
  }
  return {
    x: win.visualViewport.offsetLeft,
    y: win.visualViewport.offsetTop
  };
}
function shouldAddVisualOffsets(element2, isFixed, floatingOffsetParent) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element2)) {
    return false;
  }
  return isFixed;
}
function getBoundingClientRect(element2, includeScale, isFixedStrategy, offsetParent) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  const clientRect = element2.getBoundingClientRect();
  const domElement = unwrapElement(element2);
  let scale = createCoords(1);
  if (includeScale) {
    if (offsetParent) {
      if (isElement(offsetParent)) {
        scale = getScale(offsetParent);
      }
    } else {
      scale = getScale(element2);
    }
  }
  const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
  let x = (clientRect.left + visualOffsets.x) / scale.x;
  let y = (clientRect.top + visualOffsets.y) / scale.y;
  let width = clientRect.width / scale.x;
  let height = clientRect.height / scale.y;
  if (domElement) {
    const win = getWindow(domElement);
    const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
    let currentWin = win;
    let currentIFrame = currentWin.frameElement;
    while (currentIFrame && offsetParent && offsetWin !== currentWin) {
      const iframeScale = getScale(currentIFrame);
      const iframeRect = currentIFrame.getBoundingClientRect();
      const css = getComputedStyle2(currentIFrame);
      const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
      const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
      x *= iframeScale.x;
      y *= iframeScale.y;
      width *= iframeScale.x;
      height *= iframeScale.y;
      x += left;
      y += top;
      currentWin = getWindow(currentIFrame);
      currentIFrame = currentWin.frameElement;
    }
  }
  return rectToClientRect({
    width,
    height,
    x,
    y
  });
}
var topLayerSelectors = [":popover-open", ":modal"];
function isTopLayer(element2) {
  return topLayerSelectors.some((selector) => {
    try {
      return element2.matches(selector);
    } catch (e) {
      return false;
    }
  });
}
function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
  let {
    elements,
    rect,
    offsetParent,
    strategy
  } = _ref;
  const isFixed = strategy === "fixed";
  const documentElement = getDocumentElement(offsetParent);
  const topLayer = elements ? isTopLayer(elements.floating) : false;
  if (offsetParent === documentElement || topLayer && isFixed) {
    return rect;
  }
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  let scale = createCoords(1);
  const offsets = createCoords(0);
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isHTMLElement(offsetParent)) {
      const offsetRect = getBoundingClientRect(offsetParent);
      scale = getScale(offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    }
  }
  return {
    width: rect.width * scale.x,
    height: rect.height * scale.y,
    x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x,
    y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y
  };
}
function getClientRects(element2) {
  return Array.from(element2.getClientRects());
}
function getWindowScrollBarX(element2) {
  return getBoundingClientRect(getDocumentElement(element2)).left + getNodeScroll(element2).scrollLeft;
}
function getDocumentRect(element2) {
  const html2 = getDocumentElement(element2);
  const scroll = getNodeScroll(element2);
  const body = element2.ownerDocument.body;
  const width = max(html2.scrollWidth, html2.clientWidth, body.scrollWidth, body.clientWidth);
  const height = max(html2.scrollHeight, html2.clientHeight, body.scrollHeight, body.clientHeight);
  let x = -scroll.scrollLeft + getWindowScrollBarX(element2);
  const y = -scroll.scrollTop;
  if (getComputedStyle2(body).direction === "rtl") {
    x += max(html2.clientWidth, body.clientWidth) - width;
  }
  return {
    width,
    height,
    x,
    y
  };
}
function getViewportRect(element2, strategy) {
  const win = getWindow(element2);
  const html2 = getDocumentElement(element2);
  const visualViewport = win.visualViewport;
  let width = html2.clientWidth;
  let height = html2.clientHeight;
  let x = 0;
  let y = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    const visualViewportBased = isWebKit();
    if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
      x = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }
  return {
    width,
    height,
    x,
    y
  };
}
function getInnerBoundingClientRect(element2, strategy) {
  const clientRect = getBoundingClientRect(element2, true, strategy === "fixed");
  const top = clientRect.top + element2.clientTop;
  const left = clientRect.left + element2.clientLeft;
  const scale = isHTMLElement(element2) ? getScale(element2) : createCoords(1);
  const width = element2.clientWidth * scale.x;
  const height = element2.clientHeight * scale.y;
  const x = left * scale.x;
  const y = top * scale.y;
  return {
    width,
    height,
    x,
    y
  };
}
function getClientRectFromClippingAncestor(element2, clippingAncestor, strategy) {
  let rect;
  if (clippingAncestor === "viewport") {
    rect = getViewportRect(element2, strategy);
  } else if (clippingAncestor === "document") {
    rect = getDocumentRect(getDocumentElement(element2));
  } else if (isElement(clippingAncestor)) {
    rect = getInnerBoundingClientRect(clippingAncestor, strategy);
  } else {
    const visualOffsets = getVisualOffsets(element2);
    rect = {
      ...clippingAncestor,
      x: clippingAncestor.x - visualOffsets.x,
      y: clippingAncestor.y - visualOffsets.y
    };
  }
  return rectToClientRect(rect);
}
function hasFixedPositionAncestor(element2, stopNode) {
  const parentNode = getParentNode(element2);
  if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
    return false;
  }
  return getComputedStyle2(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
}
function getClippingElementAncestors(element2, cache) {
  const cachedResult = cache.get(element2);
  if (cachedResult) {
    return cachedResult;
  }
  let result = getOverflowAncestors(element2, [], false).filter((el) => isElement(el) && getNodeName(el) !== "body");
  let currentContainingBlockComputedStyle = null;
  const elementIsFixed = getComputedStyle2(element2).position === "fixed";
  let currentNode = elementIsFixed ? getParentNode(element2) : element2;
  while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
    const computedStyle = getComputedStyle2(currentNode);
    const currentNodeIsContaining = isContainingBlock(currentNode);
    if (!currentNodeIsContaining && computedStyle.position === "fixed") {
      currentContainingBlockComputedStyle = null;
    }
    const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && ["absolute", "fixed"].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element2, currentNode);
    if (shouldDropCurrentNode) {
      result = result.filter((ancestor) => ancestor !== currentNode);
    } else {
      currentContainingBlockComputedStyle = computedStyle;
    }
    currentNode = getParentNode(currentNode);
  }
  cache.set(element2, result);
  return result;
}
function getClippingRect(_ref) {
  let {
    element: element2,
    boundary: boundary2,
    rootBoundary,
    strategy
  } = _ref;
  const elementClippingAncestors = boundary2 === "clippingAncestors" ? isTopLayer(element2) ? [] : getClippingElementAncestors(element2, this._c) : [].concat(boundary2);
  const clippingAncestors = [...elementClippingAncestors, rootBoundary];
  const firstClippingAncestor = clippingAncestors[0];
  const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
    const rect = getClientRectFromClippingAncestor(element2, clippingAncestor, strategy);
    accRect.top = max(rect.top, accRect.top);
    accRect.right = min(rect.right, accRect.right);
    accRect.bottom = min(rect.bottom, accRect.bottom);
    accRect.left = max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromClippingAncestor(element2, firstClippingAncestor, strategy));
  return {
    width: clippingRect.right - clippingRect.left,
    height: clippingRect.bottom - clippingRect.top,
    x: clippingRect.left,
    y: clippingRect.top
  };
}
function getDimensions(element2) {
  const {
    width,
    height
  } = getCssDimensions(element2);
  return {
    width,
    height
  };
}
function getRectRelativeToOffsetParent(element2, offsetParent, strategy) {
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  const documentElement = getDocumentElement(offsetParent);
  const isFixed = strategy === "fixed";
  const rect = getBoundingClientRect(element2, true, isFixed, offsetParent);
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  const offsets = createCoords(0);
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isOffsetParentAnElement) {
      const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX(documentElement);
    }
  }
  const x = rect.left + scroll.scrollLeft - offsets.x;
  const y = rect.top + scroll.scrollTop - offsets.y;
  return {
    x,
    y,
    width: rect.width,
    height: rect.height
  };
}
function isStaticPositioned(element2) {
  return getComputedStyle2(element2).position === "static";
}
function getTrueOffsetParent(element2, polyfill) {
  if (!isHTMLElement(element2) || getComputedStyle2(element2).position === "fixed") {
    return null;
  }
  if (polyfill) {
    return polyfill(element2);
  }
  return element2.offsetParent;
}
function getOffsetParent(element2, polyfill) {
  const win = getWindow(element2);
  if (isTopLayer(element2)) {
    return win;
  }
  if (!isHTMLElement(element2)) {
    let svgOffsetParent = getParentNode(element2);
    while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
      if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
        return svgOffsetParent;
      }
      svgOffsetParent = getParentNode(svgOffsetParent);
    }
    return win;
  }
  let offsetParent = getTrueOffsetParent(element2, polyfill);
  while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
    offsetParent = getTrueOffsetParent(offsetParent, polyfill);
  }
  if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
    return win;
  }
  return offsetParent || getContainingBlock(element2) || win;
}
var getElementRects = async function(data) {
  const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
  const getDimensionsFn = this.getDimensions;
  const floatingDimensions = await getDimensionsFn(data.floating);
  return {
    reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
    floating: {
      x: 0,
      y: 0,
      width: floatingDimensions.width,
      height: floatingDimensions.height
    }
  };
};
function isRTL(element2) {
  return getComputedStyle2(element2).direction === "rtl";
}
var platform = {
  convertOffsetParentRelativeRectToViewportRelativeRect,
  getDocumentElement,
  getClippingRect,
  getOffsetParent,
  getElementRects,
  getClientRects,
  getDimensions,
  getScale,
  isElement,
  isRTL
};
function observeMove(element2, onMove) {
  let io = null;
  let timeoutId;
  const root22 = getDocumentElement(element2);
  function cleanup() {
    var _io;
    clearTimeout(timeoutId);
    (_io = io) == null || _io.disconnect();
    io = null;
  }
  function refresh(skip, threshold) {
    if (skip === void 0) {
      skip = false;
    }
    if (threshold === void 0) {
      threshold = 1;
    }
    cleanup();
    const {
      left,
      top,
      width,
      height
    } = element2.getBoundingClientRect();
    if (!skip) {
      onMove();
    }
    if (!width || !height) {
      return;
    }
    const insetTop = floor(top);
    const insetRight = floor(root22.clientWidth - (left + width));
    const insetBottom = floor(root22.clientHeight - (top + height));
    const insetLeft = floor(left);
    const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
    const options2 = {
      rootMargin,
      threshold: max(0, min(1, threshold)) || 1
    };
    let isFirstUpdate = true;
    function handleObserve(entries) {
      const ratio = entries[0].intersectionRatio;
      if (ratio !== threshold) {
        if (!isFirstUpdate) {
          return refresh();
        }
        if (!ratio) {
          timeoutId = setTimeout(() => {
            refresh(false, 1e-7);
          }, 1e3);
        } else {
          refresh(false, ratio);
        }
      }
      isFirstUpdate = false;
    }
    try {
      io = new IntersectionObserver(handleObserve, {
        ...options2,
        // Handle <iframe>s
        root: root22.ownerDocument
      });
    } catch (e) {
      io = new IntersectionObserver(handleObserve, options2);
    }
    io.observe(element2);
  }
  refresh(true);
  return cleanup;
}
function autoUpdate(reference, floating, update2, options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  const {
    ancestorScroll = true,
    ancestorResize = true,
    elementResize = typeof ResizeObserver === "function",
    layoutShift = typeof IntersectionObserver === "function",
    animationFrame = false
  } = options2;
  const referenceEl = unwrapElement(reference);
  const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...getOverflowAncestors(floating)] : [];
  ancestors.forEach((ancestor) => {
    ancestorScroll && ancestor.addEventListener("scroll", update2, {
      passive: true
    });
    ancestorResize && ancestor.addEventListener("resize", update2);
  });
  const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update2) : null;
  let reobserveFrame = -1;
  let resizeObserver = null;
  if (elementResize) {
    resizeObserver = new ResizeObserver((_ref) => {
      let [firstEntry] = _ref;
      if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {
        resizeObserver.unobserve(floating);
        cancelAnimationFrame(reobserveFrame);
        reobserveFrame = requestAnimationFrame(() => {
          var _resizeObserver;
          (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
        });
      }
      update2();
    });
    if (referenceEl && !animationFrame) {
      resizeObserver.observe(referenceEl);
    }
    resizeObserver.observe(floating);
  }
  let frameId;
  let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
  if (animationFrame) {
    frameLoop();
  }
  function frameLoop() {
    const nextRefRect = getBoundingClientRect(reference);
    if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) {
      update2();
    }
    prevRefRect = nextRefRect;
    frameId = requestAnimationFrame(frameLoop);
  }
  update2();
  return () => {
    var _resizeObserver2;
    ancestors.forEach((ancestor) => {
      ancestorScroll && ancestor.removeEventListener("scroll", update2);
      ancestorResize && ancestor.removeEventListener("resize", update2);
    });
    cleanupIo == null || cleanupIo();
    (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
    resizeObserver = null;
    if (animationFrame) {
      cancelAnimationFrame(frameId);
    }
  };
}
var offset2 = offset;
var shift2 = shift;
var flip2 = flip;
var computePosition2 = (reference, floating, options2) => {
  const cache = /* @__PURE__ */ new Map();
  const mergedOptions = {
    platform,
    ...options2
  };
  const platformWithCache = {
    ...mergedOptions.platform,
    _c: cache
  };
  return computePosition(reference, floating, {
    ...mergedOptions,
    platform: platformWithCache
  });
};

// node_modules/svelte-floating-ui/index.js
function createFloatingActions(initOptions) {
  let referenceElement;
  let floatingElement;
  const defaultOptions = {
    autoUpdate: true
  };
  let options2 = initOptions;
  const getOptions = (mixin) => {
    return { ...defaultOptions, ...initOptions || {}, ...mixin || {} };
  };
  const updatePosition = (updateOptions) => {
    if (referenceElement && floatingElement) {
      options2 = getOptions(updateOptions);
      computePosition2(referenceElement, floatingElement, options2).then((v) => {
        Object.assign(floatingElement.style, {
          position: v.strategy,
          left: `${v.x}px`,
          top: `${v.y}px`
        });
        (options2 == null ? void 0 : options2.onComputed) && options2.onComputed(v);
      });
    }
  };
  const referenceAction = (node) => {
    if ("subscribe" in node) {
      setupVirtualElementObserver(node);
      return {};
    } else {
      referenceElement = node;
      updatePosition();
    }
  };
  const contentAction = (node, contentOptions) => {
    let autoUpdateDestroy;
    floatingElement = node;
    options2 = getOptions(contentOptions);
    setTimeout(() => updatePosition(contentOptions), 0);
    updatePosition(contentOptions);
    const destroyAutoUpdate = () => {
      if (autoUpdateDestroy) {
        autoUpdateDestroy();
        autoUpdateDestroy = void 0;
      }
    };
    const initAutoUpdate = ({ autoUpdate: autoUpdate2 } = options2 || {}) => {
      destroyAutoUpdate();
      if (autoUpdate2 !== false) {
        tick().then(() => {
          return autoUpdate(referenceElement, floatingElement, () => updatePosition(options2), autoUpdate2 === true ? {} : autoUpdate2);
        });
      }
      return;
    };
    autoUpdateDestroy = initAutoUpdate();
    return {
      update(contentOptions2) {
        updatePosition(contentOptions2);
        autoUpdateDestroy = initAutoUpdate(contentOptions2);
      },
      destroy() {
        destroyAutoUpdate();
      }
    };
  };
  const setupVirtualElementObserver = (node) => {
    const unsubscribe = node.subscribe(($node) => {
      if (referenceElement === void 0) {
        referenceElement = $node;
        updatePosition();
      } else {
        Object.assign(referenceElement, $node);
        updatePosition();
      }
    });
    onDestroy(unsubscribe);
  };
  return [
    referenceAction,
    contentAction,
    updatePosition
  ];
}

// node_modules/svelte-select/filter.js
function filter({
  loadOptions,
  filterText,
  items,
  multiple,
  value,
  itemId,
  groupBy,
  filterSelectedItems,
  itemFilter,
  convertStringItemsToObjects,
  filterGroupedItems,
  label
}) {
  if (items && loadOptions) return items;
  if (!items) return [];
  if (items && items.length > 0 && typeof items[0] !== "object") {
    items = convertStringItemsToObjects(items);
  }
  let filterResults = items.filter((item) => {
    let matchesFilter = itemFilter(item[label], filterText, item);
    if (matchesFilter && multiple && (value == null ? void 0 : value.length)) {
      matchesFilter = !value.some((x) => {
        return filterSelectedItems ? x[itemId] === item[itemId] : false;
      });
    }
    return matchesFilter;
  });
  if (groupBy) {
    filterResults = filterGroupedItems(filterResults);
  }
  return filterResults;
}

// node_modules/svelte-select/get-items.js
async function getItems({ dispatch, loadOptions, convertStringItemsToObjects, filterText }) {
  let res = await loadOptions(filterText).catch((err) => {
    console.warn("svelte-select loadOptions error :>> ", err);
    dispatch("error", { type: "loadOptions", details: err });
  });
  if (res && !res.cancelled) {
    if (res) {
      if (res && res.length > 0 && typeof res[0] !== "object") {
        res = convertStringItemsToObjects(res);
      }
      dispatch("loaded", { items: res });
    } else {
      res = [];
    }
    return {
      filteredItems: res,
      loading: false,
      focused: true,
      listOpen: true
    };
  }
}

// node_modules/svelte-select/ChevronIcon.svelte
var root14 = from_svg(`<svg width="100%" height="100%" viewBox="0 0 20 20" focusable="false" aria-hidden="true" class="svelte-1kxu7be"><path fill="currentColor" d="M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747
          3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0
          1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502
          0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0
          0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z"></path></svg>`);
var $$css14 = {
  hash: "svelte-1kxu7be",
  code: "svg.svelte-1kxu7be {width:var(--chevron-icon-width, 20px);height:var(--chevron-icon-width, 20px);color:var(--chevron-icon-colour, currentColor);}"
};
function ChevronIcon($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: ChevronIcon, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css14);
  var $$exports = {
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  var svg = root14();
  append($$anchor, svg);
  return pop($$exports);
}

// node_modules/svelte-select/ClearIcon.svelte
var root15 = from_svg(`<svg width="100%" height="100%" viewBox="-2 -2 50 50" focusable="false" aria-hidden="true" role="presentation" class="svelte-1hraxrc"><path fill="currentColor" d="M34.923,37.251L24,26.328L13.077,37.251L9.436,33.61l10.923-10.923L9.436,11.765l3.641-3.641L24,19.047L34.923,8.124
    l3.641,3.641L27.641,22.688L38.564,33.61L34.923,37.251z"></path></svg>`);
var $$css15 = {
  hash: "svelte-1hraxrc",
  code: "svg.svelte-1hraxrc {width:var(--clear-icon-width, 20px);height:var(--clear-icon-width, 20px);color:var(--clear-icon-color, currentColor);}"
};
function ClearIcon($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: ClearIcon, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css15);
  var $$exports = {
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  var svg = root15();
  append($$anchor, svg);
  return pop($$exports);
}

// node_modules/svelte-select/LoadingIcon.svelte
var root16 = from_svg(`<svg class="loading svelte-y9fi5p" viewBox="25 25 50 50"><circle class="circle_path svelte-y9fi5p" cx="50" cy="50" r="20" fill="none" stroke="currentColor" stroke-width="5" stroke-miterlimit="10"></circle></svg>`);
var $$css16 = {
  hash: "svelte-y9fi5p",
  code: ".loading.svelte-y9fi5p {width:var(--spinner-width, 20px);height:var(--spinner-height, 20px);color:var(--spinner-color, var(--icons-color));\n        animation: svelte-y9fi5p-rotate 0.75s linear infinite;transform-origin:center center;transform:none;}.circle_path.svelte-y9fi5p {stroke-dasharray:90;stroke-linecap:round;}\n\n    @keyframes svelte-y9fi5p-rotate {\n        100% {\n            transform: rotate(360deg);\n        }\n    }"
};
function LoadingIcon($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: LoadingIcon, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css16);
  var $$exports = {
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  var svg = root16();
  append($$anchor, svg);
  return pop($$exports);
}

// node_modules/svelte-select/Select.svelte
var root17 = from_html(`<div class="list-item svelte-1ul7oo4" tabindex="-1" role="none"><div><!></div></div>`);
var root_113 = from_html(`<div class="empty svelte-1ul7oo4">No options</div>`);
var root_29 = from_html(`<div role="none"><!> <!> <!></div>`);
var root_37 = from_html(`<span id="aria-selection" class="svelte-1ul7oo4"> </span> <span id="aria-context" class="svelte-1ul7oo4"> </span>`, 1);
var root_47 = from_html(`<div class="multi-item-clear svelte-1ul7oo4"><!></div>`);
var root_55 = from_html(`<div role="none"><span class="multi-item-text svelte-1ul7oo4"><!></span> <!></div>`);
var root_64 = from_html(`<div><!></div>`);
var root_73 = from_html(`<div class="icon loading svelte-1ul7oo4" aria-hidden="true"><!></div>`);
var root_82 = from_html(`<button type="button" class="icon clear-select svelte-1ul7oo4"><!></button>`);
var root_92 = from_html(`<div class="icon chevron svelte-1ul7oo4" aria-hidden="true"><!></div>`);
var root_102 = from_html(`<input type="hidden" class="svelte-1ul7oo4"/>`);
var root_114 = from_html(`<select class="required svelte-1ul7oo4" required="" tabindex="-1" aria-hidden="true"></select>`);
var root_123 = from_html(`<div role="none"><!> <span aria-live="polite" aria-atomic="false" aria-relevant="additions text" class="a11y-text svelte-1ul7oo4"><!></span> <div class="prepend svelte-1ul7oo4"><!></div> <div class="value-container svelte-1ul7oo4"><!> <input/></div> <div class="indicators svelte-1ul7oo4"><!> <!> <!></div> <!> <!></div>`);
var $$css17 = {
  hash: "svelte-1ul7oo4",
  code: ".svelte-select.svelte-1ul7oo4 {\n        /* deprecating camelCase custom props in favour of kebab-case for v5 */--borderRadius: var(--border-radius);--clearSelectColor: var(--clear-select-color);--clearSelectWidth: var(--clear-select-width);--disabledBackground: var(--disabled-background);--disabledBorderColor: var(--disabled-border-color);--disabledColor: var(--disabled-color);--disabledPlaceholderColor: var(--disabled-placeholder-color);--disabledPlaceholderOpacity: var(--disabled-placeholder-opacity);--errorBackground: var(--error-background);--errorBorder: var(--error-border);--groupItemPaddingLeft: var(--group-item-padding-left);--groupTitleColor: var(--group-title-color);--groupTitleFontSize: var(--group-title-font-size);--groupTitleFontWeight: var(--group-title-font-weight);--groupTitlePadding: var(--group-title-padding);--groupTitleTextTransform: var(--group-title-text-transform);--groupTitleBorderColor: var(--group-title-border-color);--groupTitleBorderWidth: var(--group-title-border-width);--groupTitleBorderStyle: var(--group-title-border-style);--indicatorColor: var(--chevron-color);--indicatorHeight: var(--chevron-height);--indicatorWidth: var(--chevron-width);--inputColor: var(--input-color);--inputLeft: var(--input-left);--inputLetterSpacing: var(--input-letter-spacing);--inputMargin: var(--input-margin);--inputPadding: var(--input-padding);--itemActiveBackground: var(--item-active-background);--itemColor: var(--item-color);--itemFirstBorderRadius: var(--item-first-border-radius);--itemHoverBG: var(--item-hover-bg);--itemHoverColor: var(--item-hover-color);--itemIsActiveBG: var(--item-is-active-bg);--itemIsActiveColor: var(--item-is-active-color);--itemIsNotSelectableColor: var(--item-is-not-selectable-color);--itemPadding: var(--item-padding);--listBackground: var(--list-background);--listBorder: var(--list-border);--listBorderRadius: var(--list-border-radius);--listEmptyColor: var(--list-empty-color);--listEmptyPadding: var(--list-empty-padding);--listEmptyTextAlign: var(--list-empty-text-align);--listMaxHeight: var(--list-max-height);--listPosition: var(--list-position);--listShadow: var(--list-shadow);--listZIndex: var(--list-z-index);--multiItemBG: var(--multi-item-bg);--multiItemBorderRadius: var(--multi-item-border-radius);--multiItemDisabledHoverBg: var(--multi-item-disabled-hover-bg);--multiItemDisabledHoverColor: var(--multi-item-disabled-hover-color);--multiItemHeight: var(--multi-item-height);--multiItemMargin: var(--multi-item-margin);--multiItemPadding: var(--multi-item-padding);--multiSelectInputMargin: var(--multi-select-input-margin);--multiSelectInputPadding: var(--multi-select-input-padding);--multiSelectPadding: var(--multi-select-padding);--placeholderColor: var(--placeholder-color);--placeholderOpacity: var(--placeholder-opacity);--selectedItemPadding: var(--selected-item-padding);--spinnerColor: var(--spinner-color);--spinnerHeight: var(--spinner-height);--spinnerWidth: var(--spinner-width);--internal-padding: 0 0 0 16px;border:var(--border, 1px solid #d8dbdf);border-radius:var(--border-radius, 6px);min-height:var(--height, 42px);position:relative;display:flex;align-items:stretch;padding:var(--padding, var(--internal-padding));background:var(--background, #fff);margin:var(--margin, 0);width:var(--width, 100%);font-size:var(--font-size, 16px);max-height:var(--max-height);}.svelte-1ul7oo4 {box-sizing:var(--box-sizing, border-box);}.svelte-select.svelte-1ul7oo4:hover {border:var(--border-hover, 1px solid #b2b8bf);}.value-container.svelte-1ul7oo4 {display:flex;flex:1 1 0%;flex-wrap:wrap;align-items:center;gap:5px 10px;padding:var(--value-container-padding, 5px 0);position:relative;overflow:var(--value-container-overflow, hidden);align-self:stretch;}.prepend.svelte-1ul7oo4,\n    .indicators.svelte-1ul7oo4 {display:flex;flex-shrink:0;align-items:center;}.indicators.svelte-1ul7oo4 {position:var(--indicators-position);top:var(--indicators-top);right:var(--indicators-right);bottom:var(--indicators-bottom);}input.svelte-1ul7oo4 {position:absolute;cursor:default;border:none;color:var(--input-color, var(--item-color));padding:var(--input-padding, 0);letter-spacing:var(--input-letter-spacing, inherit);margin:var(--input-margin, 0);min-width:10px;top:0;right:0;bottom:0;left:0;background:transparent;font-size:var(--font-size, 16px);}.svelte-1ul7oo4:not(.multi) > .value-container:where(.svelte-1ul7oo4) > input:where(.svelte-1ul7oo4) {width:100%;height:100%;}input.svelte-1ul7oo4::placeholder {color:var(--placeholder-color, #78848f);opacity:var(--placeholder-opacity, 1);}input.svelte-1ul7oo4:focus {outline:none;}.svelte-select.focused.svelte-1ul7oo4 {border:var(--border-focused, 1px solid #006fe8);border-radius:var(--border-radius-focused, var(--border-radius, 6px));}.disabled.svelte-1ul7oo4 {background:var(--disabled-background, #ebedef);border-color:var(--disabled-border-color, #ebedef);color:var(--disabled-color, #c1c6cc);}.disabled.svelte-1ul7oo4 input:where(.svelte-1ul7oo4)::placeholder {color:var(--disabled-placeholder-color, #c1c6cc);opacity:var(--disabled-placeholder-opacity, 1);}.selected-item.svelte-1ul7oo4 {position:relative;overflow:var(--selected-item-overflow, hidden);padding:var(--selected-item-padding, 0 20px 0 0);text-overflow:ellipsis;white-space:nowrap;color:var(--selected-item-color, inherit);font-size:var(--font-size, 16px);}.multi.svelte-1ul7oo4 .selected-item:where(.svelte-1ul7oo4) {position:absolute;line-height:var(--height, 42px);height:var(--height, 42px);}.selected-item.svelte-1ul7oo4:focus {outline:none;}.hide-selected-item.svelte-1ul7oo4 {opacity:0;}.icon.svelte-1ul7oo4 {display:flex;align-items:center;justify-content:center;}.clear-select.svelte-1ul7oo4 {all:unset;display:flex;align-items:center;justify-content:center;width:var(--clear-select-width, 40px);height:var(--clear-select-height, 100%);color:var(--clear-select-color, var(--icons-color));margin:var(--clear-select-margin, 0);pointer-events:all;flex-shrink:0;}.clear-select.svelte-1ul7oo4:focus {outline:var(--clear-select-focus-outline, 1px solid #006fe8);}.loading.svelte-1ul7oo4 {width:var(--loading-width, 40px);height:var(--loading-height);color:var(--loading-color, var(--icons-color));margin:var(--loading--margin, 0);flex-shrink:0;}.chevron.svelte-1ul7oo4 {width:var(--chevron-width, 40px);height:var(--chevron-height, 40px);background:var(--chevron-background, transparent);pointer-events:var(--chevron-pointer-events, none);color:var(--chevron-color, var(--icons-color));border:var(--chevron-border, 0 0 0 1px solid #d8dbdf);flex-shrink:0;}.multi.svelte-1ul7oo4 {padding:var(--multi-select-padding, var(--internal-padding));}.multi.svelte-1ul7oo4 input:where(.svelte-1ul7oo4) {padding:var(--multi-select-input-padding, 0);position:relative;margin:var(--multi-select-input-margin, 5px 0);flex:1 1 40px;}.svelte-select.error.svelte-1ul7oo4 {border:var(--error-border, 1px solid #ff2d55);background:var(--error-background, #fff);}.a11y-text.svelte-1ul7oo4 {z-index:9999;border:0px;clip:rect(1px, 1px, 1px, 1px);height:1px;width:1px;position:absolute;overflow:hidden;padding:0px;white-space:nowrap;}.multi-item.svelte-1ul7oo4 {background:var(--multi-item-bg, #ebedef);margin:var(--multi-item-margin, 0);outline:var(--multi-item-outline, 1px solid #ddd);border-radius:var(--multi-item-border-radius, 4px);height:var(--multi-item-height, 25px);line-height:var(--multi-item-height, 25px);display:flex;cursor:default;padding:var(--multi-item-padding, 0 5px);overflow:hidden;gap:var(--multi-item-gap, 4px);outline-offset:-1px;max-width:var(--multi-max-width, none);color:var(--multi-item-color, var(--item-color));}.multi-item.disabled.svelte-1ul7oo4:hover {background:var(--multi-item-disabled-hover-bg, #ebedef);color:var(--multi-item-disabled-hover-color, #c1c6cc);}.multi-item-text.svelte-1ul7oo4 {overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.multi-item-clear.svelte-1ul7oo4 {display:flex;align-items:center;justify-content:center;--clear-icon-color: var(--multi-item-clear-icon-color, #000);}.multi-item.active.svelte-1ul7oo4 {outline:var(--multi-item-active-outline, 1px solid #006fe8);}.svelte-select-list.svelte-1ul7oo4 {box-shadow:var(--list-shadow, 0 2px 3px 0 rgba(44, 62, 80, 0.24));border-radius:var(--list-border-radius, 4px);max-height:var(--list-max-height, 252px);overflow-y:auto;background:var(--list-background, #fff);position:var(--list-position, absolute);z-index:var(--list-z-index, 2);border:var(--list-border);}.prefloat.svelte-1ul7oo4 {opacity:0;pointer-events:none;}.list-group-title.svelte-1ul7oo4 {color:var(--group-title-color, #8f8f8f);cursor:default;font-size:var(--group-title-font-size, 16px);font-weight:var(--group-title-font-weight, 600);height:var(--height, 42px);line-height:var(--height, 42px);padding:var(--group-title-padding, 0 20px);text-overflow:ellipsis;overflow-x:hidden;white-space:nowrap;text-transform:var(--group-title-text-transform, uppercase);border-width:var(--group-title-border-width, medium);border-style:var(--group-title-border-style, none);border-color:var(--group-title-border-color, color);}.empty.svelte-1ul7oo4 {text-align:var(--list-empty-text-align, center);padding:var(--list-empty-padding, 20px 0);color:var(--list-empty-color, #78848f);}.item.svelte-1ul7oo4 {cursor:default;height:var(--item-height, var(--height, 42px));line-height:var(--item-line-height, var(--height, 42px));padding:var(--item-padding, 0 20px);color:var(--item-color, inherit);text-overflow:ellipsis;overflow:hidden;white-space:nowrap;transition:var(--item-transition, all 0.2s);align-items:center;width:100%;}.item.group-item.svelte-1ul7oo4 {padding-left:var(--group-item-padding-left, 40px);}.item.svelte-1ul7oo4:active {background:var(--item-active-background, #b9daff);}.item.active.svelte-1ul7oo4 {background:var(--item-is-active-bg, #007aff);color:var(--item-is-active-color, #fff);}.item.first.svelte-1ul7oo4 {border-radius:var(--item-first-border-radius, 4px 4px 0 0);}.item.hover.svelte-1ul7oo4:not(.active) {background:var(--item-hover-bg, #e7f2ff);color:var(--item-hover-color, inherit);}.item.not-selectable.svelte-1ul7oo4,\n    .item.hover.item.not-selectable.svelte-1ul7oo4,\n    .item.active.item.not-selectable.svelte-1ul7oo4,\n    .item.not-selectable.svelte-1ul7oo4:active {color:var(--item-is-not-selectable-color, #999);background:transparent;}.required.svelte-1ul7oo4 {opacity:0;z-index:-1;position:absolute;top:0;left:0;bottom:0;right:0;}"
};
function Select($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Select, ...$$anchor });
  const $$slots = sanitize_slots($$props);
  push($$props, false);
  append_styles($$anchor, $$css17);
  const hasValue = mutable_source();
  const hideSelectedItem = mutable_source();
  const showClear = mutable_source();
  const placeholderText = mutable_source();
  const ariaSelection = mutable_source();
  const ariaContext = mutable_source();
  const filteredItems = mutable_source();
  const listDom = mutable_source();
  const scrollToHoverItem = mutable_source();
  const dispatch = createEventDispatcher();
  let justValue = prop(
    $$props,
    "justValue",
    12,
    null
    // read-only
  );
  let filter2 = prop($$props, "filter", 12, filter);
  let getItems2 = prop($$props, "getItems", 12, getItems);
  let id = prop($$props, "id", 12, null);
  let name = prop($$props, "name", 12, null);
  let container = prop($$props, "container", 12, void 0);
  let input = prop($$props, "input", 12, void 0);
  let multiple = prop($$props, "multiple", 12, false);
  let multiFullItemClearable = prop($$props, "multiFullItemClearable", 12, false);
  let disabled = prop($$props, "disabled", 12, false);
  let focused = prop($$props, "focused", 12, false);
  let value = prop($$props, "value", 12, null);
  let filterText = prop($$props, "filterText", 12, "");
  let placeholder = prop($$props, "placeholder", 12, "Please select");
  let placeholderAlwaysShow = prop($$props, "placeholderAlwaysShow", 12, false);
  let items = prop($$props, "items", 12, null);
  let label = prop($$props, "label", 12, "label");
  let itemFilter = prop($$props, "itemFilter", 12, (label2, filterText2, option) => `${label2}`.toLowerCase().includes(filterText2.toLowerCase()));
  let groupBy = prop($$props, "groupBy", 12, void 0);
  let groupFilter = prop($$props, "groupFilter", 12, (groups) => groups);
  let groupHeaderSelectable = prop($$props, "groupHeaderSelectable", 12, false);
  let itemId = prop($$props, "itemId", 12, "value");
  let loadOptions = prop($$props, "loadOptions", 12, void 0);
  let containerStyles = prop($$props, "containerStyles", 12, "");
  let hasError = prop($$props, "hasError", 12, false);
  let filterSelectedItems = prop($$props, "filterSelectedItems", 12, true);
  let required = prop($$props, "required", 12, false);
  let closeListOnChange = prop($$props, "closeListOnChange", 12, true);
  let clearFilterTextOnBlur = prop($$props, "clearFilterTextOnBlur", 12, true);
  let createGroupHeaderItem = prop($$props, "createGroupHeaderItem", 12, (groupValue, item) => {
    return { value: groupValue, [label()]: groupValue };
  });
  const getFilteredItems = () => {
    return get(filteredItems);
  };
  let searchable = prop($$props, "searchable", 12, true);
  let inputStyles = prop($$props, "inputStyles", 12, "");
  let clearable = prop($$props, "clearable", 12, true);
  let loading = prop($$props, "loading", 12, false);
  let listOpen = prop($$props, "listOpen", 12, false);
  let timeout;
  let debounce = prop($$props, "debounce", 12, (fn, wait2 = 1) => {
    clearTimeout(timeout);
    timeout = setTimeout(fn, wait2);
  });
  let debounceWait = prop($$props, "debounceWait", 12, 300);
  let hideEmptyState = prop($$props, "hideEmptyState", 12, false);
  let inputAttributes = prop($$props, "inputAttributes", 28, () => ({}));
  let listAutoWidth = prop($$props, "listAutoWidth", 12, true);
  let showChevron = prop($$props, "showChevron", 12, false);
  let listOffset = prop($$props, "listOffset", 12, 5);
  let hoverItemIndex = prop($$props, "hoverItemIndex", 12, 0);
  let floatingConfig = prop($$props, "floatingConfig", 28, () => ({}));
  let containerClasses = prop($$props, "class", 12, "");
  let activeValue = mutable_source();
  let prev_value = mutable_source();
  let prev_filterText = mutable_source();
  let prev_multiple = mutable_source();
  function setValue() {
    if (typeof value() === "string") {
      let item = (items() || []).find((item2) => item2[itemId()] === value());
      value(item || { [itemId()]: value(), label: value() });
    } else if (multiple() && Array.isArray(value()) && value().length > 0) {
      value(value().map((item) => typeof item === "string" ? { value: item, label: item } : item));
    }
  }
  let _inputAttributes = mutable_source();
  function assignInputAttributes() {
    set(_inputAttributes, Object.assign(
      {
        autocapitalize: "none",
        autocomplete: "off",
        autocorrect: "off",
        spellcheck: false,
        tabindex: 0,
        type: "text",
        "aria-autocomplete": "list"
      },
      inputAttributes()
    ));
    if (id()) {
      mutate(_inputAttributes, get(_inputAttributes)["id"] = id());
    }
    if (!searchable()) {
      mutate(_inputAttributes, get(_inputAttributes)["readonly"] = true);
    }
  }
  function convertStringItemsToObjects(_items) {
    return _items.map((item, index2) => {
      return { index: index2, value: item, label: `${item}` };
    });
  }
  function filterGroupedItems(_items) {
    const groupValues = [];
    const groups = {};
    _items.forEach((item) => {
      const groupValue = groupBy()(item);
      if (!groupValues.includes(groupValue)) {
        groupValues.push(groupValue);
        groups[groupValue] = [];
        if (groupValue) {
          groups[groupValue].push(Object.assign(createGroupHeaderItem()(groupValue, item), {
            id: groupValue,
            groupHeader: true,
            selectable: groupHeaderSelectable()
          }));
        }
      }
      groups[groupValue].push(Object.assign({ groupItem: !!groupValue }, item));
    });
    const sortedGroupedItems = [];
    groupFilter()(groupValues).forEach((groupValue) => {
      if (groups[groupValue]) sortedGroupedItems.push(...groups[groupValue]);
    });
    return sortedGroupedItems;
  }
  function dispatchSelectedItem() {
    if (multiple()) {
      if (JSON.stringify(value()) !== JSON.stringify(get(prev_value))) {
        if (checkValueForDuplicates()) {
          dispatch("input", value());
        }
      }
      return;
    }
    if (!get(prev_value) || JSON.stringify(value()[itemId()]) !== JSON.stringify(get(prev_value)[itemId()])) {
      dispatch("input", value());
    }
  }
  function setupMulti() {
    if (value()) {
      if (Array.isArray(value())) {
        value([...value()]);
      } else {
        value([value()]);
      }
    }
  }
  function setupSingle() {
    if (value()) value(null);
  }
  function setValueIndexAsHoverIndex() {
    const valueIndex = get(filteredItems).findIndex((i) => {
      return i[itemId()] === value()[itemId()];
    });
    checkHoverSelectable(valueIndex, true);
  }
  function dispatchHover(i) {
    dispatch("hoverItem", i);
  }
  function checkHoverSelectable(startingIndex = 0, ignoreGroup) {
    hoverItemIndex(startingIndex < 0 ? 0 : startingIndex);
    if (!ignoreGroup && groupBy() && get(filteredItems)[hoverItemIndex()] && !get(filteredItems)[hoverItemIndex()].selectable) {
      setHoverIndex(1);
    }
  }
  function setupFilterText() {
    if (!loadOptions() && filterText().length === 0) return;
    if (loadOptions()) {
      debounce()(
        async function() {
          loading(true);
          let res = await getItems2()({
            dispatch,
            loadOptions: loadOptions(),
            convertStringItemsToObjects,
            filterText: filterText()
          });
          if (res) {
            loading(res.loading);
            listOpen(listOpen() ? res.listOpen : filterText().length > 0 ? true : false);
            focused(listOpen() && res.focused);
            items(groupBy() ? filterGroupedItems(res.filteredItems) : res.filteredItems);
          } else {
            loading(false);
            focused(true);
            listOpen(true);
          }
        },
        debounceWait()
      );
    } else {
      listOpen(true);
      if (multiple()) {
        set(activeValue, void 0);
      }
    }
  }
  function handleFilterEvent(items2) {
    if (listOpen()) dispatch("filter", items2);
  }
  beforeUpdate(async () => {
    set(prev_value, value());
    set(prev_filterText, filterText());
    set(prev_multiple, multiple());
  });
  function computeJustValue() {
    if (multiple()) return value() ? value().map((item) => item[itemId()]) : null;
    return value() ? value()[itemId()] : value();
  }
  function checkValueForDuplicates() {
    let noDuplicates = true;
    if (value()) {
      const ids = [];
      const uniqueValues = [];
      value().forEach((val) => {
        if (!ids.includes(val[itemId()])) {
          ids.push(val[itemId()]);
          uniqueValues.push(val);
        } else {
          noDuplicates = false;
        }
      });
      if (!noDuplicates) value(uniqueValues);
    }
    return noDuplicates;
  }
  function findItem(selection) {
    let matchTo = selection ? selection[itemId()] : value()[itemId()];
    return items().find((item) => item[itemId()] === matchTo);
  }
  function updateValueDisplay(items2) {
    if (!items2 || items2.length === 0 || items2.some((item) => typeof item !== "object")) return;
    if (!value() || (multiple() ? value().some((selection) => !selection || !selection[itemId()]) : !value()[itemId()])) return;
    if (Array.isArray(value())) {
      value(value().map((selection) => findItem(selection) || selection));
    } else {
      value(findItem() || value());
    }
  }
  async function handleMultiItemClear(i) {
    const itemToRemove = value()[i];
    if (value().length === 1) {
      value(void 0);
    } else {
      value(value().filter((item) => {
        return item !== itemToRemove;
      }));
    }
    dispatch("clear", itemToRemove);
  }
  function handleKeyDown(e) {
    if (!focused()) return;
    e.stopPropagation();
    switch (e.key) {
      case "Escape":
        e.preventDefault();
        closeList();
        break;
      case "Enter":
        e.preventDefault();
        if (listOpen()) {
          if (get(filteredItems).length === 0) break;
          const hoverItem = get(filteredItems)[hoverItemIndex()];
          if (value() && !multiple() && value()[itemId()] === hoverItem[itemId()]) {
            closeList();
            break;
          } else {
            handleSelect(get(filteredItems)[hoverItemIndex()]);
          }
        }
        break;
      case "ArrowDown":
        e.preventDefault();
        if (listOpen()) {
          setHoverIndex(1);
        } else {
          listOpen(true);
          set(activeValue, void 0);
        }
        break;
      case "ArrowUp":
        e.preventDefault();
        if (listOpen()) {
          setHoverIndex(-1);
        } else {
          listOpen(true);
          set(activeValue, void 0);
        }
        break;
      case "Tab":
        if (listOpen() && focused()) {
          if (get(filteredItems).length === 0 || value() && value()[itemId()] === get(filteredItems)[hoverItemIndex()][itemId()]) return closeList();
          e.preventDefault();
          handleSelect(get(filteredItems)[hoverItemIndex()]);
          closeList();
        }
        break;
      case "Backspace":
        if (!multiple() || filterText().length > 0) return;
        if (multiple() && value() && value().length > 0) {
          handleMultiItemClear(get(activeValue) !== void 0 ? get(activeValue) : value().length - 1);
          if (get(activeValue) === 0 || get(activeValue) === void 0) break;
          set(activeValue, value().length > get(activeValue) ? get(activeValue) - 1 : void 0);
        }
        break;
      case "ArrowLeft":
        if (!value() || !multiple() || filterText().length > 0) return;
        if (get(activeValue) === void 0) {
          set(activeValue, value().length - 1);
        } else if (value().length > get(activeValue) && get(activeValue) !== 0) {
          set(activeValue, get(activeValue) - 1);
        }
        break;
      case "ArrowRight":
        if (!value() || !multiple() || filterText().length > 0 || get(activeValue) === void 0) return;
        if (get(activeValue) === value().length - 1) {
          set(activeValue, void 0);
        } else if (get(activeValue) < value().length - 1) {
          set(activeValue, get(activeValue) + 1);
        }
        break;
    }
  }
  function handleFocus(e) {
    var _a5;
    if (focused() && input() === (document == null ? void 0 : document.activeElement)) return;
    if (e) dispatch("focus", e);
    (_a5 = input()) == null ? void 0 : _a5.focus();
    focused(true);
  }
  async function handleBlur(e) {
    var _a5;
    if (isScrolling) return;
    if (listOpen() || focused()) {
      dispatch("blur", e);
      closeList();
      focused(false);
      set(activeValue, void 0);
      (_a5 = input()) == null ? void 0 : _a5.blur();
    }
  }
  function handleClick() {
    if (disabled()) return;
    if (filterText().length > 0) return listOpen(true);
    listOpen(!listOpen());
  }
  function handleClear() {
    dispatch("clear", value());
    value(void 0);
    closeList();
    handleFocus();
  }
  onMount(() => {
    if (listOpen()) focused(true);
    if (focused() && input()) input().focus();
  });
  function itemSelected(selection) {
    if (selection) {
      filterText("");
      const item = Object.assign({}, selection);
      if (item.groupHeader && !item.selectable) return;
      value(multiple() ? value() ? value().concat([item]) : [item] : value(item));
      setTimeout(() => {
        if (closeListOnChange()) closeList();
        set(activeValue, void 0);
        dispatch("change", value());
        dispatch("select", selection);
      });
    }
  }
  function closeList() {
    if (clearFilterTextOnBlur()) {
      filterText("");
    }
    listOpen(false);
  }
  let ariaValues = prop($$props, "ariaValues", 12, (values) => {
    return `Option ${values}, selected.`;
  });
  let ariaListOpen = prop($$props, "ariaListOpen", 12, (label2, count) => {
    return `You are currently focused on option ${label2}. There are ${count} results available.`;
  });
  let ariaFocused = prop($$props, "ariaFocused", 12, () => {
    return `Select is focused, type to refine list, press down to open the menu.`;
  });
  function handleAriaSelection(_multiple) {
    let selected = void 0;
    if (_multiple && value().length > 0) {
      selected = value().map((v) => v[label()]).join(", ");
    } else {
      selected = value()[label()];
    }
    return ariaValues()(selected);
  }
  function handleAriaContent() {
    if (!get(filteredItems) || get(filteredItems).length === 0) return "";
    let _item = get(filteredItems)[hoverItemIndex()];
    if (listOpen() && _item) {
      let count = get(filteredItems) ? get(filteredItems).length : 0;
      return ariaListOpen()(_item[label()], count);
    } else {
      return ariaFocused()();
    }
  }
  let list = mutable_source(null);
  let isScrollingTimer;
  function handleListScroll() {
    clearTimeout(isScrollingTimer);
    isScrollingTimer = setTimeout(
      () => {
        isScrolling = false;
      },
      100
    );
  }
  function handleClickOutside(event2) {
    var _a5;
    if (!listOpen() && !focused() && container() && !container().contains(event2.target) && !((_a5 = get(list)) == null ? void 0 : _a5.contains(event2.target))) {
      handleBlur();
    }
  }
  onDestroy(() => {
    var _a5;
    (_a5 = get(list)) == null ? void 0 : _a5.remove();
  });
  let isScrolling = false;
  function handleSelect(item) {
    if (!item || item.selectable === false) return;
    itemSelected(item);
  }
  function handleHover(i) {
    if (isScrolling) return;
    hoverItemIndex(i);
  }
  function handleItemClick(args) {
    const { item, i } = args;
    if ((item == null ? void 0 : item.selectable) === false) return;
    if (value() && !multiple() && value()[itemId()] === item[itemId()]) return closeList();
    if (isItemSelectable(item)) {
      hoverItemIndex(i);
      handleSelect(item);
    }
  }
  function setHoverIndex(increment2) {
    let selectableFilteredItems = get(filteredItems).filter((item) => !Object.hasOwn(item, "selectable") || item.selectable === true);
    if (selectableFilteredItems.length === 0) {
      return hoverItemIndex(0);
    }
    if (increment2 > 0 && hoverItemIndex() === get(filteredItems).length - 1) {
      hoverItemIndex(0);
    } else if (increment2 < 0 && hoverItemIndex() === 0) {
      hoverItemIndex(get(filteredItems).length - 1);
    } else {
      hoverItemIndex(hoverItemIndex() + increment2);
    }
    const hover = get(filteredItems)[hoverItemIndex()];
    if (hover && hover.selectable === false) {
      if (increment2 === 1 || increment2 === -1) setHoverIndex(increment2);
      return;
    }
  }
  function isItemActive(item, value2, itemId2) {
    if (multiple()) return;
    return value2 && value2[itemId2] === item[itemId2];
  }
  function isItemFirst(itemIndex) {
    return itemIndex === 0;
  }
  function isItemSelectable(item) {
    return item.groupHeader && item.selectable || item.selectable || !item.hasOwnProperty("selectable");
  }
  const activeScroll = scrollAction;
  const hoverScroll = scrollAction;
  function scrollAction(node) {
    return {
      update(args) {
        if (args.scroll) {
          handleListScroll();
          node.scrollIntoView({ behavior: "auto", block: "nearest" });
        }
      }
    };
  }
  function setListWidth() {
    const { width } = container().getBoundingClientRect();
    mutate(list, get(list).style.width = listAutoWidth() ? width + "px" : "auto");
  }
  let _floatingConfig = mutable_source({
    strategy: "absolute",
    placement: "bottom-start",
    middleware: [offset2(listOffset()), flip2(), shift2()],
    autoUpdate: false
  });
  const [floatingRef, floatingContent, floatingUpdate] = createFloatingActions(get(_floatingConfig));
  let prefloat = mutable_source(true);
  function listMounted(list2, listOpen2) {
    if (!list2 || !listOpen2) return set(prefloat, true);
    setTimeout(
      () => {
        set(prefloat, false);
      },
      0
    );
  }
  legacy_pre_effect(() => (deep_read_state(items()), deep_read_state(value())), () => {
    if (items(), value()) setValue();
  });
  legacy_pre_effect(
    () => (deep_read_state(inputAttributes()), deep_read_state(searchable())),
    () => {
      if (inputAttributes() || !searchable()) assignInputAttributes();
    }
  );
  legacy_pre_effect(() => deep_read_state(multiple()), () => {
    if (multiple()) setupMulti();
  });
  legacy_pre_effect(() => (get(prev_multiple), deep_read_state(multiple())), () => {
    if (get(prev_multiple) && !multiple()) setupSingle();
  });
  legacy_pre_effect(() => (deep_read_state(multiple()), deep_read_state(value())), () => {
    if (multiple() && value() && value().length > 1) checkValueForDuplicates();
  });
  legacy_pre_effect(() => deep_read_state(value()), () => {
    if (value()) dispatchSelectedItem();
  });
  legacy_pre_effect(
    () => (deep_read_state(value()), deep_read_state(multiple()), get(prev_value)),
    () => {
      if (!value() && multiple() && get(prev_value)) dispatch("input", value());
    }
  );
  legacy_pre_effect(() => (deep_read_state(focused()), deep_read_state(input())), () => {
    if (!focused() && input()) closeList();
  });
  legacy_pre_effect(() => (deep_read_state(filterText()), get(prev_filterText)), () => {
    if (filterText() !== get(prev_filterText)) setupFilterText();
  });
  legacy_pre_effect(
    () => (deep_read_state(filter2()), deep_read_state(loadOptions()), deep_read_state(filterText()), deep_read_state(items()), deep_read_state(multiple()), deep_read_state(value()), deep_read_state(itemId()), deep_read_state(groupBy()), deep_read_state(label()), deep_read_state(filterSelectedItems()), deep_read_state(itemFilter())),
    () => {
      set(filteredItems, filter2()({
        loadOptions: loadOptions(),
        filterText: filterText(),
        items: items(),
        multiple: multiple(),
        value: value(),
        itemId: itemId(),
        groupBy: groupBy(),
        label: label(),
        filterSelectedItems: filterSelectedItems(),
        itemFilter: itemFilter(),
        convertStringItemsToObjects,
        filterGroupedItems
      }));
    }
  );
  legacy_pre_effect(
    () => (deep_read_state(multiple()), deep_read_state(listOpen()), deep_read_state(value()), get(filteredItems)),
    () => {
      if (!multiple() && listOpen() && value() && get(filteredItems)) setValueIndexAsHoverIndex();
    }
  );
  legacy_pre_effect(() => (deep_read_state(listOpen()), deep_read_state(multiple())), () => {
    if (listOpen() && multiple()) hoverItemIndex(0);
  });
  legacy_pre_effect(() => deep_read_state(filterText()), () => {
    if (filterText()) hoverItemIndex(0);
  });
  legacy_pre_effect(() => deep_read_state(hoverItemIndex()), () => {
    dispatchHover(hoverItemIndex());
  });
  legacy_pre_effect(() => (deep_read_state(multiple()), deep_read_state(value())), () => {
    set(hasValue, multiple() ? value() && value().length > 0 : value());
  });
  legacy_pre_effect(() => (get(hasValue), deep_read_state(filterText())), () => {
    set(hideSelectedItem, get(hasValue) && filterText().length > 0);
  });
  legacy_pre_effect(
    () => (get(hasValue), deep_read_state(clearable()), deep_read_state(disabled()), deep_read_state(loading())),
    () => {
      set(showClear, get(hasValue) && clearable() && !disabled() && !loading());
    }
  );
  legacy_pre_effect(
    () => (deep_read_state(placeholderAlwaysShow()), deep_read_state(multiple()), deep_read_state(placeholder()), deep_read_state(value())),
    () => {
      var _a5;
      set(placeholderText, placeholderAlwaysShow() && multiple() ? placeholder() : multiple() && ((_a5 = value()) == null ? void 0 : _a5.length) === 0 ? placeholder() : value() ? "" : placeholder());
    }
  );
  legacy_pre_effect(() => (deep_read_state(value()), deep_read_state(multiple())), () => {
    set(ariaSelection, value() ? handleAriaSelection(multiple()) : "");
  });
  legacy_pre_effect(
    () => (get(filteredItems), deep_read_state(hoverItemIndex()), deep_read_state(focused()), deep_read_state(listOpen())),
    () => {
      set(ariaContext, handleAriaContent({
        filteredItems: get(filteredItems),
        hoverItemIndex: hoverItemIndex(),
        focused: focused(),
        listOpen: listOpen()
      }));
    }
  );
  legacy_pre_effect(() => deep_read_state(items()), () => {
    updateValueDisplay(items());
  });
  legacy_pre_effect(
    () => (deep_read_state(multiple()), deep_read_state(value()), deep_read_state(itemId())),
    () => {
      justValue(computeJustValue(multiple(), value(), itemId()));
    }
  );
  legacy_pre_effect(
    () => (deep_read_state(multiple()), get(prev_value), deep_read_state(value())),
    () => {
      if (!multiple() && get(prev_value) && !value()) dispatch("input", value());
    }
  );
  legacy_pre_effect(
    () => (deep_read_state(listOpen()), get(filteredItems), deep_read_state(multiple()), deep_read_state(value())),
    () => {
      if (listOpen() && get(filteredItems) && !multiple() && !value()) checkHoverSelectable();
    }
  );
  legacy_pre_effect(() => get(filteredItems), () => {
    handleFilterEvent(get(filteredItems));
  });
  legacy_pre_effect(
    () => (deep_read_state(container()), deep_read_state(floatingConfig()), get(_floatingConfig)),
    () => {
      if (container() && floatingConfig()) floatingUpdate(Object.assign(get(_floatingConfig), floatingConfig()));
    }
  );
  legacy_pre_effect(() => get(list), () => {
    set(listDom, !!get(list));
  });
  legacy_pre_effect(() => (get(list), deep_read_state(listOpen())), () => {
    listMounted(get(list), listOpen());
  });
  legacy_pre_effect(
    () => (deep_read_state(listOpen()), deep_read_state(container()), get(list)),
    () => {
      if (listOpen() && container() && get(list)) setListWidth();
    }
  );
  legacy_pre_effect(() => deep_read_state(hoverItemIndex()), () => {
    set(scrollToHoverItem, hoverItemIndex());
  });
  legacy_pre_effect(
    () => (deep_read_state(input()), deep_read_state(listOpen()), deep_read_state(focused())),
    () => {
      if (input() && listOpen() && !focused()) handleFocus();
    }
  );
  legacy_pre_effect(
    () => (deep_read_state(container()), deep_read_state(floatingConfig())),
    () => {
      var _a5;
      if (container() && ((_a5 = floatingConfig()) == null ? void 0 : _a5.autoUpdate) === void 0) {
        mutate(_floatingConfig, get(_floatingConfig).autoUpdate = true);
      }
    }
  );
  legacy_pre_effect_reset();
  var $$exports = {
    getFilteredItems,
    handleClear,
    get justValue() {
      return justValue();
    },
    set justValue($$value) {
      justValue($$value);
      flushSync();
    },
    get filter() {
      return filter2();
    },
    set filter($$value) {
      filter2($$value);
      flushSync();
    },
    get getItems() {
      return getItems2();
    },
    set getItems($$value) {
      getItems2($$value);
      flushSync();
    },
    get id() {
      return id();
    },
    set id($$value) {
      id($$value);
      flushSync();
    },
    get name() {
      return name();
    },
    set name($$value) {
      name($$value);
      flushSync();
    },
    get container() {
      return container();
    },
    set container($$value) {
      container($$value);
      flushSync();
    },
    get input() {
      return input();
    },
    set input($$value) {
      input($$value);
      flushSync();
    },
    get multiple() {
      return multiple();
    },
    set multiple($$value) {
      multiple($$value);
      flushSync();
    },
    get multiFullItemClearable() {
      return multiFullItemClearable();
    },
    set multiFullItemClearable($$value) {
      multiFullItemClearable($$value);
      flushSync();
    },
    get disabled() {
      return disabled();
    },
    set disabled($$value) {
      disabled($$value);
      flushSync();
    },
    get focused() {
      return focused();
    },
    set focused($$value) {
      focused($$value);
      flushSync();
    },
    get value() {
      return value();
    },
    set value($$value) {
      value($$value);
      flushSync();
    },
    get filterText() {
      return filterText();
    },
    set filterText($$value) {
      filterText($$value);
      flushSync();
    },
    get placeholder() {
      return placeholder();
    },
    set placeholder($$value) {
      placeholder($$value);
      flushSync();
    },
    get placeholderAlwaysShow() {
      return placeholderAlwaysShow();
    },
    set placeholderAlwaysShow($$value) {
      placeholderAlwaysShow($$value);
      flushSync();
    },
    get items() {
      return items();
    },
    set items($$value) {
      items($$value);
      flushSync();
    },
    get label() {
      return label();
    },
    set label($$value) {
      label($$value);
      flushSync();
    },
    get itemFilter() {
      return itemFilter();
    },
    set itemFilter($$value) {
      itemFilter($$value);
      flushSync();
    },
    get groupBy() {
      return groupBy();
    },
    set groupBy($$value) {
      groupBy($$value);
      flushSync();
    },
    get groupFilter() {
      return groupFilter();
    },
    set groupFilter($$value) {
      groupFilter($$value);
      flushSync();
    },
    get groupHeaderSelectable() {
      return groupHeaderSelectable();
    },
    set groupHeaderSelectable($$value) {
      groupHeaderSelectable($$value);
      flushSync();
    },
    get itemId() {
      return itemId();
    },
    set itemId($$value) {
      itemId($$value);
      flushSync();
    },
    get loadOptions() {
      return loadOptions();
    },
    set loadOptions($$value) {
      loadOptions($$value);
      flushSync();
    },
    get containerStyles() {
      return containerStyles();
    },
    set containerStyles($$value) {
      containerStyles($$value);
      flushSync();
    },
    get hasError() {
      return hasError();
    },
    set hasError($$value) {
      hasError($$value);
      flushSync();
    },
    get filterSelectedItems() {
      return filterSelectedItems();
    },
    set filterSelectedItems($$value) {
      filterSelectedItems($$value);
      flushSync();
    },
    get required() {
      return required();
    },
    set required($$value) {
      required($$value);
      flushSync();
    },
    get closeListOnChange() {
      return closeListOnChange();
    },
    set closeListOnChange($$value) {
      closeListOnChange($$value);
      flushSync();
    },
    get clearFilterTextOnBlur() {
      return clearFilterTextOnBlur();
    },
    set clearFilterTextOnBlur($$value) {
      clearFilterTextOnBlur($$value);
      flushSync();
    },
    get createGroupHeaderItem() {
      return createGroupHeaderItem();
    },
    set createGroupHeaderItem($$value) {
      createGroupHeaderItem($$value);
      flushSync();
    },
    get searchable() {
      return searchable();
    },
    set searchable($$value) {
      searchable($$value);
      flushSync();
    },
    get inputStyles() {
      return inputStyles();
    },
    set inputStyles($$value) {
      inputStyles($$value);
      flushSync();
    },
    get clearable() {
      return clearable();
    },
    set clearable($$value) {
      clearable($$value);
      flushSync();
    },
    get loading() {
      return loading();
    },
    set loading($$value) {
      loading($$value);
      flushSync();
    },
    get listOpen() {
      return listOpen();
    },
    set listOpen($$value) {
      listOpen($$value);
      flushSync();
    },
    get debounce() {
      return debounce();
    },
    set debounce($$value) {
      debounce($$value);
      flushSync();
    },
    get debounceWait() {
      return debounceWait();
    },
    set debounceWait($$value) {
      debounceWait($$value);
      flushSync();
    },
    get hideEmptyState() {
      return hideEmptyState();
    },
    set hideEmptyState($$value) {
      hideEmptyState($$value);
      flushSync();
    },
    get inputAttributes() {
      return inputAttributes();
    },
    set inputAttributes($$value) {
      inputAttributes($$value);
      flushSync();
    },
    get listAutoWidth() {
      return listAutoWidth();
    },
    set listAutoWidth($$value) {
      listAutoWidth($$value);
      flushSync();
    },
    get showChevron() {
      return showChevron();
    },
    set showChevron($$value) {
      showChevron($$value);
      flushSync();
    },
    get listOffset() {
      return listOffset();
    },
    set listOffset($$value) {
      listOffset($$value);
      flushSync();
    },
    get hoverItemIndex() {
      return hoverItemIndex();
    },
    set hoverItemIndex($$value) {
      hoverItemIndex($$value);
      flushSync();
    },
    get floatingConfig() {
      return floatingConfig();
    },
    set floatingConfig($$value) {
      floatingConfig($$value);
      flushSync();
    },
    get class() {
      return containerClasses();
    },
    set class($$value) {
      containerClasses($$value);
      flushSync();
    },
    get ariaValues() {
      return ariaValues();
    },
    set ariaValues($$value) {
      ariaValues($$value);
      flushSync();
    },
    get ariaListOpen() {
      return ariaListOpen();
    },
    set ariaListOpen($$value) {
      ariaListOpen($$value);
      flushSync();
    },
    get ariaFocused() {
      return ariaFocused();
    },
    set ariaFocused($$value) {
      ariaFocused($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root_123();
  event("click", $window, handleClickOutside);
  event("keydown", $window, handleKeyDown);
  let classes;
  var node_1 = child(div);
  {
    var consequent_5 = ($$anchor2) => {
      var div_1 = root_29();
      let classes_1;
      var node_2 = child(div_1);
      {
        var consequent = ($$anchor3) => {
          var fragment = comment();
          var node_3 = first_child(fragment);
          slot(node_3, $$props, "list-prepend", {}, null);
          append($$anchor3, fragment);
        };
        if_block(node_2, ($$render) => {
          if (untrack(() => $$slots["list-prepend"])) $$render(consequent);
        });
      }
      var node_4 = sibling(node_2, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var fragment_1 = comment();
          var node_5 = first_child(fragment_1);
          slot(
            node_5,
            $$props,
            "list",
            {
              get filteredItems() {
                return get(filteredItems);
              }
            },
            null
          );
          append($$anchor3, fragment_1);
        };
        var consequent_2 = ($$anchor3) => {
          var fragment_2 = comment();
          var node_6 = first_child(fragment_2);
          each(node_6, 1, () => get(filteredItems), index, ($$anchor4, item, i) => {
            var div_2 = root17();
            var div_3 = child(div_2);
            let classes_2;
            var node_7 = child(div_3);
            slot(
              node_7,
              $$props,
              "item",
              {
                get item() {
                  return get(item);
                },
                index: i
              },
              ($$anchor5) => {
                var text2 = text();
                template_effect(() => set_text(text2, (get(item), deep_read_state(label()), untrack(() => {
                  var _a5;
                  return (_a5 = get(item)) == null ? void 0 : _a5[label()];
                }))));
                append($$anchor5, text2);
              }
            );
            reset(div_3);
            action(div_3, ($$node, $$action_arg) => activeScroll == null ? void 0 : activeScroll($$node, $$action_arg), () => ({
              scroll: isItemActive(get(item), value(), itemId()),
              listDom: get(listDom)
            }));
            action(div_3, ($$node, $$action_arg) => hoverScroll == null ? void 0 : hoverScroll($$node, $$action_arg), () => ({
              scroll: get(scrollToHoverItem) === i,
              listDom: get(listDom)
            }));
            reset(div_2);
            template_effect(($0) => classes_2 = set_class(div_3, 1, "item svelte-1ul7oo4", null, classes_2, $0), [
              () => {
                var _a5;
                return {
                  "list-group-title": get(item).groupHeader,
                  active: isItemActive(get(item), value(), itemId()),
                  first: isItemFirst(i),
                  hover: hoverItemIndex() === i,
                  "group-item": get(item).groupItem,
                  "not-selectable": ((_a5 = get(item)) == null ? void 0 : _a5.selectable) === false
                };
              }
            ]);
            event("mouseover", div_2, () => handleHover(i));
            event("focus", div_2, () => handleHover(i));
            event("click", div_2, stopPropagation(() => handleItemClick({ item: get(item), i })));
            event("keydown", div_2, preventDefault(stopPropagation(function($$arg) {
              bubble_event.call(this, $$props, $$arg);
            })));
            append($$anchor4, div_2);
          });
          append($$anchor3, fragment_2);
        };
        var consequent_3 = ($$anchor3) => {
          var fragment_4 = comment();
          var node_8 = first_child(fragment_4);
          slot(node_8, $$props, "empty", {}, ($$anchor4) => {
            var div_4 = root_113();
            append($$anchor4, div_4);
          });
          append($$anchor3, fragment_4);
        };
        if_block(node_4, ($$render) => {
          if (untrack(() => $$slots.list)) $$render(consequent_1);
          else if (get(filteredItems), untrack(() => get(filteredItems).length > 0)) $$render(consequent_2, 1);
          else if (!hideEmptyState()) $$render(consequent_3, 2);
        });
      }
      var node_9 = sibling(node_4, 2);
      {
        var consequent_4 = ($$anchor3) => {
          var fragment_5 = comment();
          var node_10 = first_child(fragment_5);
          slot(node_10, $$props, "list-append", {}, null);
          append($$anchor3, fragment_5);
        };
        if_block(node_9, ($$render) => {
          if (untrack(() => $$slots["list-append"])) $$render(consequent_4);
        });
      }
      reset(div_1);
      action(div_1, ($$node) => floatingContent == null ? void 0 : floatingContent($$node));
      bind_this(div_1, ($$value) => set(list, $$value), () => get(list));
      effect(() => event("scroll", div_1, handleListScroll));
      effect(() => event("pointerup", div_1, preventDefault(stopPropagation(function($$arg) {
        bubble_event.call(this, $$props, $$arg);
      }))));
      effect(() => event("mousedown", div_1, preventDefault(stopPropagation(function($$arg) {
        bubble_event.call(this, $$props, $$arg);
      }))));
      template_effect(() => classes_1 = set_class(div_1, 1, "svelte-select-list svelte-1ul7oo4", null, classes_1, { prefloat: get(prefloat) }));
      append($$anchor2, div_1);
    };
    if_block(node_1, ($$render) => {
      if (listOpen()) $$render(consequent_5);
    });
  }
  var span = sibling(node_1, 2);
  var node_11 = child(span);
  {
    var consequent_6 = ($$anchor2) => {
      var fragment_6 = root_37();
      var span_1 = first_child(fragment_6);
      var text_1 = child(span_1, true);
      reset(span_1);
      var span_2 = sibling(span_1, 2);
      var text_2 = child(span_2, true);
      reset(span_2);
      template_effect(() => {
        set_text(text_1, get(ariaSelection));
        set_text(text_2, get(ariaContext));
      });
      append($$anchor2, fragment_6);
    };
    if_block(node_11, ($$render) => {
      if (focused()) $$render(consequent_6);
    });
  }
  reset(span);
  var div_5 = sibling(span, 2);
  var node_12 = child(div_5);
  slot(node_12, $$props, "prepend", {}, null);
  reset(div_5);
  var div_6 = sibling(div_5, 2);
  var node_13 = child(div_6);
  {
    var consequent_9 = ($$anchor2) => {
      var fragment_7 = comment();
      var node_14 = first_child(fragment_7);
      {
        var consequent_8 = ($$anchor3) => {
          var fragment_8 = comment();
          var node_15 = first_child(fragment_8);
          each(node_15, 1, value, index, ($$anchor4, item, i) => {
            var div_7 = root_55();
            let classes_3;
            var span_3 = child(div_7);
            var node_16 = child(span_3);
            slot(
              node_16,
              $$props,
              "selection",
              {
                get selection() {
                  return get(item);
                },
                index: i
              },
              ($$anchor5) => {
                var text_3 = text();
                template_effect(() => set_text(text_3, (get(item), deep_read_state(label()), untrack(() => get(item)[label()]))));
                append($$anchor5, text_3);
              }
            );
            reset(span_3);
            var node_17 = sibling(span_3, 2);
            {
              var consequent_7 = ($$anchor5) => {
                var div_8 = root_47();
                var node_18 = child(div_8);
                slot(node_18, $$props, "multi-clear-icon", {}, ($$anchor6) => {
                  ClearIcon($$anchor6, {});
                });
                reset(div_8);
                event("pointerup", div_8, preventDefault(stopPropagation(() => handleMultiItemClear(i))));
                append($$anchor5, div_8);
              };
              if_block(node_17, ($$render) => {
                if (!disabled() && !multiFullItemClearable() && ClearIcon) $$render(consequent_7);
              });
            }
            reset(div_7);
            template_effect(() => classes_3 = set_class(div_7, 1, "multi-item svelte-1ul7oo4", null, classes_3, { active: get(activeValue) === i, disabled: disabled() }));
            event("click", div_7, preventDefault(() => multiFullItemClearable() ? handleMultiItemClear(i) : {}));
            event("keydown", div_7, preventDefault(stopPropagation(function($$arg) {
              bubble_event.call(this, $$props, $$arg);
            })));
            append($$anchor4, div_7);
          });
          append($$anchor3, fragment_8);
        };
        var alternate = ($$anchor3) => {
          var div_9 = root_64();
          let classes_4;
          var node_19 = child(div_9);
          slot(
            node_19,
            $$props,
            "selection",
            {
              get selection() {
                return value();
              }
            },
            ($$anchor4) => {
              var text_4 = text();
              template_effect(() => set_text(text_4, (deep_read_state(value()), deep_read_state(label()), untrack(() => value()[label()]))));
              append($$anchor4, text_4);
            }
          );
          reset(div_9);
          template_effect(() => classes_4 = set_class(div_9, 1, "selected-item svelte-1ul7oo4", null, classes_4, { "hide-selected-item": get(hideSelectedItem) }));
          append($$anchor3, div_9);
        };
        if_block(node_14, ($$render) => {
          if (multiple()) $$render(consequent_8);
          else $$render(alternate, -1);
        });
      }
      append($$anchor2, fragment_7);
    };
    if_block(node_13, ($$render) => {
      if (get(hasValue)) $$render(consequent_9);
    });
  }
  var input_1 = sibling(node_13, 2);
  attribute_effect(
    input_1,
    () => ({
      readOnly: !searchable(),
      ...get(_inputAttributes),
      placeholder: get(placeholderText),
      style: inputStyles(),
      disabled: disabled()
    }),
    void 0,
    void 0,
    void 0,
    "svelte-1ul7oo4",
    true
  );
  bind_this(input_1, ($$value) => input($$value), () => input());
  reset(div_6);
  var div_10 = sibling(div_6, 2);
  var node_20 = child(div_10);
  {
    var consequent_10 = ($$anchor2) => {
      var div_11 = root_73();
      var node_21 = child(div_11);
      slot(node_21, $$props, "loading-icon", {}, ($$anchor3) => {
        LoadingIcon($$anchor3, {});
      });
      reset(div_11);
      append($$anchor2, div_11);
    };
    if_block(node_20, ($$render) => {
      if (loading()) $$render(consequent_10);
    });
  }
  var node_22 = sibling(node_20, 2);
  {
    var consequent_11 = ($$anchor2) => {
      var button = root_82();
      var node_23 = child(button);
      slot(node_23, $$props, "clear-icon", {}, ($$anchor3) => {
        ClearIcon($$anchor3, {});
      });
      reset(button);
      event("click", button, handleClear);
      append($$anchor2, button);
    };
    if_block(node_22, ($$render) => {
      if (get(showClear)) $$render(consequent_11);
    });
  }
  var node_24 = sibling(node_22, 2);
  {
    var consequent_12 = ($$anchor2) => {
      var div_12 = root_92();
      var node_25 = child(div_12);
      slot(
        node_25,
        $$props,
        "chevron-icon",
        {
          get listOpen() {
            return listOpen();
          }
        },
        ($$anchor3) => {
          ChevronIcon($$anchor3, {});
        }
      );
      reset(div_12);
      append($$anchor2, div_12);
    };
    if_block(node_24, ($$render) => {
      if (showChevron()) $$render(consequent_12);
    });
  }
  reset(div_10);
  var node_26 = sibling(div_10, 2);
  slot(
    node_26,
    $$props,
    "input-hidden",
    {
      get value() {
        return value();
      }
    },
    ($$anchor2) => {
      var input_2 = root_102();
      remove_input_defaults(input_2);
      template_effect(
        ($0) => {
          set_attribute2(input_2, "name", name());
          set_value(input_2, $0);
        },
        [
          () => (deep_read_state(value()), untrack(() => value() ? JSON.stringify(value()) : null))
        ]
      );
      append($$anchor2, input_2);
    }
  );
  var node_27 = sibling(node_26, 2);
  {
    var consequent_13 = ($$anchor2) => {
      var fragment_15 = comment();
      var node_28 = first_child(fragment_15);
      slot(
        node_28,
        $$props,
        "required",
        {
          get value() {
            return value();
          }
        },
        ($$anchor3) => {
          var select = root_114();
          append($$anchor3, select);
        }
      );
      append($$anchor2, fragment_15);
    };
    if_block(node_27, ($$render) => {
      if (deep_read_state(required()), deep_read_state(value()), untrack(() => required() && (!value() || value().length === 0))) $$render(consequent_13);
    });
  }
  reset(div);
  effect(() => event("pointerup", div, preventDefault(handleClick)));
  bind_this(div, ($$value) => container($$value), () => container());
  action(div, ($$node) => floatingRef == null ? void 0 : floatingRef($$node));
  template_effect(() => {
    var _a5;
    classes = set_class(div, 1, `svelte-select ${(_a5 = containerClasses()) != null ? _a5 : ""}`, "svelte-1ul7oo4", classes, {
      multi: multiple(),
      disabled: disabled(),
      focused: focused(),
      "list-open": listOpen(),
      "show-chevron": showChevron(),
      error: hasError()
    });
    set_style(div, containerStyles());
  });
  event("keydown", input_1, handleKeyDown);
  event("blur", input_1, handleBlur);
  event("focus", input_1, handleFocus);
  bind_value(input_1, filterText);
  append($$anchor, div);
  bind_prop($$props, "getFilteredItems", getFilteredItems);
  bind_prop($$props, "handleClear", handleClear);
  return pop($$exports);
}

// src/ui/components/select/selection.ts
function toValidSelectedOptions(selected, availableValues) {
  if (!Array.isArray(selected)) {
    return [];
  }
  const validSelections = [];
  for (const entry of selected) {
    if (typeof entry === "object" && entry !== null && "label" in entry && "value" in entry) {
      const label = entry.label;
      const value = entry.value;
      if (typeof label === "string" && typeof value === "string" && availableValues.has(value)) {
        validSelections.push(entry);
      }
    }
  }
  return validSelections;
}

// src/ui/components/select/base_select.svelte
var root18 = from_html(`<span role="button" tabindex="0" class="delete-btn svelte-vdzxvu">\xD7</span>`);
var root_115 = from_html(`<li class="svelte-vdzxvu"><!> <span role="button" tabindex="0"> </span></li>`);
var root_210 = from_html(`<div><label class="svelte-vdzxvu"> </label> <div class="saved-filters svelte-vdzxvu"><details style="position: relative;" class="svelte-vdzxvu"><summary class="svelte-vdzxvu">Saved filters</summary> <ul role="list" style="position: absolute; top: 100%; left: 0; z-index: 100; min-width: max-content;" class="svelte-vdzxvu"></ul></details></div> <div class="select-wrapper"><svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper></div> <div class="filter-actions svelte-vdzxvu"><button class="filter-action-btn save-btn svelte-vdzxvu" aria-label="Save filter">Save</button> <button class="filter-action-btn clear-btn svelte-vdzxvu" aria-label="Clear filter">Clear</button></div></div>`);
var $$css18 = {
  hash: "svelte-vdzxvu",
  code: "label.svelte-vdzxvu {display:inline-block;margin-bottom:var(--size-4-1);font-weight:600;}.saved-filters.svelte-vdzxvu {margin-top:var(--size-4-1);font-size:var(--font-ui-small);align-self:flex-start;}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) summary:where(.svelte-vdzxvu) {cursor:pointer;color:var(--text-muted);padding:var(--size-2-1) 0;user-select:none;transition:color 0.15s ease;}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) summary:where(.svelte-vdzxvu):hover {color:var(--text-normal);}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) ul:where(.svelte-vdzxvu) {margin:0;padding:var(--size-2-2) !important;list-style:none;background:var(--background-primary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);box-shadow:var(--shadow-s);z-index:100;display:flex;flex-direction:column;gap:4px;align-items:flex-start;}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) ul:where(.svelte-vdzxvu) li:where(.svelte-vdzxvu) {margin:0;display:flex;align-items:center;border-radius:var(--radius-s);transition:background 0.15s ease;}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) ul:where(.svelte-vdzxvu) li:where(.svelte-vdzxvu):hover {background:var(--background-modifier-hover);}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) ul:where(.svelte-vdzxvu) li:where(.svelte-vdzxvu) span[role=button]:where(.svelte-vdzxvu) {text-align:left;padding:var(--size-2-1) var(--size-2-2);background:transparent;border:none;cursor:pointer;color:var(--text-normal);white-space:nowrap;transition:color 0.15s ease;}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) ul:where(.svelte-vdzxvu) li:where(.svelte-vdzxvu) span[role=button].active:where(.svelte-vdzxvu) {font-weight:700;color:var(--interactive-accent);}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) ul:where(.svelte-vdzxvu) li:where(.svelte-vdzxvu) span[role=button].delete-btn:where(.svelte-vdzxvu) {padding:var(--size-2-1) 0 var(--size-2-1) var(--size-2-2);display:flex;align-items:center;justify-content:center;font-size:18px;line-height:1;color:var(--text-muted);}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) ul:where(.svelte-vdzxvu) li:where(.svelte-vdzxvu) span[role=button].delete-btn:where(.svelte-vdzxvu):hover {color:var(--color-red);}.saved-filters.svelte-vdzxvu details:where(.svelte-vdzxvu) ul:where(.svelte-vdzxvu) li:where(.svelte-vdzxvu) span[role=button].filter-text:where(.svelte-vdzxvu) {padding-left:var(--size-2-1);}.filter-actions.svelte-vdzxvu {display:flex;gap:var(--size-4-2);margin-top:var(--size-4-2);}.filter-action-btn.svelte-vdzxvu {padding:var(--size-2-2) var(--size-4-3);border-radius:var(--radius-s);cursor:pointer;font-size:var(--font-ui-small);transition:background 150ms ease, opacity 150ms ease;}.filter-action-btn.save-btn.svelte-vdzxvu {background:var(--interactive-accent);color:var(--text-on-accent);border:none;}.filter-action-btn.save-btn.svelte-vdzxvu:hover:not(:disabled) {background:var(--interactive-accent-hover);}.filter-action-btn.clear-btn.svelte-vdzxvu {background:transparent;color:var(--text-muted);border:1px solid var(--background-modifier-border);}.filter-action-btn.clear-btn.svelte-vdzxvu:hover:not(:disabled) {background:var(--background-modifier-hover);}.filter-action-btn.svelte-vdzxvu:disabled {opacity:0.5;cursor:not-allowed;}.svelte-select button > svg,\n.svelte-select .multi-item-clear > svg {cursor:pointer;}.svelte-select .multi-item {border:var(--border-width) solid var(--pill-border-color) !important;outline:none !important;}.svelte-select .svelte-select-list {z-index:5;}.svelte-select .clear-select {display:none !important;}.svelte-select.focused {transition:box-shadow 150ms ease;}.svelte-select input:focus-visible {outline:none;}"
};
function Base_select($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Base_select, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css18);
  const fieldName = mutable_source();
  const availableValues = mutable_source();
  const selectedItemsFromValue = mutable_source();
  const savedFilterOptions = mutable_source();
  let label = prop($$props, "label", 12);
  let items = prop($$props, "items", 12);
  let value = prop($$props, "value", 12);
  let savedFilters = prop($$props, "savedFilters", 28, () => []);
  let loadSavedFilter = prop($$props, "loadSavedFilter", 12, void 0);
  let addButtonDisabled = prop($$props, "addButtonDisabled", 12, false);
  let onAddClick = prop($$props, "onAddClick", 12, void 0);
  let clearButtonDisabled = prop($$props, "clearButtonDisabled", 12, false);
  let onClearClick = prop($$props, "onClearClick", 12, void 0);
  let activeFilterId = prop($$props, "activeFilterId", 12, void 0);
  let onDeleteClick = prop($$props, "onDeleteClick", 12, void 0);
  let selectedItems = mutable_source(items().filter((item) => value().includes(item.value)));
  function clearSelection() {
    set(selectedItems, []);
    value([]);
  }
  async function handleSavedFilterSelect(option) {
    if (loadSavedFilter()) {
      loadSavedFilter()(option.filter);
      await tick();
      set(selectedItems, items().filter((item) => value().includes(item.value)));
    }
  }
  function handleSelectInput(event2) {
    set(selectedItems, toValidSelectedOptions(event2.detail, get(availableValues)));
    value(get(selectedItems).map((option) => option.value));
  }
  legacy_pre_effect(() => deep_read_state(label()), () => {
    set(fieldName, `field=${label()}`);
  });
  legacy_pre_effect(() => deep_read_state(items()), () => {
    set(availableValues, new Set(items().map((item) => item.value)));
  });
  legacy_pre_effect(() => (deep_read_state(items()), deep_read_state(value())), () => {
    set(selectedItemsFromValue, items().filter((item) => value().includes(item.value)));
  });
  legacy_pre_effect(() => (get(selectedItems), get(selectedItemsFromValue)), () => {
    const currentValues = get(selectedItems).map((item) => item.value).sort().join(",");
    const nextValues = get(selectedItemsFromValue).map((item) => item.value).sort().join(",");
    if (currentValues !== nextValues) {
      set(selectedItems, get(selectedItemsFromValue));
    }
  });
  legacy_pre_effect(() => deep_read_state(savedFilters()), () => {
    set(savedFilterOptions, savedFilters().map((filter2) => {
      const displayText = filter2.tag ? filter2.tag.tags.join(", ") : "";
      return { filter: filter2, displayText };
    }));
  });
  legacy_pre_effect_reset();
  var $$exports = {
    clearSelection,
    get label() {
      return label();
    },
    set label($$value) {
      label($$value);
      flushSync();
    },
    get items() {
      return items();
    },
    set items($$value) {
      items($$value);
      flushSync();
    },
    get value() {
      return value();
    },
    set value($$value) {
      value($$value);
      flushSync();
    },
    get savedFilters() {
      return savedFilters();
    },
    set savedFilters($$value) {
      savedFilters($$value);
      flushSync();
    },
    get loadSavedFilter() {
      return loadSavedFilter();
    },
    set loadSavedFilter($$value) {
      loadSavedFilter($$value);
      flushSync();
    },
    get addButtonDisabled() {
      return addButtonDisabled();
    },
    set addButtonDisabled($$value) {
      addButtonDisabled($$value);
      flushSync();
    },
    get onAddClick() {
      return onAddClick();
    },
    set onAddClick($$value) {
      onAddClick($$value);
      flushSync();
    },
    get clearButtonDisabled() {
      return clearButtonDisabled();
    },
    set clearButtonDisabled($$value) {
      clearButtonDisabled($$value);
      flushSync();
    },
    get onClearClick() {
      return onClearClick();
    },
    set onClearClick($$value) {
      onClearClick($$value);
      flushSync();
    },
    get activeFilterId() {
      return activeFilterId();
    },
    set activeFilterId($$value) {
      activeFilterId($$value);
      flushSync();
    },
    get onDeleteClick() {
      return onDeleteClick();
    },
    set onDeleteClick($$value) {
      onDeleteClick($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root_210();
  var label_1 = child(div);
  var text2 = child(label_1);
  reset(label_1);
  var div_1 = sibling(label_1, 2);
  var details = child(div_1);
  var ul = sibling(child(details), 2);
  each(ul, 5, () => get(savedFilterOptions), index, ($$anchor2, option) => {
    var li = root_115();
    var node = child(li);
    {
      var consequent = ($$anchor3) => {
        var span = root18();
        template_effect(() => {
          var _a5;
          return set_attribute2(span, "aria-label", `Delete filter: ${(_a5 = (get(option), untrack(() => get(option).displayText))) != null ? _a5 : ""}`);
        });
        event("click", span, () => {
          var _a5;
          return (_a5 = onDeleteClick()) == null ? void 0 : _a5(get(option).filter.id, get(option).displayText);
        });
        event("keydown", span, (e) => {
          var _a5;
          return e.key === "Enter" && ((_a5 = onDeleteClick()) == null ? void 0 : _a5(get(option).filter.id, get(option).displayText));
        });
        append($$anchor3, span);
      };
      if_block(node, ($$render) => {
        if (onDeleteClick()) $$render(consequent);
      });
    }
    var span_1 = sibling(node, 2);
    let classes;
    var text_1 = child(span_1, true);
    reset(span_1);
    reset(li);
    template_effect(() => {
      var _a5;
      classes = set_class(span_1, 1, "filter-text svelte-vdzxvu", null, classes, { active: get(option).filter.id === activeFilterId() });
      set_attribute2(span_1, "aria-label", `Load saved filter: ${(_a5 = (get(option), untrack(() => get(option).displayText))) != null ? _a5 : ""}`);
      set_attribute2(span_1, "aria-pressed", (get(option), deep_read_state(activeFilterId()), untrack(() => get(option).filter.id === activeFilterId())));
      set_text(text_1, (get(option), untrack(() => get(option).displayText)));
    });
    event("click", span_1, () => handleSavedFilterSelect(get(option)));
    event("keydown", span_1, (e) => e.key === "Enter" && handleSavedFilterSelect(get(option)));
    append($$anchor2, li);
  });
  reset(ul);
  reset(details);
  reset(div_1);
  var div_2 = sibling(div_1, 2);
  var node_1 = child(div_2);
  {
    css_props(node_1, () => ({
      "--background": "var(--background-primary)",
      "--border": "var(--border-width) solid var(--background-modifier-border)",
      "--border-focused": "var(--border-width) solid var(--background-modifier-border-focus)",
      "--border-hover": "var(--border-width) solid var(--background-modifier-border-hover)",
      "--border-radius": "var(--input-radius)",
      "--item-hover-bg": "var(--background-modifier-hover)",
      "--list-background": "var(--background-primary)",
      "--list-border": "var(--border-width) solid var(--background-modifier-border)",
      "--multi-item-bg": "var(--pill-background)",
      "--multi-item-clear-icon-color": "var(--pill-color)",
      "--multi-item-color": "var(--pill-color)",
      "--multi-item-height": "auto",
      "--multi-item-outline": "var(--border-width) solid var(--pill-border-color)",
      "--multi-item-padding": "var(--pill-padding-y) var(--pill-padding-x)",
      "--multi-select-input-padding": "var(--size-4-2)",
      "--multi-select-input-margin": "var(--size-2-2) var(--size-4-4) var(--size-2-2) var(--size-2-2)",
      "--input-color": "var(--text-normal)",
      "--placeholder-color": "var(--text-muted)"
    }));
    Select(node_1.lastChild, {
      get name() {
        return get(fieldName);
      },
      multiple: true,
      closeListOnChange: false,
      listAutoWidth: true,
      placeholder: "",
      get items() {
        return items();
      },
      get value() {
        return get(selectedItems);
      },
      $$events: { input: handleSelectInput }
    });
    reset(node_1);
  }
  reset(div_2);
  var div_3 = sibling(div_2, 2);
  var button = child(div_3);
  var button_1 = sibling(button, 2);
  reset(div_3);
  reset(div);
  template_effect(() => {
    var _a5;
    set_attribute2(label_1, "for", get(fieldName));
    set_text(text2, `${(_a5 = label()) != null ? _a5 : ""}:`);
    button.disabled = addButtonDisabled();
    button_1.disabled = clearButtonDisabled();
  });
  event("click", button, function(...$$args) {
    var _a5;
    (_a5 = onAddClick()) == null ? void 0 : _a5.apply(this, $$args);
  });
  event("click", button_1, function(...$$args) {
    var _a5;
    (_a5 = onClearClick()) == null ? void 0 : _a5.apply(this, $$args);
  });
  append($$anchor, div);
  bind_prop($$props, "clearSelection", clearSelection);
  return pop($$exports);
}

// src/ui/components/select/select_tag.svelte
function Select_tag($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Select_tag, ...$$anchor });
  push($$props, false);
  let tags = prop($$props, "tags", 12);
  let value = prop($$props, "value", 12);
  let savedFilters = prop($$props, "savedFilters", 28, () => []);
  let onLoadFilter = prop($$props, "onLoadFilter", 12, void 0);
  let addButtonDisabled = prop($$props, "addButtonDisabled", 12, false);
  let onAddClick = prop($$props, "onAddClick", 12, void 0);
  let clearButtonDisabled = prop($$props, "clearButtonDisabled", 12, false);
  let onClearClick = prop($$props, "onClearClick", 12, void 0);
  let activeFilterId = prop($$props, "activeFilterId", 12, void 0);
  let onDeleteClick = prop($$props, "onDeleteClick", 12, void 0);
  let baseSelectRef = mutable_source();
  function loadSavedFilter(filter2) {
    var _a5, _b3;
    if (filter2.tag) {
      if (activeFilterId() === filter2.id) {
        (_a5 = get(baseSelectRef)) == null ? void 0 : _a5.clearSelection();
      } else {
        value([...filter2.tag.tags]);
      }
      (_b3 = onLoadFilter()) == null ? void 0 : _b3(filter2.id);
    }
  }
  function handleClear() {
    var _a5, _b3;
    (_a5 = get(baseSelectRef)) == null ? void 0 : _a5.clearSelection();
    (_b3 = onClearClick()) == null ? void 0 : _b3();
  }
  var $$exports = {
    get tags() {
      return tags();
    },
    set tags($$value) {
      tags($$value);
      flushSync();
    },
    get value() {
      return value();
    },
    set value($$value) {
      value($$value);
      flushSync();
    },
    get savedFilters() {
      return savedFilters();
    },
    set savedFilters($$value) {
      savedFilters($$value);
      flushSync();
    },
    get onLoadFilter() {
      return onLoadFilter();
    },
    set onLoadFilter($$value) {
      onLoadFilter($$value);
      flushSync();
    },
    get addButtonDisabled() {
      return addButtonDisabled();
    },
    set addButtonDisabled($$value) {
      addButtonDisabled($$value);
      flushSync();
    },
    get onAddClick() {
      return onAddClick();
    },
    set onAddClick($$value) {
      onAddClick($$value);
      flushSync();
    },
    get clearButtonDisabled() {
      return clearButtonDisabled();
    },
    set clearButtonDisabled($$value) {
      clearButtonDisabled($$value);
      flushSync();
    },
    get onClearClick() {
      return onClearClick();
    },
    set onClearClick($$value) {
      onClearClick($$value);
      flushSync();
    },
    get activeFilterId() {
      return activeFilterId();
    },
    set activeFilterId($$value) {
      activeFilterId($$value);
      flushSync();
    },
    get onDeleteClick() {
      return onDeleteClick();
    },
    set onDeleteClick($$value) {
      onDeleteClick($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  {
    let $0 = derived_safe_equal(() => (deep_read_state(tags()), untrack(() => tags().map((tag2) => ({ label: tag2, value: tag2 })))));
    bind_this(
      Base_select($$anchor, {
        get items() {
          return get($0);
        },
        label: "Filter by tag",
        get savedFilters() {
          return savedFilters();
        },
        loadSavedFilter,
        get addButtonDisabled() {
          return addButtonDisabled();
        },
        get onAddClick() {
          return onAddClick();
        },
        get clearButtonDisabled() {
          return clearButtonDisabled();
        },
        onClearClick: handleClear,
        get activeFilterId() {
          return activeFilterId();
        },
        get onDeleteClick() {
          return onDeleteClick();
        },
        get value() {
          return value();
        },
        set value($$value) {
          value($$value);
        },
        $$legacy: true
      }),
      ($$value) => set(baseSelectRef, $$value),
      () => get(baseSelectRef)
    );
  }
  return pop($$exports);
}

// src/ui/components/delete_filter_modal.svelte
var root19 = from_html(`<div class="modal-backdrop svelte-z61jvf" role="presentation"><div class="modal svelte-z61jvf" role="dialog" aria-modal="true" aria-labelledby="modal-title"><h3 id="modal-title" class="svelte-z61jvf">Delete saved filter?</h3> <div class="filter-preview svelte-z61jvf"> </div> <div class="modal-actions svelte-z61jvf"><button class="cancel-btn svelte-z61jvf">Cancel</button> <button class="delete-btn svelte-z61jvf">Delete</button></div></div></div>`);
var $$css19 = {
  hash: "svelte-z61jvf",
  code: ".modal-backdrop.svelte-z61jvf {position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0, 0, 0, 0.5);display:flex;align-items:flex-start;justify-content:center;padding-top:20vh;z-index:1000;}.modal.svelte-z61jvf {background:var(--background-primary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);padding:var(--size-4-4);min-width:300px;max-width:500px;box-shadow:var(--shadow-l);pointer-events:auto;}h3.svelte-z61jvf {margin:0 0 var(--size-4-3) 0;font-size:var(--font-ui-medium);font-weight:var(--font-semibold);}.filter-preview.svelte-z61jvf {padding:var(--size-4-2);background:var(--background-secondary);border-radius:var(--radius-s);margin-bottom:var(--size-4-4);font-family:var(--font-monospace);font-size:var(--font-ui-small);}.modal-actions.svelte-z61jvf {display:flex;gap:var(--size-4-2);justify-content:flex-end;}button.svelte-z61jvf {padding:var(--size-4-1) var(--size-4-3);border-radius:var(--radius-s);cursor:pointer;font-size:var(--font-ui-small);transition:background 100ms linear;}.cancel-btn.svelte-z61jvf {background:var(--background-secondary);border:1px solid var(--background-modifier-border);color:var(--text-normal);}.cancel-btn.svelte-z61jvf:hover {background:var(--background-secondary-alt);}.delete-btn.svelte-z61jvf {background:var(--color-red);border:none;color:white;}.delete-btn.svelte-z61jvf:hover {background:var(--color-red);opacity:0.8;}"
};
function Delete_filter_modal($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Delete_filter_modal, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css19);
  let filterText = prop($$props, "filterText", 12);
  let onConfirm = prop($$props, "onConfirm", 12);
  let onCancel = prop($$props, "onCancel", 12);
  let modalElement = mutable_source();
  let deleteButton = mutable_source();
  function handleKeydown(event2) {
    if (event2.key === "Escape") {
      onCancel()();
    }
  }
  onMount(() => {
    var _a5;
    (_a5 = get(deleteButton)) == null ? void 0 : _a5.focus();
    const focusableElements = get(modalElement).querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];
    const handleTabKey = (e) => {
      if (e.key === "Tab") {
        if (e.shiftKey && document.activeElement === firstElement) {
          e.preventDefault();
          lastElement == null ? void 0 : lastElement.focus();
        } else if (!e.shiftKey && document.activeElement === lastElement) {
          e.preventDefault();
          firstElement == null ? void 0 : firstElement.focus();
        }
      }
    };
    get(modalElement).addEventListener("keydown", handleTabKey);
    return () => get(modalElement).removeEventListener("keydown", handleTabKey);
  });
  var $$exports = {
    get filterText() {
      return filterText();
    },
    set filterText($$value) {
      filterText($$value);
      flushSync();
    },
    get onConfirm() {
      return onConfirm();
    },
    set onConfirm($$value) {
      onConfirm($$value);
      flushSync();
    },
    get onCancel() {
      return onCancel();
    },
    set onCancel($$value) {
      onCancel($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root19();
  event("keydown", $window, handleKeydown);
  var div_1 = child(div);
  var div_2 = sibling(child(div_1), 2);
  var text2 = child(div_2, true);
  reset(div_2);
  var div_3 = sibling(div_2, 2);
  var button = child(div_3);
  var button_1 = sibling(button, 2);
  bind_this(button_1, ($$value) => set(deleteButton, $$value), () => get(deleteButton));
  reset(div_3);
  reset(div_1);
  bind_this(div_1, ($$value) => set(modalElement, $$value), () => get(modalElement));
  reset(div);
  template_effect(() => set_text(text2, filterText()));
  event("click", button, function(...$$args) {
    var _a5;
    (_a5 = onCancel()) == null ? void 0 : _a5.apply(this, $$args);
  });
  event("click", button_1, function(...$$args) {
    var _a5;
    (_a5 = onConfirm()) == null ? void 0 : _a5.apply(this, $$args);
  });
  event("click", div, (e) => e.target === e.currentTarget && onCancel()());
  append($$anchor, div);
  return pop($$exports);
}

// src/ui/board_counts.ts
function isActiveBoardTask(task) {
  return task.column !== "archived" && !task.done && task.column !== "done";
}
function getBoardTaskCount(tasks) {
  return tasks.filter(isActiveBoardTask).length;
}

// src/ui/filters/filter_state.ts
function readBoardFilterState(settings) {
  var _a5, _b3, _c2, _d;
  return {
    contentText: (_a5 = settings.lastContentFilter) != null ? _a5 : "",
    tagValues: [...(_b3 = settings.lastTagFilter) != null ? _b3 : []],
    fileText: (_d = (_c2 = settings.lastFileFilter) == null ? void 0 : _c2[0]) != null ? _d : ""
  };
}
function writeBoardFilterState(settings, state2) {
  return {
    ...settings,
    lastContentFilter: state2.contentText,
    lastTagFilter: [...state2.tagValues],
    lastFileFilter: state2.fileText ? [state2.fileText] : []
  };
}
function serializeBoardFilterState(state2) {
  return JSON.stringify({
    contentText: state2.contentText,
    tagValues: state2.tagValues,
    fileText: state2.fileText
  });
}
function shouldApplyIncomingBoardFilterState(currentState, incomingState, lastPersistedStateKey, hydrated) {
  if (!hydrated) {
    return true;
  }
  const currentStateKey = serializeBoardFilterState(currentState);
  const incomingStateKey = serializeBoardFilterState(incomingState);
  return currentStateKey === lastPersistedStateKey && incomingStateKey !== lastPersistedStateKey;
}

// src/ui/main.svelte
var root20 = from_html(`<li class="svelte-16qe0yp"><span role="button" tabindex="0" class="delete-btn svelte-16qe0yp">\xD7</span> <span role="button" tabindex="0"> </span></li>`);
var root_116 = from_html(`<option> </option>`);
var root_211 = from_html(`<datalist id="content-filters"></datalist>`);
var root_38 = from_html(`<datalist id="file-paths"></datalist>`);
var root_48 = from_html(`<aside class="filters-sidebar svelte-16qe0yp"><button class="resize-handle svelte-16qe0yp" aria-label="Resize sidebar"></button> <div class="controls svelte-16qe0yp"><div class="text-filter svelte-16qe0yp"><label for="filter" class="svelte-16qe0yp">Filter by content:</label> <div class="saved-filters svelte-16qe0yp"><details class="svelte-16qe0yp"><summary class="svelte-16qe0yp">Saved filters</summary> <ul role="list" class="svelte-16qe0yp"></ul></details></div> <div class="filter-input-container svelte-16qe0yp"><input id="filter" name="filter" type="search" placeholder="Type to search..." list="content-filters" class="svelte-16qe0yp"/> <!></div> <div class="filter-actions svelte-16qe0yp"><button class="filter-action-btn save-btn svelte-16qe0yp" aria-label="Save filter">Save</button> <button class="filter-action-btn clear-btn svelte-16qe0yp" aria-label="Clear filter">Clear</button></div></div> <div class="tag-filter svelte-16qe0yp"><!></div> <div class="file-filter svelte-16qe0yp"><label for="file-filter" class="svelte-16qe0yp">Filter by file:</label> <div class="saved-filters svelte-16qe0yp"><details class="svelte-16qe0yp"><summary class="svelte-16qe0yp">Saved filters</summary> <ul role="list" class="svelte-16qe0yp"></ul></details></div> <div class="filter-input-container svelte-16qe0yp"><input id="file-filter" name="file-filter" type="search" placeholder="Type to search files..." list="file-paths" aria-label="Filter by file path" class="svelte-16qe0yp"/> <!></div> <div class="filter-actions svelte-16qe0yp"><button class="filter-action-btn save-btn svelte-16qe0yp" aria-label="Save filter">Save</button> <button class="filter-action-btn clear-btn svelte-16qe0yp" aria-label="Clear file filter">Clear</button></div></div></div></aside>`);
var root_56 = from_html(`<li class="svelte-16qe0yp"><span role="button" tabindex="0" class="delete-btn svelte-16qe0yp" aria-label="Delete saved grouping">\xD7</span> <span role="button" tabindex="0"> </span></li>`);
var root_65 = from_html(`<div class="saved-filters saved-groups svelte-16qe0yp"><details class="svelte-16qe0yp"><summary class="svelte-16qe0yp">Saved groups</summary> <ul role="list" class="svelte-16qe0yp"></ul></details></div>`);
var root_74 = from_html(`<div class="grouping-controls svelte-16qe0yp"><div class="grouping-prefix-row svelte-16qe0yp"><input type="text" class="grouping-prefix-input svelte-16qe0yp" placeholder="Prefix (e.g. Sprint-)"/> <button class="filter-action-btn save-btn grouping-save-btn svelte-16qe0yp">Save</button></div> <!></div>`);
var root_83 = from_html(`<optgroup label="Properties"></optgroup>`);
var root_93 = from_html(`<button class="sort-direction-btn svelte-16qe0yp" aria-label="Toggle group direction"><!></button>`);
var root_103 = from_html(`<button class="sort-direction-btn svelte-16qe0yp" aria-label="Toggle sort direction"><!></button>`);
var root_117 = from_html(`<div class="main svelte-16qe0yp"><button class="sidebar-toggle-btn svelte-16qe0yp"><span class="toggle-icon svelte-16qe0yp"> </span> <span class="toggle-label svelte-16qe0yp">Filters</span></button> <div><!> <div class="board-content svelte-16qe0yp"><div class="board-header svelte-16qe0yp"><div class="board-header-controls svelte-16qe0yp"><!> <select class="dropdown group-by-select svelte-16qe0yp"><option>Group by: (none)</option><option>Group by: File</option><option>Group by: Tag</option><!></select> <!> <select class="dropdown sort-by-select svelte-16qe0yp"><option>Sort: File order</option><option>Sort: Task name</option><option>Sort: Manual</option><optgroup label="Properties"></optgroup></select> <!> <span class="board-task-count svelte-16qe0yp" aria-live="polite"><!></span> <!></div></div> <div><!></div></div></div></div> <!>`, 1);
var $$css20 = {
  hash: "svelte-16qe0yp",
  code: ".main.svelte-16qe0yp {height:100%;display:flex;flex-direction:column;font-size:var(--font-text-size);}.main.svelte-16qe0yp .sidebar-toggle-btn:where(.svelte-16qe0yp) {position:fixed;top:50px;left:8px;padding:var(--size-2-1) var(--size-2-2);background:var(--background-primary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-s);cursor:pointer;color:var(--text-muted);font-size:var(--font-ui-small);display:flex;align-items:center;gap:var(--size-2-1);z-index:100;transition:color 0.15s ease;}.main.svelte-16qe0yp .sidebar-toggle-btn:where(.svelte-16qe0yp):hover {background:var(--background-modifier-hover);color:var(--text-normal);}.main.svelte-16qe0yp .sidebar-toggle-btn:where(.svelte-16qe0yp) .toggle-icon:where(.svelte-16qe0yp) {font-size:16px;}.main.svelte-16qe0yp .sidebar-toggle-btn:where(.svelte-16qe0yp) .toggle-label:where(.svelte-16qe0yp) {font-weight:500;}.main.svelte-16qe0yp .board-container:where(.svelte-16qe0yp) {display:grid;grid-template-columns:1fr;height:100%;}.main.svelte-16qe0yp .board-container.sidebar-expanded:where(.svelte-16qe0yp) {grid-template-columns:var(--sidebar-width, 280px) 1fr;}.main.svelte-16qe0yp .filters-sidebar:where(.svelte-16qe0yp) {background:var(--background-primary);border-right:1px solid var(--background-modifier-border);overflow-y:auto;display:flex;flex-direction:column;position:relative;}.main.svelte-16qe0yp .filters-sidebar:where(.svelte-16qe0yp) .resize-handle:where(.svelte-16qe0yp) {position:absolute;top:0;right:0;width:4px;height:100%;cursor:col-resize;background:transparent;border:none;padding:0;z-index:10;}.main.svelte-16qe0yp .filters-sidebar:where(.svelte-16qe0yp) .resize-handle:where(.svelte-16qe0yp):hover {background:var(--interactive-accent);opacity:0.5;}.main.svelte-16qe0yp .board-content:where(.svelte-16qe0yp) {display:flex;flex-direction:column;height:100%;overflow:hidden;padding:var(--size-4-3) var(--size-4-4) 0 var(--size-4-4);background:color-mix(in srgb, var(--background-primary) 92%, var(--background-secondary));}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) {display:flex;justify-content:flex-end;align-items:flex-start;padding:0 0 var(--size-4-3) 0;gap:var(--size-4-3);}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .board-task-count:where(.svelte-16qe0yp) {font-size:var(--font-ui-medium);color:var(--text-muted);margin-top:4px; /* to align with input */margin-left:var(--size-4-2);margin-right:var(--size-4-2);}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .board-header-controls:where(.svelte-16qe0yp) {display:flex;align-items:flex-start;gap:var(--size-4-2);min-height:54px; /* prevent shifting when saved groups is toggled */}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .board-header-controls:where(.svelte-16qe0yp) .group-by-select:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .board-header-controls:where(.svelte-16qe0yp) .sort-by-select:where(.svelte-16qe0yp) {font-size:var(--font-ui-smaller);\n  /* Only adjust vertical padding; leave horizontal padding to\n     Obsidian's .dropdown so its chevron keeps its reserved space. */padding-block:var(--size-2-1);}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .board-header-controls:where(.svelte-16qe0yp) .sort-direction-btn:where(.svelte-16qe0yp) {display:inline-flex;align-items:center;justify-content:center;padding:var(--size-2-1) var(--size-2-2);border:var(--input-border-width, 1px) solid var(--background-modifier-border);border-radius:var(--radius-s);background:var(--interactive-normal);color:var(--text-normal);cursor:pointer;}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .board-header-controls:where(.svelte-16qe0yp) .sort-direction-btn:where(.svelte-16qe0yp):hover {background:var(--interactive-hover);}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .grouping-controls:where(.svelte-16qe0yp) {display:flex;flex-direction:column;align-items:flex-start;gap:var(--size-2-2);}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .grouping-prefix-row:where(.svelte-16qe0yp) {display:flex;align-items:center;gap:var(--size-4-2);}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .grouping-prefix-row:where(.svelte-16qe0yp) .grouping-prefix-input:where(.svelte-16qe0yp) {width:140px;font-size:var(--font-ui-small);}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .grouping-prefix-row:where(.svelte-16qe0yp) .grouping-save-btn:where(.svelte-16qe0yp) {padding:var(--size-2-1) var(--size-2-3);font-size:var(--font-ui-smaller);}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .saved-groups:where(.svelte-16qe0yp) {margin-left:var(--size-4-2);margin-bottom:0;}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .saved-groups:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) {position:relative;}.main.svelte-16qe0yp .board-header:where(.svelte-16qe0yp) .saved-groups:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) {position:absolute;top:100%;left:0;z-index:100;min-width:max-content;gap:var(--size-2-2);}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) {margin-top:0;margin-bottom:var(--size-4-2);font-size:var(--font-ui-small);}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) summary:where(.svelte-16qe0yp) {cursor:pointer;color:var(--text-muted);padding:var(--size-2-1) 0;user-select:none;transition:color 0.15s ease;}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) summary:where(.svelte-16qe0yp):hover {color:var(--text-normal);}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) {margin:0;padding:var(--size-2-2) !important;list-style:none;background:var(--background-primary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);box-shadow:var(--shadow-s);z-index:100;}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) li:where(.svelte-16qe0yp) {margin:0;display:flex;align-items:center;border-radius:var(--radius-s);background:var(--background-primary);border:1px solid var(--background-modifier-border);box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);transition:background 0.15s ease;}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) li:where(.svelte-16qe0yp):hover {background:var(--background-modifier-hover);}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) li:where(.svelte-16qe0yp) span[role=button]:where(.svelte-16qe0yp) {text-align:left;padding:var(--size-2-1) var(--size-2-2);background:transparent;border:none;cursor:pointer;color:var(--text-normal);white-space:nowrap;transition:color 0.15s ease;}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) li:where(.svelte-16qe0yp) span[role=button].active:where(.svelte-16qe0yp) {font-weight:700;color:var(--interactive-accent);}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) li:where(.svelte-16qe0yp) span[role=button].delete-btn:where(.svelte-16qe0yp) {padding:var(--size-2-1) 0 var(--size-2-1) var(--size-2-2);display:flex;align-items:center;justify-content:center;font-size:18px;line-height:1;color:var(--text-muted);}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) li:where(.svelte-16qe0yp) span[role=button].delete-btn:where(.svelte-16qe0yp):hover {color:var(--color-red);}.main.svelte-16qe0yp .saved-filters:where(.svelte-16qe0yp) details:where(.svelte-16qe0yp) ul:where(.svelte-16qe0yp) li:where(.svelte-16qe0yp) span[role=button].filter-text:where(.svelte-16qe0yp) {padding-left:var(--size-2-1);}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) {display:flex;flex-direction:column;gap:var(--size-4-5);padding:var(--size-4-4);padding-top:50px;}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) {display:flex;flex-direction:column;}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) label:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) label:where(.svelte-16qe0yp) {display:inline-block;margin-bottom:var(--size-2-3);font-weight:600;}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-input-container:where(.svelte-16qe0yp) input[type=search]:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-input-container:where(.svelte-16qe0yp) input[type=search]:where(.svelte-16qe0yp) {display:block;width:100%;background:var(--background-primary);padding:var(--size-4-2);box-sizing:border-box;transition:box-shadow 150ms ease;}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-input-container:where(.svelte-16qe0yp) input[type=search]:where(.svelte-16qe0yp):focus-visible,\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-input-container:where(.svelte-16qe0yp) input[type=search]:where(.svelte-16qe0yp):focus-visible {box-shadow:0 0 0 2px var(--background-modifier-border-focus);}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-input-container:where(.svelte-16qe0yp) input[type=search]:where(.svelte-16qe0yp)::-webkit-calendar-picker-indicator, .main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-input-container:where(.svelte-16qe0yp) input[type=search]:where(.svelte-16qe0yp)::-webkit-list-button,\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-input-container:where(.svelte-16qe0yp) input[type=search]:where(.svelte-16qe0yp)::-webkit-calendar-picker-indicator,\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-input-container:where(.svelte-16qe0yp) input[type=search]:where(.svelte-16qe0yp)::-webkit-list-button {display:none !important;opacity:0 !important;pointer-events:none !important;}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-actions:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-actions:where(.svelte-16qe0yp) {display:flex;gap:var(--size-4-2);margin-top:var(--size-4-2);}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-action-btn:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-action-btn:where(.svelte-16qe0yp) {padding:var(--size-2-2) var(--size-4-3);border-radius:var(--radius-s);cursor:pointer;font-size:var(--font-ui-small);transition:background 150ms ease, opacity 150ms ease;}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-action-btn.save-btn:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-action-btn.save-btn:where(.svelte-16qe0yp) {background:var(--interactive-accent);color:var(--text-on-accent);border:none;}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-action-btn.save-btn:where(.svelte-16qe0yp):hover:not(:disabled),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-action-btn.save-btn:where(.svelte-16qe0yp):hover:not(:disabled) {background:var(--interactive-accent-hover);}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-action-btn.clear-btn:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-action-btn.clear-btn:where(.svelte-16qe0yp) {background:transparent;color:var(--text-muted);border:1px solid var(--background-modifier-border);}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-action-btn.clear-btn:where(.svelte-16qe0yp):hover:not(:disabled),\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-action-btn.clear-btn:where(.svelte-16qe0yp):hover:not(:disabled) {background:var(--background-modifier-hover);}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .text-filter:where(.svelte-16qe0yp) .filter-action-btn:where(.svelte-16qe0yp):disabled,\n.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .file-filter:where(.svelte-16qe0yp) .filter-action-btn:where(.svelte-16qe0yp):disabled {opacity:0.5;cursor:not-allowed;}.main.svelte-16qe0yp .controls:where(.svelte-16qe0yp) .tag-filter:where(.svelte-16qe0yp) {display:flex;flex-direction:column;}.main.svelte-16qe0yp .columns:where(.svelte-16qe0yp) {flex:1 1 0;min-height:0;max-width:100vw;overflow-x:scroll;overflow-y:auto;padding-bottom:var(--size-4-4);}.main.svelte-16qe0yp .columns.vertical-flow:where(.svelte-16qe0yp) {overflow-x:auto;overflow-y:scroll;}"
};
function Main($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Main, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css20);
  const $collapsedColumnsStore = () => store_get(collapsedColumnsStore, "$collapsedColumnsStore", $$stores);
  const $tasksStore = () => store_get(tasksStore(), "$tasksStore", $$stores);
  const $settingsStore = () => store_get(settingsStore(), "$settingsStore", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const tags = mutable_source();
  const availableFiles = mutable_source();
  const selectedTagsSet = mutable_source();
  const savedFilters = mutable_source();
  const savedGroupings = mutable_source();
  const savedTagGroupings = mutable_source();
  const contentFilters = mutable_source();
  const tagFilters = mutable_source();
  const fileFilters = mutable_source();
  const contentFilterExists = mutable_source();
  const tagFilterExists = mutable_source();
  const fileFilterExists = mutable_source();
  const filteredByText = mutable_source();
  const filteredByTag = mutable_source();
  const filteredByFile = mutable_source();
  const tasksByColumn = mutable_source();
  const totalTaskCount = mutable_source();
  const filteredTaskCount = mutable_source();
  const isFiltered = mutable_source();
  const showFilepath = mutable_source();
  const consolidateTags = mutable_source();
  const uncategorizedVisibility = mutable_source();
  const doneVisibility = mutable_source();
  const filtersSidebarExpanded = mutable_source();
  const filtersSidebarWidth = mutable_source();
  const columnWidth = mutable_source();
  const flowDirection = mutable_source();
  const uncategorizedColumnName = mutable_source();
  const doneColumnName = mutable_source();
  const propertyDisplay = mutable_source();
  const treatNestedTasksAsSubtasks = mutable_source();
  const targetFileIsDefault = mutable_source();
  const showUncategorizedColumn = mutable_source();
  const showDoneColumn = mutable_source();
  const orderedColumns = mutable_source();
  const isVerticalFlow = mutable_source();
  const activeMatrix = mutable_source();
  const activeSchema = mutable_source();
  const propertySchemaOption = mutable_source();
  const availableSortKeys = mutable_source();
  const availableGroupKeys = mutable_source();
  const orderMode = mutable_source();
  const isTaskNameSort = mutable_source();
  const isPropertySort = mutable_source();
  const isDirectionalSort = mutable_source();
  const isManualOrder = mutable_source();
  const sortSelectValue = mutable_source();
  const groupSelectValue = mutable_source();
  const isDirectionalGroup = mutable_source();
  const manualOrder = mutable_source();
  const reorderEnabled = mutable_source();
  let app = prop($$props, "app", 12);
  let tasksStore = prop($$props, "tasksStore", 12);
  let taskActions = prop($$props, "taskActions", 12);
  let openSettings = prop($$props, "openSettings", 12);
  let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
  let columnColourTableStore = prop($$props, "columnColourTableStore", 12);
  let columnMatchTagTableStore = prop($$props, "columnMatchTagTableStore", 12);
  let columnSubtitleTableStore = prop($$props, "columnSubtitleTableStore", 12);
  let settingsStore = prop($$props, "settingsStore", 12);
  let requestSave = prop($$props, "requestSave", 12);
  const collapsedColumnsStore = createCollapsedColumnsStore(settingsStore());
  function toggleColumnCollapse(col) {
    const isCurrentlyCollapsed = $collapsedColumnsStore().has(col);
    settingsStore().update((s) => {
      var _a5;
      const collapsed = (_a5 = s.collapsedColumns) != null ? _a5 : [];
      const tag2 = col;
      return {
        ...s,
        collapsedColumns: isCurrentlyCollapsed ? collapsed.filter((c) => c !== tag2) : [...collapsed, tag2]
      };
    });
    requestSave()();
  }
  let selectedTags = mutable_source([]);
  function tagsMatch(a, b) {
    if (a.length !== b.length) return false;
    const sortedA = [...a].sort();
    const sortedB = [...b].sort();
    return sortedA.every((tag2, i) => tag2 === sortedB[i]);
  }
  let activeContentFilterId = mutable_source();
  let activeTagFilterId = mutable_source();
  let activeFileFilterId = mutable_source();
  let activeSavedGroupingId = mutable_source();
  let rememberedSavedTagGroupingId = mutable_source();
  function getRememberedSavedTagGrouping() {
    return get(rememberedSavedTagGroupingId) ? get(savedTagGroupings).find((g) => g.id === get(rememberedSavedTagGroupingId)) : void 0;
  }
  function rememberCurrentTagGroupingIfSaved() {
    var _a5;
    if (((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) !== "tag-prefix") return;
    set(rememberedSavedTagGroupingId, get(activeSavedGroupingId));
  }
  function createTagGroupSourceFromMemory() {
    const remembered = getRememberedSavedTagGrouping();
    return remembered ? { ...remembered.source } : { kind: "tag-prefix", prefix: "" };
  }
  function saveCurrentGrouping() {
    const src = $settingsStore().groupSource;
    if (!src || src.kind !== "tag-prefix") return;
    if (get(activeSavedGroupingId)) return;
    const name = src.kind === "tag-prefix" && src.prefix ? src.prefix : src.kind === "tag-prefix" ? "Tags" : "Files";
    const newGrouping = { id: crypto.randomUUID(), name, source: { ...src } };
    store_mutate(settingsStore(), untrack($settingsStore).savedGroupings = [...get(savedGroupings), newGrouping], untrack($settingsStore));
    set(rememberedSavedTagGroupingId, newGrouping.id);
    requestSave()();
  }
  function loadSavedGrouping(id) {
    const grouping = get(savedGroupings).find((g) => g.id === id);
    if (grouping) {
      store_mutate(settingsStore(), untrack($settingsStore).groupSource = { ...grouping.source }, untrack($settingsStore));
      requestSave()();
    }
  }
  function deleteSavedGrouping(id) {
    store_mutate(settingsStore(), untrack($settingsStore).savedGroupings = get(savedGroupings).filter((g) => g.id !== id), untrack($settingsStore));
    if (get(rememberedSavedTagGroupingId) === id) {
      set(rememberedSavedTagGroupingId, void 0);
    }
    requestSave()();
  }
  function onActivateKey(e, action2) {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      action2();
    }
  }
  let deleteModalOpen = mutable_source(false);
  let filterToDelete = mutable_source(null);
  function addContentFilter() {
    const normalized = get(filterText).trim();
    const existingFilterIndex = get(savedFilters).findIndex((f) => {
      var _a5;
      return ((_a5 = f.content) == null ? void 0 : _a5.text) === normalized;
    });
    if (existingFilterIndex >= 0) {
      return;
    }
    const newFilter = { id: crypto.randomUUID(), content: { text: normalized } };
    store_mutate(settingsStore(), untrack($settingsStore).savedFilters = [...get(savedFilters), newFilter], untrack($settingsStore));
    requestSave()();
  }
  function loadContentFilter(filterId, text2) {
    if (get(activeContentFilterId) === filterId) {
      clearContentFilter();
    } else {
      set(filterText, text2);
      set(activeContentFilterId, filterId);
    }
  }
  function clearContentFilter() {
    set(filterText, "");
    set(activeContentFilterId, void 0);
  }
  function clearFileFilter() {
    set(fileFilter, "");
    set(activeFileFilterId, void 0);
  }
  function addFileFilter() {
    const normalized = get(fileFilter).trim();
    if (!normalized) return;
    const existingFilterIndex = get(savedFilters).findIndex((f) => {
      var _a5;
      return ((_a5 = f.file) == null ? void 0 : _a5.filepaths[0]) === normalized;
    });
    if (existingFilterIndex >= 0) {
      return;
    }
    const newFilter = { id: crypto.randomUUID(), file: { filepaths: [normalized] } };
    store_mutate(settingsStore(), untrack($settingsStore).savedFilters = [...get(savedFilters), newFilter], untrack($settingsStore));
    requestSave()();
  }
  function loadFileFilter(filterId, filepath) {
    if (get(activeFileFilterId) === filterId) {
      clearFileFilter();
    } else {
      set(fileFilter, filepath);
      set(activeFileFilterId, filterId);
    }
  }
  function addTagFilter() {
    if (get(selectedTags).length === 0 || get(tagFilterExists)) {
      return;
    }
    const newFilter = {
      id: crypto.randomUUID(),
      tag: { tags: [...get(selectedTags)].sort() }
    };
    store_mutate(settingsStore(), untrack($settingsStore).savedFilters = [...get(savedFilters), newFilter], untrack($settingsStore));
    requestSave()();
  }
  function clearTagFilter() {
    set(selectedTags, []);
    set(activeTagFilterId, void 0);
  }
  function openDeleteModal(filterId, filterText2, type) {
    set(filterToDelete, { id: filterId, text: filterText2, type });
    set(deleteModalOpen, true);
  }
  function closeDeleteModal() {
    set(deleteModalOpen, false);
    set(filterToDelete, null);
  }
  function confirmDelete() {
    if (!get(filterToDelete)) return;
    const filterId = get(filterToDelete).id;
    const filterType = get(filterToDelete).type;
    const wasActive = filterType === "content" ? get(activeContentFilterId) === filterId : filterType === "tag" ? get(activeTagFilterId) === filterId : get(activeFileFilterId) === filterId;
    store_mutate(settingsStore(), untrack($settingsStore).savedFilters = get(savedFilters).filter((f) => f.id !== filterId), untrack($settingsStore));
    if (wasActive) {
      if (filterType === "content") {
        set(activeContentFilterId, void 0);
      } else if (filterType === "tag") {
        set(activeTagFilterId, void 0);
      } else {
        set(activeFileFilterId, void 0);
      }
    }
    requestSave()();
    closeDeleteModal();
  }
  function groupByColumnTag(tasks) {
    var _a5;
    const output = { uncategorised: [], done: [] };
    for (const task of tasks) {
      if (task.done || task.column === "done") {
        output["done"] = output["done"].concat(task);
      } else if (task.column === "archived") {
      } else if (task.column) {
        output[task.column] = ((_a5 = output[task.column]) != null ? _a5 : []).concat(task);
      } else {
        output["uncategorised"] = output["uncategorised"].concat(task);
      }
    }
    return output;
  }
  let columns = mutable_source();
  let filterText = mutable_source("");
  let fileFilter = mutable_source("");
  let hydrated = mutable_source(false);
  let lastPersistedFilterStateKey = "";
  function getCurrentFilterState() {
    return {
      contentText: get(filterText),
      tagValues: get(selectedTags),
      fileText: get(fileFilter)
    };
  }
  function applyFilterState(filterState) {
    set(filterText, filterState.contentText);
    set(selectedTags, filterState.tagValues);
    set(fileFilter, filterState.fileText);
    lastPersistedFilterStateKey = serializeBoardFilterState(filterState);
    set(hydrated, true);
  }
  onMount(() => {
    const unsubscribe = settingsStore().subscribe((settings) => {
      const filterState = readBoardFilterState(settings);
      if (shouldApplyIncomingBoardFilterState(getCurrentFilterState(), filterState, lastPersistedFilterStateKey, get(hydrated))) {
        applyFilterState(filterState);
      }
    });
    return unsubscribe;
  });
  function saveFilterState() {
    if (get(hydrated)) {
      const filterState = getCurrentFilterState();
      const nextFilterStateKey = serializeBoardFilterState(filterState);
      if (nextFilterStateKey === lastPersistedFilterStateKey) {
        return;
      }
      lastPersistedFilterStateKey = nextFilterStateKey;
      settingsStore().update((settings) => writeBoardFilterState(settings, filterState));
      requestSave()();
    }
  }
  let targetTaskFile = mutable_source(null);
  const SORT_FILE_VALUE = "__file__";
  const SORT_TASK_NAME_VALUE = "__task_name__";
  const SORT_MANUAL_VALUE = "__manual__";
  function onSortChange(value) {
    if (value.startsWith("prop:")) {
      store_mutate(settingsStore(), untrack($settingsStore).columnOrderMode = "property" /* Property */, untrack($settingsStore));
      store_mutate(settingsStore(), untrack($settingsStore).sortProperty = value.slice("prop:".length), untrack($settingsStore));
    } else if (value === SORT_TASK_NAME_VALUE) {
      store_mutate(settingsStore(), untrack($settingsStore).columnOrderMode = "task-name" /* TaskName */, untrack($settingsStore));
    } else if (value === SORT_MANUAL_VALUE) {
      store_mutate(settingsStore(), untrack($settingsStore).columnOrderMode = "manual" /* Manual */, untrack($settingsStore));
    } else {
      store_mutate(settingsStore(), untrack($settingsStore).columnOrderMode = "file" /* FileOrder */, untrack($settingsStore));
    }
    requestSave()();
  }
  let pruneTimer;
  function schedulePrune() {
    if (pruneTimer) {
      clearTimeout(pruneTimer);
    }
    pruneTimer = setTimeout(
      () => {
        var _a5, _b3, _c2, _d, _e, _f;
        pruneTimer = void 0;
        const groupSource = (_a5 = $settingsStore().groupSource) != null ? _a5 : { kind: "none" };
        const groupBuckets = deriveGroupBuckets($tasksStore(), groupSource, (_b3 = $settingsStore().excludedTags) != null ? _b3 : [], (_c2 = $settingsStore().statusMarkerOrder) != null ? _c2 : "", (_d = $settingsStore().doneStatusMarkers) != null ? _d : "", (_e = $settingsStore().groupDirection) != null ? _e : "asc");
        const assignGroupId = createGroupAssigner(groupBuckets, groupSource, (_f = $settingsStore().excludedTags) != null ? _f : []);
        taskActions().pruneManualOrder(collectPresentManualOrderKeys($tasksStore(), assignGroupId));
      },
      500
    );
  }
  onDestroy(() => {
    if (pruneTimer) {
      clearTimeout(pruneTimer);
    }
  });
  function toggleSortDirection() {
    var _a5;
    store_mutate(settingsStore(), untrack($settingsStore).sortDirection = ((_a5 = $settingsStore().sortDirection) != null ? _a5 : "asc") === "asc" ? "desc" : "asc", untrack($settingsStore));
    requestSave()();
  }
  function toggleGroupDirection() {
    var _a5;
    store_mutate(settingsStore(), untrack($settingsStore).groupDirection = ((_a5 = $settingsStore().groupDirection) != null ? _a5 : "asc") === "asc" ? "desc" : "asc", untrack($settingsStore));
    requestSave()();
  }
  function toggleSidebar() {
    store_mutate(settingsStore(), untrack($settingsStore).filtersSidebarExpanded = !get(filtersSidebarExpanded), untrack($settingsStore));
    requestSave()();
  }
  let isResizing = false;
  let resizeStartX = 0;
  let resizeStartWidth = 0;
  const MIN_SIDEBAR_WIDTH = 200;
  const MAX_SIDEBAR_WIDTH = 600;
  function startResize(e) {
    e.preventDefault();
    isResizing = true;
    resizeStartX = e.clientX;
    resizeStartWidth = get(filtersSidebarWidth);
  }
  function handleMouseMove(e) {
    if (!isResizing) return;
    const delta = e.clientX - resizeStartX;
    const newWidth = Math.min(MAX_SIDEBAR_WIDTH, Math.max(MIN_SIDEBAR_WIDTH, resizeStartWidth + delta));
    store_mutate(settingsStore(), untrack($settingsStore).filtersSidebarWidth = newWidth, untrack($settingsStore));
  }
  function stopResize() {
    if (isResizing) {
      isResizing = false;
      requestSave()();
    }
  }
  async function handleOpenSettings() {
    openSettings()();
  }
  legacy_pre_effect(() => $tasksStore(), () => {
    set(tags, $tasksStore().reduce(
      (acc, curr) => {
        for (const tag2 of curr.tags) {
          acc.add(tag2);
        }
        return acc;
      },
      /* @__PURE__ */ new Set()
    ));
  });
  legacy_pre_effect(() => $tasksStore(), () => {
    set(availableFiles, [...new Set($tasksStore().map((task) => task.path))].sort((a, b) => {
      const aParts = a.split("/");
      const bParts = b.split("/");
      const minLength = Math.min(aParts.length, bParts.length);
      for (let i = 0; i < minLength; i++) {
        const aIsLast = i === aParts.length - 1;
        const bIsLast = i === bParts.length - 1;
        if (aIsLast && !bIsLast) return -1;
        if (bIsLast && !aIsLast) return 1;
        const aPart = aParts[i];
        const bPart = bParts[i];
        if (aPart === void 0 || bPart === void 0) continue;
        const comparison = aPart.localeCompare(bPart);
        if (comparison !== 0) return comparison;
      }
      return aParts.length - bParts.length;
    }));
  });
  legacy_pre_effect(() => get(selectedTags), () => {
    set(selectedTagsSet, new Set(get(selectedTags)));
  });
  legacy_pre_effect(() => $settingsStore(), () => {
    var _a5;
    set(savedFilters, (_a5 = $settingsStore().savedFilters) != null ? _a5 : []);
  });
  legacy_pre_effect(() => $settingsStore(), () => {
    var _a5;
    set(savedGroupings, (_a5 = $settingsStore().savedGroupings) != null ? _a5 : []);
  });
  legacy_pre_effect(() => get(savedGroupings), () => {
    set(savedTagGroupings, get(savedGroupings).filter((g) => g.source.kind === "tag-prefix"));
  });
  legacy_pre_effect(
    () => ($settingsStore(), get(savedTagGroupings), normalizeTagPrefix),
    () => {
      const src = $settingsStore().groupSource;
      const matching = (src == null ? void 0 : src.kind) === "tag-prefix" ? get(savedTagGroupings).find((g) => normalizeTagPrefix(g.source.prefix) === normalizeTagPrefix(src.prefix)) : void 0;
      set(activeSavedGroupingId, matching == null ? void 0 : matching.id);
    }
  );
  legacy_pre_effect(
    () => (get(rememberedSavedTagGroupingId), get(savedTagGroupings)),
    () => {
      if (get(rememberedSavedTagGroupingId) && !get(savedTagGroupings).some((g) => g.id === get(rememberedSavedTagGroupingId))) {
        set(rememberedSavedTagGroupingId, void 0);
      }
    }
  );
  legacy_pre_effect(() => (get(activeSavedGroupingId), get(savedTagGroupings)), () => {
    if (get(activeSavedGroupingId)) {
      const activeSavedTagGrouping = get(savedTagGroupings).find((g) => g.id === get(activeSavedGroupingId));
      if (activeSavedTagGrouping) {
        set(rememberedSavedTagGroupingId, activeSavedTagGrouping.id);
      }
    }
  });
  legacy_pre_effect(() => (get(filterText), get(savedFilters)), () => {
    var _a5;
    set(activeContentFilterId, get(filterText).trim() ? (_a5 = get(savedFilters).find((f) => {
      var _a6;
      return ((_a6 = f.content) == null ? void 0 : _a6.text) === get(filterText).trim();
    })) == null ? void 0 : _a5.id : void 0);
  });
  legacy_pre_effect(() => (get(selectedTags), get(savedFilters)), () => {
    if (get(selectedTags).length > 0) {
      const matchingFilter = get(savedFilters).find((f) => f.tag ? tagsMatch(get(selectedTags), f.tag.tags) : false);
      set(activeTagFilterId, matchingFilter == null ? void 0 : matchingFilter.id);
    } else {
      set(activeTagFilterId, void 0);
    }
  });
  legacy_pre_effect(() => (get(fileFilter), get(savedFilters)), () => {
    var _a5;
    set(activeFileFilterId, get(fileFilter).trim() ? (_a5 = get(savedFilters).find((f) => {
      var _a6;
      return ((_a6 = f.file) == null ? void 0 : _a6.filepaths[0]) === get(fileFilter).trim();
    })) == null ? void 0 : _a5.id : void 0);
  });
  legacy_pre_effect(() => get(savedFilters), () => {
    set(contentFilters, get(savedFilters).filter((f) => f.content !== void 0).sort((a, b) => {
      var _a5, _b3, _c2, _d;
      const textA = (_b3 = (_a5 = a.content) == null ? void 0 : _a5.text.toLowerCase()) != null ? _b3 : "";
      const textB = (_d = (_c2 = b.content) == null ? void 0 : _c2.text.toLowerCase()) != null ? _d : "";
      return textA.localeCompare(textB);
    }));
  });
  legacy_pre_effect(() => get(savedFilters), () => {
    set(tagFilters, get(savedFilters).filter((f) => f.tag !== void 0).sort((a, b) => {
      var _a5, _b3, _c2, _d;
      const tagsA = ((_b3 = (_a5 = a.tag) == null ? void 0 : _a5.tags) != null ? _b3 : []).join(", ").toLowerCase();
      const tagsB = ((_d = (_c2 = b.tag) == null ? void 0 : _c2.tags) != null ? _d : []).join(", ").toLowerCase();
      return tagsA.localeCompare(tagsB);
    }));
  });
  legacy_pre_effect(() => get(savedFilters), () => {
    set(fileFilters, get(savedFilters).filter((f) => f.file !== void 0).sort((a, b) => {
      var _a5, _b3, _c2, _d;
      const pathA = (_b3 = (_a5 = a.file) == null ? void 0 : _a5.filepaths[0]) != null ? _b3 : "";
      const pathB = (_d = (_c2 = b.file) == null ? void 0 : _c2.filepaths[0]) != null ? _d : "";
      return pathA.localeCompare(pathB);
    }));
  });
  legacy_pre_effect(() => (get(contentFilters), get(filterText)), () => {
    set(contentFilterExists, get(contentFilters).some((f) => {
      var _a5;
      return ((_a5 = f.content) == null ? void 0 : _a5.text) === get(filterText).trim();
    }));
  });
  legacy_pre_effect(() => (get(selectedTags), get(savedFilters)), () => {
    set(tagFilterExists, get(selectedTags).length > 0 && get(savedFilters).some((f) => f.tag ? tagsMatch(get(selectedTags), f.tag.tags) : false));
  });
  legacy_pre_effect(() => (get(savedFilters), get(fileFilter)), () => {
    set(fileFilterExists, get(savedFilters).some((f) => {
      var _a5;
      return ((_a5 = f.file) == null ? void 0 : _a5.filepaths[0]) === get(fileFilter).trim();
    }));
  });
  legacy_pre_effect(() => $settingsStore(), () => {
    set(columns, $settingsStore().columns.map((column) => column.id));
  });
  legacy_pre_effect(
    () => (get(hydrated), get(filterText), get(selectedTags), get(fileFilter)),
    () => {
      if (get(hydrated)) {
        get(filterText);
        get(selectedTags);
        get(fileFilter);
        saveFilterState();
      }
    }
  );
  legacy_pre_effect(() => (get(filterText), $tasksStore()), () => {
    set(filteredByText, get(filterText) ? $tasksStore().filter((task) => task.content.toLowerCase().includes(get(filterText).toLowerCase())) : $tasksStore());
  });
  legacy_pre_effect(() => (get(selectedTagsSet), get(filteredByText)), () => {
    set(filteredByTag, get(selectedTagsSet).size ? get(filteredByText).filter((task) => {
      for (const tag2 of task.tags) {
        if (get(selectedTagsSet).has(tag2)) {
          return true;
        }
      }
      return false;
    }) : get(filteredByText));
  });
  legacy_pre_effect(() => (get(fileFilter), get(filteredByTag)), () => {
    set(filteredByFile, get(fileFilter) ? get(filteredByTag).filter((task) => task.path.toLowerCase().includes(get(fileFilter).toLowerCase())) : get(filteredByTag));
  });
  legacy_pre_effect(() => get(filteredByFile), () => {
    set(tasksByColumn, groupByColumnTag(get(filteredByFile)));
  });
  legacy_pre_effect(() => (getBoardTaskCount, $tasksStore()), () => {
    set(totalTaskCount, getBoardTaskCount($tasksStore()));
  });
  legacy_pre_effect(() => (getBoardTaskCount, get(filteredByFile)), () => {
    set(filteredTaskCount, getBoardTaskCount(get(filteredByFile)));
  });
  legacy_pre_effect(() => (get(filterText), get(selectedTags), get(fileFilter)), () => {
    set(isFiltered, get(filterText).trim() !== "" || get(selectedTags).length > 0 || get(fileFilter).trim() !== "");
  });
  legacy_pre_effect(
    () => (get(showFilepath), get(consolidateTags), get(uncategorizedVisibility), VisibilityOption, get(doneVisibility), get(filtersSidebarExpanded), get(filtersSidebarWidth), get(columnWidth), get(flowDirection), FlowDirection, get(uncategorizedColumnName), get(doneColumnName), get(propertyDisplay), PropertyDisplayMode, get(treatNestedTasksAsSubtasks), $settingsStore()),
    () => {
      (($$value) => {
        set(showFilepath, fallback($$value.showFilepath, true));
        set(consolidateTags, fallback($$value.consolidateTags, false));
        set(uncategorizedVisibility, fallback($$value.uncategorizedVisibility, () => "auto" /* Auto */, true));
        set(doneVisibility, fallback($$value.doneVisibility, () => "always" /* AlwaysShow */, true));
        set(filtersSidebarExpanded, fallback($$value.filtersSidebarExpanded, true));
        set(filtersSidebarWidth, fallback($$value.filtersSidebarWidth, 280));
        set(columnWidth, fallback($$value.columnWidth, 300));
        set(flowDirection, fallback($$value.flowDirection, () => "ltr" /* LeftToRight */, true));
        set(uncategorizedColumnName, $$value.uncategorizedColumnName);
        set(doneColumnName, $$value.doneColumnName);
        set(propertyDisplay, fallback($$value.propertyDisplay, () => "none" /* None */, true));
        set(treatNestedTasksAsSubtasks, fallback($$value.treatNestedTasksAsSubtasks, false));
      })($settingsStore());
    }
  );
  legacy_pre_effect(() => ($settingsStore(), deep_read_state(taskActions())), () => {
    void $settingsStore(), set(targetTaskFile, taskActions().getTargetFile());
  });
  legacy_pre_effect(() => (get(targetTaskFile), $settingsStore()), () => {
    set(targetFileIsDefault, !!get(targetTaskFile) && !!$settingsStore().defaultTaskFile && get(targetTaskFile).path === $settingsStore().defaultTaskFile);
  });
  legacy_pre_effect(
    () => (get(uncategorizedVisibility), VisibilityOption, get(tasksByColumn)),
    () => {
      var _a5;
      set(showUncategorizedColumn, get(uncategorizedVisibility) === "always" /* AlwaysShow */ || get(uncategorizedVisibility) === "auto" /* Auto */ && ((_a5 = get(tasksByColumn)["uncategorised"]) == null ? void 0 : _a5.length) > 0);
    }
  );
  legacy_pre_effect(
    () => (get(doneVisibility), VisibilityOption, get(tasksByColumn)),
    () => {
      var _a5;
      set(showDoneColumn, get(doneVisibility) === "always" /* AlwaysShow */ || get(doneVisibility) === "auto" /* Auto */ && ((_a5 = get(tasksByColumn)["done"]) == null ? void 0 : _a5.length) > 0);
    }
  );
  legacy_pre_effect(
    () => (get(showUncategorizedColumn), get(columns), get(showDoneColumn), get(flowDirection), FlowDirection),
    () => {
      set(orderedColumns, (() => {
        const allColumns = [];
        if (get(showUncategorizedColumn)) allColumns.push("uncategorised");
        allColumns.push(...get(columns));
        if (get(showDoneColumn)) allColumns.push("done");
        const shouldReverse = get(flowDirection) === "rtl" /* RightToLeft */ || get(flowDirection) === "btt" /* BottomToTop */;
        return shouldReverse ? allColumns.reverse() : allColumns;
      })());
    }
  );
  legacy_pre_effect(() => (get(flowDirection), FlowDirection), () => {
    set(isVerticalFlow, get(flowDirection) === "ttb" /* TopToBottom */ || get(flowDirection) === "btt" /* BottomToTop */);
  });
  legacy_pre_effect(
    () => (deriveBoardMatrix, get(filteredByFile), $settingsStore(), $collapsedColumnsStore()),
    () => {
      set(activeMatrix, deriveBoardMatrix(get(filteredByFile), $settingsStore().columns, {
        ...$settingsStore(),
        collapsedColumns: Array.from($collapsedColumnsStore())
      }));
    }
  );
  legacy_pre_effect(() => (getSchemaImpl, $settingsStore(), PropertySchemaOption), () => {
    var _a5;
    set(activeSchema, getSchemaImpl((_a5 = $settingsStore().propertySchema) != null ? _a5 : "none" /* None */));
  });
  legacy_pre_effect(() => ($settingsStore(), PropertySchemaOption), () => {
    var _a5;
    set(propertySchemaOption, (_a5 = $settingsStore().propertySchema) != null ? _a5 : "none" /* None */);
  });
  legacy_pre_effect(
    () => (get(activeSchema), $settingsStore(), PropertySchemaOption, $tasksStore()),
    () => {
      set(availableSortKeys, (() => {
        const known = get(activeSchema).knownKeys().map((k) => ({ key: k.key, label: k.label }));
        if ($settingsStore().propertySchema !== "dataview" /* Dataview */) {
          return known;
        }
        const seen = new Set(known.map((k) => k.key));
        const discovered = [];
        for (const task of $tasksStore()) {
          for (const key2 of task.properties.keys()) {
            if (!seen.has(key2)) {
              seen.add(key2);
              discovered.push({ key: key2, label: key2 });
            }
          }
        }
        return [...known, ...discovered];
      })());
    }
  );
  legacy_pre_effect(() => get(availableSortKeys), () => {
    set(availableGroupKeys, get(availableSortKeys));
  });
  legacy_pre_effect(() => ($settingsStore(), ColumnOrderMode), () => {
    var _a5;
    set(orderMode, (_a5 = $settingsStore().columnOrderMode) != null ? _a5 : "file" /* FileOrder */);
  });
  legacy_pre_effect(() => (get(orderMode), ColumnOrderMode), () => {
    set(isTaskNameSort, get(orderMode) === "task-name" /* TaskName */);
  });
  legacy_pre_effect(() => (get(orderMode), ColumnOrderMode), () => {
    set(isPropertySort, get(orderMode) === "property" /* Property */);
  });
  legacy_pre_effect(() => (get(isTaskNameSort), get(isPropertySort)), () => {
    set(isDirectionalSort, get(isTaskNameSort) || get(isPropertySort));
  });
  legacy_pre_effect(() => (get(orderMode), ColumnOrderMode), () => {
    set(isManualOrder, get(orderMode) === "manual" /* Manual */);
  });
  legacy_pre_effect(
    () => (get(isManualOrder), get(isTaskNameSort), get(isPropertySort), $settingsStore()),
    () => {
      set(sortSelectValue, get(isManualOrder) ? SORT_MANUAL_VALUE : get(isTaskNameSort) ? SORT_TASK_NAME_VALUE : get(isPropertySort) && $settingsStore().sortProperty ? `prop:${$settingsStore().sortProperty}` : SORT_FILE_VALUE);
    }
  );
  legacy_pre_effect(() => $settingsStore(), () => {
    var _a5, _b3, _c2;
    set(groupSelectValue, ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "property" ? `prop:${$settingsStore().groupSource.key}` : (_c2 = (_b3 = $settingsStore().groupSource) == null ? void 0 : _b3.kind) != null ? _c2 : "none");
  });
  legacy_pre_effect(() => $settingsStore(), () => {
    var _a5, _b3;
    set(isDirectionalGroup, ((_b3 = (_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) != null ? _b3 : "none") !== "none");
  });
  legacy_pre_effect(() => $settingsStore(), () => {
    var _a5;
    set(manualOrder, (_a5 = $settingsStore().manualOrder) != null ? _a5 : {});
  });
  legacy_pre_effect(() => get(isManualOrder), () => {
    set(reorderEnabled, get(isManualOrder));
  });
  legacy_pre_effect(() => (get(isManualOrder), $tasksStore()), () => {
    if (get(isManualOrder) && $tasksStore()) {
      schedulePrune();
    }
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get app() {
      return app();
    },
    set app($$value) {
      app($$value);
      flushSync();
    },
    get tasksStore() {
      return tasksStore();
    },
    set tasksStore($$value) {
      tasksStore($$value);
      flushSync();
    },
    get taskActions() {
      return taskActions();
    },
    set taskActions($$value) {
      taskActions($$value);
      flushSync();
    },
    get openSettings() {
      return openSettings();
    },
    set openSettings($$value) {
      openSettings($$value);
      flushSync();
    },
    get columnTagTableStore() {
      return columnTagTableStore();
    },
    set columnTagTableStore($$value) {
      columnTagTableStore($$value);
      flushSync();
    },
    get columnColourTableStore() {
      return columnColourTableStore();
    },
    set columnColourTableStore($$value) {
      columnColourTableStore($$value);
      flushSync();
    },
    get columnMatchTagTableStore() {
      return columnMatchTagTableStore();
    },
    set columnMatchTagTableStore($$value) {
      columnMatchTagTableStore($$value);
      flushSync();
    },
    get columnSubtitleTableStore() {
      return columnSubtitleTableStore();
    },
    set columnSubtitleTableStore($$value) {
      columnSubtitleTableStore($$value);
      flushSync();
    },
    get settingsStore() {
      return settingsStore();
    },
    set settingsStore($$value) {
      settingsStore($$value);
      flushSync();
    },
    get requestSave() {
      return requestSave();
    },
    set requestSave($$value) {
      requestSave($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var fragment = root_117();
  event("mousemove", $window, handleMouseMove);
  event("mouseup", $window, stopResize);
  var div = first_child(fragment);
  var button = child(div);
  var span = child(button);
  var text_1 = child(span, true);
  reset(span);
  next(2);
  reset(button);
  var div_1 = sibling(button, 2);
  let classes;
  var node = child(div_1);
  {
    var consequent_2 = ($$anchor2) => {
      var aside = root_48();
      var button_1 = child(aside);
      var div_2 = sibling(button_1, 2);
      var div_3 = child(div_2);
      var div_4 = sibling(child(div_3), 2);
      var details = child(div_4);
      var ul = sibling(child(details), 2);
      each(ul, 5, () => get(contentFilters), index, ($$anchor3, filter2) => {
        var li = root20();
        var span_1 = child(li);
        var span_2 = sibling(span_1, 2);
        let classes_1;
        var text_2 = child(span_2, true);
        reset(span_2);
        reset(li);
        template_effect(() => {
          var _a5, _b3;
          set_attribute2(span_1, "aria-label", `Delete filter: ${(_a5 = (get(filter2), untrack(() => {
            var _a6;
            return (_a6 = get(filter2).content) == null ? void 0 : _a6.text;
          }))) != null ? _a5 : ""}`);
          classes_1 = set_class(span_2, 1, "filter-text svelte-16qe0yp", null, classes_1, { active: get(filter2).id === get(activeContentFilterId) });
          set_attribute2(span_2, "aria-label", `Load saved filter: ${(_b3 = (get(filter2), untrack(() => {
            var _a6;
            return (_a6 = get(filter2).content) == null ? void 0 : _a6.text;
          }))) != null ? _b3 : ""}`);
          set_attribute2(span_2, "aria-pressed", (get(filter2), get(activeContentFilterId), untrack(() => get(filter2).id === get(activeContentFilterId))));
          set_text(text_2, (get(filter2), untrack(() => {
            var _a6;
            return (_a6 = get(filter2).content) == null ? void 0 : _a6.text;
          })));
        });
        event("click", span_1, () => {
          var _a5, _b3;
          return openDeleteModal(get(filter2).id, (_b3 = (_a5 = get(filter2).content) == null ? void 0 : _a5.text) != null ? _b3 : "", "content");
        });
        event("keydown", span_1, (e) => onActivateKey(e, () => {
          var _a5, _b3;
          return openDeleteModal(get(filter2).id, (_b3 = (_a5 = get(filter2).content) == null ? void 0 : _a5.text) != null ? _b3 : "", "content");
        }));
        event("click", span_2, () => {
          var _a5, _b3;
          return loadContentFilter(get(filter2).id, (_b3 = (_a5 = get(filter2).content) == null ? void 0 : _a5.text) != null ? _b3 : "");
        });
        event("keydown", span_2, (e) => onActivateKey(e, () => {
          var _a5, _b3;
          return loadContentFilter(get(filter2).id, (_b3 = (_a5 = get(filter2).content) == null ? void 0 : _a5.text) != null ? _b3 : "");
        }));
        append($$anchor3, li);
      });
      reset(ul);
      reset(details);
      reset(div_4);
      var div_5 = sibling(div_4, 2);
      var input = child(div_5);
      remove_input_defaults(input);
      var node_1 = sibling(input, 2);
      {
        var consequent = ($$anchor3) => {
          var datalist = root_211();
          each(datalist, 5, () => get(contentFilters), index, ($$anchor4, filter2) => {
            var option = root_116();
            var text_3 = child(option, true);
            reset(option);
            var option_value = {};
            template_effect(() => {
              var _a5;
              set_text(text_3, (get(filter2), untrack(() => {
                var _a6;
                return (_a6 = get(filter2).content) == null ? void 0 : _a6.text;
              })));
              if (option_value !== (option_value = (get(filter2), untrack(() => {
                var _a6;
                return (_a6 = get(filter2).content) == null ? void 0 : _a6.text;
              })))) {
                option.value = (_a5 = option.__value = (get(filter2), untrack(() => {
                  var _a6;
                  return (_a6 = get(filter2).content) == null ? void 0 : _a6.text;
                }))) != null ? _a5 : "";
              }
            });
            append($$anchor4, option);
          });
          reset(datalist);
          append($$anchor3, datalist);
        };
        if_block(node_1, ($$render) => {
          if (get(contentFilters), untrack(() => get(contentFilters).length > 0)) $$render(consequent);
        });
      }
      reset(div_5);
      var div_6 = sibling(div_5, 2);
      var button_2 = child(div_6);
      var button_3 = sibling(button_2, 2);
      reset(div_6);
      reset(div_3);
      var div_7 = sibling(div_3, 2);
      var node_2 = child(div_7);
      {
        let $0 = derived_safe_equal(() => (get(tags), untrack(() => [...get(tags)])));
        let $1 = derived_safe_equal(() => (get(selectedTags), get(tagFilterExists), untrack(() => get(selectedTags).length === 0 || get(tagFilterExists))));
        let $2 = derived_safe_equal(() => (get(selectedTags), untrack(() => get(selectedTags).length === 0)));
        Select_tag(node_2, {
          get tags() {
            return get($0);
          },
          get savedFilters() {
            return get(tagFilters);
          },
          onLoadFilter: (filterId) => {
            if (get(activeTagFilterId) === filterId) {
              clearTagFilter();
            } else {
              set(activeTagFilterId, filterId);
            }
          },
          get addButtonDisabled() {
            return get($1);
          },
          onAddClick: addTagFilter,
          get clearButtonDisabled() {
            return get($2);
          },
          onClearClick: clearTagFilter,
          get activeFilterId() {
            return get(activeTagFilterId);
          },
          onDeleteClick: (filterId, filterText2) => openDeleteModal(filterId, filterText2, "tag"),
          get value() {
            return get(selectedTags);
          },
          set value($$value) {
            set(selectedTags, $$value);
          },
          $$legacy: true
        });
      }
      reset(div_7);
      var div_8 = sibling(div_7, 2);
      var div_9 = sibling(child(div_8), 2);
      var details_1 = child(div_9);
      var ul_1 = sibling(child(details_1), 2);
      each(ul_1, 5, () => get(fileFilters), index, ($$anchor3, filter2) => {
        var li_1 = root20();
        var span_3 = child(li_1);
        var span_4 = sibling(span_3, 2);
        let classes_2;
        var text_4 = child(span_4, true);
        reset(span_4);
        reset(li_1);
        template_effect(() => {
          var _a5, _b3;
          set_attribute2(span_3, "aria-label", `Delete filter: ${(_a5 = (get(filter2), untrack(() => {
            var _a6;
            return (_a6 = get(filter2).file) == null ? void 0 : _a6.filepaths[0];
          }))) != null ? _a5 : ""}`);
          classes_2 = set_class(span_4, 1, "filter-text svelte-16qe0yp", null, classes_2, { active: get(filter2).id === get(activeFileFilterId) });
          set_attribute2(span_4, "aria-label", `Load saved filter: ${(_b3 = (get(filter2), untrack(() => {
            var _a6;
            return (_a6 = get(filter2).file) == null ? void 0 : _a6.filepaths[0];
          }))) != null ? _b3 : ""}`);
          set_attribute2(span_4, "aria-pressed", (get(filter2), get(activeFileFilterId), untrack(() => get(filter2).id === get(activeFileFilterId))));
          set_text(text_4, (get(filter2), untrack(() => {
            var _a6;
            return (_a6 = get(filter2).file) == null ? void 0 : _a6.filepaths[0];
          })));
        });
        event("click", span_3, () => {
          var _a5, _b3;
          return openDeleteModal(get(filter2).id, (_b3 = (_a5 = get(filter2).file) == null ? void 0 : _a5.filepaths[0]) != null ? _b3 : "", "file");
        });
        event("keydown", span_3, (e) => onActivateKey(e, () => {
          var _a5, _b3;
          return openDeleteModal(get(filter2).id, (_b3 = (_a5 = get(filter2).file) == null ? void 0 : _a5.filepaths[0]) != null ? _b3 : "", "file");
        }));
        event("click", span_4, () => {
          var _a5, _b3;
          return loadFileFilter(get(filter2).id, (_b3 = (_a5 = get(filter2).file) == null ? void 0 : _a5.filepaths[0]) != null ? _b3 : "");
        });
        event("keydown", span_4, (e) => onActivateKey(e, () => {
          var _a5, _b3;
          return loadFileFilter(get(filter2).id, (_b3 = (_a5 = get(filter2).file) == null ? void 0 : _a5.filepaths[0]) != null ? _b3 : "");
        }));
        append($$anchor3, li_1);
      });
      reset(ul_1);
      reset(details_1);
      reset(div_9);
      var div_10 = sibling(div_9, 2);
      var input_1 = child(div_10);
      remove_input_defaults(input_1);
      var node_3 = sibling(input_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var datalist_1 = root_38();
          each(datalist_1, 5, () => get(availableFiles), index, ($$anchor4, filePath) => {
            var option_1 = root_116();
            var text_5 = child(option_1, true);
            reset(option_1);
            var option_1_value = {};
            template_effect(() => {
              var _a5;
              set_text(text_5, get(filePath));
              if (option_1_value !== (option_1_value = get(filePath))) {
                option_1.value = (_a5 = option_1.__value = get(filePath)) != null ? _a5 : "";
              }
            });
            append($$anchor4, option_1);
          });
          reset(datalist_1);
          append($$anchor3, datalist_1);
        };
        if_block(node_3, ($$render) => {
          if (get(availableFiles), untrack(() => get(availableFiles).length > 0)) $$render(consequent_1);
        });
      }
      reset(div_10);
      var div_11 = sibling(div_10, 2);
      var button_4 = child(div_11);
      var button_5 = sibling(button_4, 2);
      reset(div_11);
      reset(div_8);
      reset(div_2);
      reset(aside);
      template_effect(
        ($0, $1, $2, $3) => {
          set_attribute2(input, "aria-describedby", (get(contentFilters), untrack(() => get(contentFilters).length > 0 ? "content-filters" : void 0)));
          button_2.disabled = $0;
          button_3.disabled = $1;
          button_4.disabled = $2;
          button_5.disabled = $3;
        },
        [
          () => (get(filterText), get(contentFilterExists), untrack(() => get(filterText).trim() === "" || get(contentFilterExists))),
          () => (get(filterText), untrack(() => get(filterText).trim() === "")),
          () => (get(fileFilter), get(fileFilterExists), untrack(() => get(fileFilter).trim() === "" || get(fileFilterExists))),
          () => (get(fileFilter), untrack(() => get(fileFilter).trim() === ""))
        ]
      );
      event("mousedown", button_1, startResize);
      bind_value(input, () => get(filterText), ($$value) => set(filterText, $$value));
      event("click", button_2, addContentFilter);
      event("click", button_3, clearContentFilter);
      bind_value(input_1, () => get(fileFilter), ($$value) => set(fileFilter, $$value));
      event("click", button_4, addFileFilter);
      event("click", button_5, clearFileFilter);
      append($$anchor2, aside);
    };
    if_block(node, ($$render) => {
      if (get(filtersSidebarExpanded)) $$render(consequent_2);
    });
  }
  var div_12 = sibling(node, 2);
  var div_13 = child(div_12);
  var div_14 = child(div_13);
  var node_4 = child(div_14);
  {
    var consequent_4 = ($$anchor2) => {
      var div_15 = root_74();
      var div_16 = child(div_15);
      var input_2 = child(div_16);
      remove_input_defaults(input_2);
      var button_6 = sibling(input_2, 2);
      reset(div_16);
      var node_5 = sibling(div_16, 2);
      {
        var consequent_3 = ($$anchor3) => {
          var div_17 = root_65();
          var details_2 = child(div_17);
          var ul_2 = sibling(child(details_2), 2);
          each(ul_2, 5, () => get(savedTagGroupings), index, ($$anchor4, group) => {
            var li_2 = root_56();
            var span_5 = child(li_2);
            var span_6 = sibling(span_5, 2);
            let classes_3;
            var text_6 = child(span_6, true);
            reset(span_6);
            reset(li_2);
            template_effect(() => {
              classes_3 = set_class(span_6, 1, "filter-text svelte-16qe0yp", null, classes_3, { active: get(group).id === get(activeSavedGroupingId) });
              set_text(text_6, (get(group), untrack(() => get(group).name)));
            });
            event("click", span_5, () => deleteSavedGrouping(get(group).id));
            event("keydown", span_5, (e) => onActivateKey(e, () => deleteSavedGrouping(get(group).id)));
            event("click", span_6, () => loadSavedGrouping(get(group).id));
            event("keydown", span_6, (e) => onActivateKey(e, () => loadSavedGrouping(get(group).id)));
            append($$anchor4, li_2);
          });
          reset(ul_2);
          reset(details_2);
          reset(div_17);
          append($$anchor3, div_17);
        };
        if_block(node_5, ($$render) => {
          if (get(savedTagGroupings), untrack(() => get(savedTagGroupings).length > 0)) $$render(consequent_3);
        });
      }
      reset(div_15);
      template_effect(() => {
        set_value(input_2, ($settingsStore(), untrack(() => {
          var _a5;
          return (_a5 = $settingsStore().groupSource.prefix) != null ? _a5 : "";
        })));
        button_6.disabled = !!get(activeSavedGroupingId);
      });
      event("input", input_2, (e) => {
        store_mutate(settingsStore(), untrack($settingsStore).groupSource = { kind: "tag-prefix", prefix: e.currentTarget.value }, untrack($settingsStore));
        set(activeSavedGroupingId, void 0);
        requestSave()();
      });
      event("click", button_6, saveCurrentGrouping);
      append($$anchor2, div_15);
    };
    if_block(node_4, ($$render) => {
      if ($settingsStore(), untrack(() => {
        var _a5;
        return ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "tag-prefix";
      })) $$render(consequent_4);
    });
  }
  var select = sibling(node_4, 2);
  var option_2 = child(select);
  option_2.value = option_2.__value = "none";
  var option_3 = sibling(option_2);
  option_3.value = option_3.__value = "file";
  var option_4 = sibling(option_3);
  option_4.value = option_4.__value = "tag-prefix";
  var node_6 = sibling(option_4);
  {
    var consequent_5 = ($$anchor2) => {
      var optgroup = root_83();
      each(optgroup, 5, () => get(availableGroupKeys), (groupKey) => groupKey.key, ($$anchor3, groupKey) => {
        var option_5 = root_116();
        var text_7 = child(option_5);
        reset(option_5);
        var option_5_value = {};
        template_effect(() => {
          var _a5, _b3;
          set_text(text_7, `Group by: ${(_a5 = (get(groupKey), untrack(() => get(groupKey).label))) != null ? _a5 : ""}`);
          if (option_5_value !== (option_5_value = (get(groupKey), untrack(() => `prop:${get(groupKey).key}`)))) {
            option_5.value = (_b3 = option_5.__value = (get(groupKey), untrack(() => `prop:${get(groupKey).key}`))) != null ? _b3 : "";
          }
        });
        append($$anchor3, option_5);
      });
      reset(optgroup);
      append($$anchor2, optgroup);
    };
    if_block(node_6, ($$render) => {
      if (get(availableGroupKeys), untrack(() => get(availableGroupKeys).length > 0)) $$render(consequent_5);
    });
  }
  reset(select);
  var select_value;
  init_select(select);
  var node_7 = sibling(select, 2);
  {
    var consequent_6 = ($$anchor2) => {
      var button_7 = root_93();
      var node_8 = child(button_7);
      {
        let $0 = derived_safe_equal(() => ($settingsStore(), untrack(() => {
          var _a5;
          return ((_a5 = $settingsStore().groupDirection) != null ? _a5 : "asc") === "asc" ? "arrow-up-narrow-wide" : "arrow-down-wide-narrow";
        })));
        Icon(node_8, {
          get name() {
            return get($0);
          },
          size: 16
        });
      }
      reset(button_7);
      template_effect(() => set_attribute2(button_7, "title", ($settingsStore(), untrack(() => {
        var _a5;
        return ((_a5 = $settingsStore().groupDirection) != null ? _a5 : "asc") === "asc" ? "Group ascending" : "Group descending";
      }))));
      event("click", button_7, toggleGroupDirection);
      append($$anchor2, button_7);
    };
    if_block(node_7, ($$render) => {
      if (get(isDirectionalGroup)) $$render(consequent_6);
    });
  }
  var select_1 = sibling(node_7, 2);
  var option_6 = child(select_1);
  option_6.value = option_6.__value = SORT_FILE_VALUE;
  var option_7 = sibling(option_6);
  option_7.value = option_7.__value = SORT_TASK_NAME_VALUE;
  var option_8 = sibling(option_7);
  option_8.value = option_8.__value = SORT_MANUAL_VALUE;
  var optgroup_1 = sibling(option_8);
  each(optgroup_1, 5, () => get(availableSortKeys), (sortKey) => sortKey.key, ($$anchor2, sortKey) => {
    var option_9 = root_116();
    var text_8 = child(option_9);
    reset(option_9);
    var option_9_value = {};
    template_effect(() => {
      var _a5, _b3;
      set_text(text_8, `Sort: ${(_a5 = (get(sortKey), untrack(() => get(sortKey).label))) != null ? _a5 : ""}`);
      if (option_9_value !== (option_9_value = (get(sortKey), untrack(() => `prop:${get(sortKey).key}`)))) {
        option_9.value = (_b3 = option_9.__value = (get(sortKey), untrack(() => `prop:${get(sortKey).key}`))) != null ? _b3 : "";
      }
    });
    append($$anchor2, option_9);
  });
  reset(optgroup_1);
  reset(select_1);
  var select_1_value;
  init_select(select_1);
  var node_9 = sibling(select_1, 2);
  {
    var consequent_7 = ($$anchor2) => {
      var button_8 = root_103();
      var node_10 = child(button_8);
      {
        let $0 = derived_safe_equal(() => ($settingsStore(), untrack(() => {
          var _a5;
          return ((_a5 = $settingsStore().sortDirection) != null ? _a5 : "asc") === "asc" ? "arrow-up-narrow-wide" : "arrow-down-wide-narrow";
        })));
        Icon(node_10, {
          get name() {
            return get($0);
          },
          size: 16
        });
      }
      reset(button_8);
      template_effect(() => set_attribute2(button_8, "title", ($settingsStore(), untrack(() => {
        var _a5;
        return ((_a5 = $settingsStore().sortDirection) != null ? _a5 : "asc") === "asc" ? "Ascending" : "Descending";
      }))));
      event("click", button_8, toggleSortDirection);
      append($$anchor2, button_8);
    };
    if_block(node_9, ($$render) => {
      if (get(isDirectionalSort)) $$render(consequent_7);
    });
  }
  var span_7 = sibling(node_9, 2);
  var node_11 = child(span_7);
  {
    var consequent_8 = ($$anchor2) => {
      var text_9 = text();
      template_effect(() => {
        var _a5, _b3;
        return set_text(text_9, `${(_a5 = get(filteredTaskCount)) != null ? _a5 : ""} of ${(_b3 = get(totalTaskCount)) != null ? _b3 : ""} tasks`);
      });
      append($$anchor2, text_9);
    };
    var alternate = ($$anchor2) => {
      var text_10 = text();
      template_effect(() => {
        var _a5;
        return set_text(text_10, `Total: ${(_a5 = get(totalTaskCount)) != null ? _a5 : ""} tasks`);
      });
      append($$anchor2, text_10);
    };
    if_block(node_11, ($$render) => {
      if (get(isFiltered)) $$render(consequent_8);
      else $$render(alternate, -1);
    });
  }
  reset(span_7);
  var node_12 = sibling(span_7, 2);
  Icon_button(node_12, {
    icon: "lucide-settings",
    $$events: { click: handleOpenSettings }
  });
  reset(div_14);
  reset(div_13);
  var div_18 = sibling(div_13, 2);
  let classes_4;
  var node_13 = child(div_18);
  {
    var consequent_9 = ($$anchor2) => {
      {
        let $0 = derived_safe_equal(() => ($settingsStore(), untrack(() => {
          var _a5;
          return (_a5 = $settingsStore().excludedTags) != null ? _a5 : [];
        })));
        Board_matrix_horizontal($$anchor2, {
          get app() {
            return app();
          },
          get matrix() {
            return get(activeMatrix);
          },
          get taskActions() {
            return taskActions();
          },
          get columnTagTableStore() {
            return columnTagTableStore();
          },
          get columnColourTableStore() {
            return columnColourTableStore();
          },
          get columnMatchTagTableStore() {
            return columnMatchTagTableStore();
          },
          get columnSubtitleTableStore() {
            return columnSubtitleTableStore();
          },
          get showFilepath() {
            return get(showFilepath);
          },
          get consolidateTags() {
            return get(consolidateTags);
          },
          get excludedTags() {
            return get($0);
          },
          get targetTaskFile() {
            return get(targetTaskFile);
          },
          get targetFileIsDefault() {
            return get(targetFileIsDefault);
          },
          onToggleCollapse: toggleColumnCollapse,
          get uncategorizedColumnName() {
            return get(uncategorizedColumnName);
          },
          get doneColumnName() {
            return get(doneColumnName);
          },
          get columnWidth() {
            var _a5;
            return `${(_a5 = get(columnWidth)) != null ? _a5 : ""}px`;
          },
          get propertyDisplay() {
            return get(propertyDisplay);
          },
          get propertySchemaOption() {
            return get(propertySchemaOption);
          },
          get isManualOrder() {
            return get(isManualOrder);
          },
          get manualOrder() {
            return get(manualOrder);
          },
          get reorderEnabled() {
            return get(reorderEnabled);
          },
          get treatNestedTasksAsSubtasks() {
            return get(treatNestedTasksAsSubtasks);
          }
        });
      }
    };
    var alternate_1 = ($$anchor2) => {
      {
        let $0 = derived_safe_equal(() => ($settingsStore(), untrack(() => {
          var _a5;
          return (_a5 = $settingsStore().excludedTags) != null ? _a5 : [];
        })));
        Board_matrix_vertical($$anchor2, {
          get app() {
            return app();
          },
          get matrix() {
            return get(activeMatrix);
          },
          get taskActions() {
            return taskActions();
          },
          get columnTagTableStore() {
            return columnTagTableStore();
          },
          get columnColourTableStore() {
            return columnColourTableStore();
          },
          get columnMatchTagTableStore() {
            return columnMatchTagTableStore();
          },
          get columnSubtitleTableStore() {
            return columnSubtitleTableStore();
          },
          get showFilepath() {
            return get(showFilepath);
          },
          get consolidateTags() {
            return get(consolidateTags);
          },
          get excludedTags() {
            return get($0);
          },
          get targetTaskFile() {
            return get(targetTaskFile);
          },
          get targetFileIsDefault() {
            return get(targetFileIsDefault);
          },
          onToggleCollapse: toggleColumnCollapse,
          get uncategorizedColumnName() {
            return get(uncategorizedColumnName);
          },
          get doneColumnName() {
            return get(doneColumnName);
          },
          get propertyDisplay() {
            return get(propertyDisplay);
          },
          get propertySchemaOption() {
            return get(propertySchemaOption);
          },
          get isManualOrder() {
            return get(isManualOrder);
          },
          get manualOrder() {
            return get(manualOrder);
          },
          get reorderEnabled() {
            return get(reorderEnabled);
          },
          get treatNestedTasksAsSubtasks() {
            return get(treatNestedTasksAsSubtasks);
          }
        });
      }
    };
    if_block(node_13, ($$render) => {
      if (!get(isVerticalFlow)) $$render(consequent_9);
      else $$render(alternate_1, -1);
    });
  }
  reset(div_18);
  reset(div_12);
  reset(div_1);
  reset(div);
  var node_14 = sibling(div, 2);
  {
    var consequent_10 = ($$anchor2) => {
      Delete_filter_modal($$anchor2, {
        get filterText() {
          return get(filterToDelete), untrack(() => get(filterToDelete).text);
        },
        onConfirm: confirmDelete,
        onCancel: closeDeleteModal
      });
    };
    if_block(node_14, ($$render) => {
      if (get(deleteModalOpen) && get(filterToDelete)) $$render(consequent_10);
    });
  }
  template_effect(() => {
    var _a5, _b3, _c2, _d;
    set_attribute2(button, "aria-label", get(filtersSidebarExpanded) ? "Hide filters" : "Show filters");
    set_text(text_1, get(filtersSidebarExpanded) ? "\u25C2" : "\u25B8");
    classes = set_class(div_1, 1, "board-container svelte-16qe0yp", null, classes, { "sidebar-expanded": get(filtersSidebarExpanded) });
    set_style(div_1, `--sidebar-width: ${(_a5 = get(filtersSidebarWidth)) != null ? _a5 : ""}px;`);
    if (select_value !== (select_value = get(groupSelectValue))) {
      select.value = (_b3 = select.__value = get(groupSelectValue)) != null ? _b3 : "", select_option(select, get(groupSelectValue));
    }
    if (select_1_value !== (select_1_value = get(sortSelectValue))) {
      select_1.value = (_c2 = select_1.__value = get(sortSelectValue)) != null ? _c2 : "", select_option(select_1, get(sortSelectValue));
    }
    classes_4 = set_class(div_18, 1, "columns svelte-16qe0yp", null, classes_4, { "vertical-flow": get(isVerticalFlow) });
    set_style(div_18, `--column-width: ${(_d = get(columnWidth)) != null ? _d : ""}px;`);
  });
  event("click", button, toggleSidebar);
  event("change", select, (e) => {
    var _a5;
    const val = e.currentTarget.value;
    rememberCurrentTagGroupingIfSaved();
    if (val === "file") {
      store_mutate(settingsStore(), untrack($settingsStore).groupSource = { kind: "file" }, untrack($settingsStore));
    } else if (val === "tag-prefix") {
      store_mutate(
        settingsStore(),
        untrack($settingsStore).groupSource = ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "tag-prefix" ? {
          kind: "tag-prefix",
          prefix: $settingsStore().groupSource.prefix
        } : createTagGroupSourceFromMemory(),
        untrack($settingsStore)
      );
    } else if (val.startsWith("prop:")) {
      store_mutate(settingsStore(), untrack($settingsStore).groupSource = { kind: "property", key: val.slice("prop:".length) }, untrack($settingsStore));
    } else {
      store_mutate(settingsStore(), untrack($settingsStore).groupSource = { kind: "none" }, untrack($settingsStore));
    }
    requestSave()();
  });
  event("change", select_1, (e) => onSortChange(e.currentTarget.value));
  append($$anchor, fragment);
  var $$pop = pop($$exports);
  $$cleanup();
  return $$pop;
}

// src/ui/settings/settings.ts
var import_obsidian9 = require("obsidian");

// src/ui/components/select/compact_tag_select.svelte
var root21 = from_html(`<div class="compact-tag-select svelte-1j8ru35"><svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper></div>`);
var $$css21 = {
  hash: "svelte-1j8ru35",
  code: ".compact-tag-select.svelte-1j8ru35 {--compact-tag-select-reserve: 64px;--compact-tag-chip-bg: color-mix(\n  	in srgb,\n  	var(--interactive-accent) 10%,\n  	var(--background-modifier-form-field, var(--background-primary))\n  );--compact-tag-chip-border: color-mix(\n  	in srgb,\n  	var(--interactive-accent) 24%,\n  	var(--background-modifier-border)\n  );--compact-tag-chip-color: var(--text-normal);width:100%;min-width:0;display:flex;max-width:100%;}.compact-tag-select .svelte-select button > svg,\n.compact-tag-select .svelte-select .multi-item-clear > svg {cursor:pointer;}.compact-tag-select .svelte-select .multi-item {border:var(--border-width) solid var(--compact-tag-chip-border) !important;color:var(--compact-tag-chip-color);outline:none !important;box-shadow:none !important;font-size:calc(var(--font-ui-smaller) - 1px);line-height:1;min-height:20px;display:inline-flex;align-items:center;margin:0 !important;border-radius:var(--pill-radius, 8px);background-clip:padding-box;}.compact-tag-select .svelte-select .value-container.multiple {display:flex !important;flex-direction:row !important;padding:0 !important;min-height:20px;align-items:center;gap:4px;flex-wrap:wrap;overflow:hidden !important;}.compact-tag-select .svelte-select .multi-item-text {padding-right:0 !important;display:inline-flex;align-items:center;line-height:1;}.compact-tag-select .svelte-select .multi-item-clear {transform:scale(0.9);display:inline-flex;align-items:center;}.compact-tag-select .svelte-select .svelte-select-list {z-index:5;min-width:max-content;width:max-content;max-width:min(320px, 100vw - 32px);}.compact-tag-select .svelte-select .clear-select {display:none !important;}.compact-tag-select .svelte-select.focused {transition:box-shadow 150ms ease;box-shadow:none !important;}.compact-tag-select .svelte-select input:focus-visible {outline:none;}.compact-tag-select .svelte-select .item {font-weight:var(--font-normal);white-space:nowrap;}.compact-tag-select .svelte-select {font-size:var(--font-ui-smaller);width:100%;min-width:0;max-width:100%;background:var(--background-modifier-form-field, var(--background-primary));border-radius:var(--input-radius);}.compact-tag-select .svelte-select .value-container {min-height:20px;min-width:0;overflow:hidden !important;}.compact-tag-select .svelte-select input {padding-top:0 !important;padding-bottom:0 !important;padding-left:0 !important;padding-right:0 !important;margin:0 !important;line-height:1.1;min-width:2ch !important;width:auto !important;flex:1 1 var(--compact-tag-select-reserve);max-width:100%;border:0 !important;background:transparent !important;box-shadow:none !important;appearance:none !important;}.compact-tag-select .svelte-select .selectContainer {display:flex;align-items:center;padding:2px 6px !important;min-height:24px;min-width:0;width:100%;max-width:100%;box-sizing:border-box;flex-wrap:wrap;overflow:hidden !important;background:var(--background-modifier-form-field, var(--background-primary));border-radius:var(--input-radius);}.compact-tag-select .svelte-select.focused .selectContainer {padding:2px 6px !important;}"
};
function Compact_tag_select($$anchor, $$props) {
  if (new.target) return createClassComponent({ component: Compact_tag_select, ...$$anchor });
  push($$props, false);
  append_styles($$anchor, $$css21);
  const normalizedItems = mutable_source();
  const hasCustomOption = mutable_source();
  const options2 = mutable_source();
  const selectedItemsFromValue = mutable_source();
  let items = prop($$props, "items", 28, () => []);
  let value = prop($$props, "value", 28, () => []);
  let maxSelected = prop($$props, "maxSelected", 12, 1);
  let placeholder = prop($$props, "placeholder", 12, "");
  let ariaLabel = prop($$props, "ariaLabel", 12, "Tag selector");
  const dispatch = createEventDispatcher();
  let filterText = mutable_source("");
  let selectedItems = mutable_source([]);
  function normalizeSelected(selected) {
    if (!Array.isArray(selected)) {
      return [];
    }
    const parsed = selected.flatMap((entry) => {
      if (typeof entry === "object" && entry !== null && "value" in entry && typeof entry.value === "string") {
        return [entry.value.trim()];
      }
      return [];
    }).filter((entry) => entry.length > 0);
    const unique = [...new Set(parsed)];
    if (maxSelected() > 0 && unique.length > maxSelected()) {
      return unique.slice(unique.length - maxSelected());
    }
    return unique;
  }
  function handleInput(event2) {
    value(normalizeSelected(event2.detail));
    dispatch("change", value());
  }
  legacy_pre_effect(() => deep_read_state(items()), () => {
    set(normalizedItems, [...new Set(items())].map((item) => ({ label: item, value: item })));
  });
  legacy_pre_effect(() => (get(filterText), deep_read_state(items())), () => {
    set(hasCustomOption, get(filterText).trim().length > 0 && !items().some((item) => item === get(filterText).trim()));
  });
  legacy_pre_effect(
    () => (get(hasCustomOption), get(filterText), get(normalizedItems)),
    () => {
      set(options2, get(hasCustomOption) ? [
        {
          label: get(filterText).trim(),
          value: get(filterText).trim()
        },
        ...get(normalizedItems)
      ] : get(normalizedItems));
    }
  );
  legacy_pre_effect(() => deep_read_state(value()), () => {
    set(selectedItemsFromValue, value().map((item) => ({ label: item, value: item })));
  });
  legacy_pre_effect(() => (get(selectedItems), get(selectedItemsFromValue)), () => {
    const currentValues = get(selectedItems).map((item) => item.value).join(",");
    const nextValues = get(selectedItemsFromValue).map((item) => item.value).join(",");
    if (currentValues !== nextValues) {
      set(selectedItems, get(selectedItemsFromValue));
    }
  });
  legacy_pre_effect_reset();
  var $$exports = {
    get items() {
      return items();
    },
    set items($$value) {
      items($$value);
      flushSync();
    },
    get value() {
      return value();
    },
    set value($$value) {
      value($$value);
      flushSync();
    },
    get maxSelected() {
      return maxSelected();
    },
    set maxSelected($$value) {
      maxSelected($$value);
      flushSync();
    },
    get placeholder() {
      return placeholder();
    },
    set placeholder($$value) {
      placeholder($$value);
      flushSync();
    },
    get ariaLabel() {
      return ariaLabel();
    },
    set ariaLabel($$value) {
      ariaLabel($$value);
      flushSync();
    },
    $set: update_legacy_props,
    $on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
  };
  init();
  var div = root21();
  var node = child(div);
  {
    let $0 = derived_safe_equal(() => ({ "aria-label": ariaLabel() }));
    css_props(node, () => ({
      "--background": "var(--background-modifier-form-field, var(--background-primary))",
      "--border": "var(--border-width) solid var(--background-modifier-border)",
      "--border-focused": "var(--border-width) solid var(--background-modifier-border-focus)",
      "--border-hover": "var(--border-width) solid var(--background-modifier-border-hover)",
      "--border-radius": "var(--input-radius)",
      "--item-hover-bg": "var(--background-modifier-hover)",
      "--list-background": "var(--background-modifier-form-field, var(--background-primary))",
      "--list-border": "var(--border-width) solid var(--background-modifier-border)",
      "--multi-item-bg": "var(--compact-tag-chip-bg)",
      "--multi-item-clear-icon-color": "var(--compact-tag-chip-color)",
      "--multi-item-color": "var(--compact-tag-chip-color)",
      "--multi-item-height": "auto",
      "--multi-item-outline": "var(--border-width) solid var(--compact-tag-chip-border)",
      "--multi-item-padding": "2px 8px",
      "--multi-select-input-padding": "2px 8px",
      "--multi-select-input-margin": "0 6px 0 0",
      "--input-color": "var(--text-normal)",
      "--placeholder-color": "var(--text-muted)"
    }));
    Select(node.lastChild, {
      multiple: true,
      closeListOnChange: false,
      listAutoWidth: true,
      clearable: false,
      showChevron: false,
      get placeholder() {
        return placeholder();
      },
      get items() {
        return get(options2);
      },
      get value() {
        return get(selectedItems);
      },
      get inputAttributes() {
        return get($0);
      },
      get filterText() {
        return get(filterText);
      },
      set filterText($$value) {
        set(filterText, $$value);
      },
      $$events: { input: handleInput },
      $$legacy: true
    });
    reset(node);
  }
  reset(div);
  append($$anchor, div);
  return pop($$exports);
}

// src/ui/tasks/scope.ts
function normalizePath(path) {
  return path.replace(/^\//, "").replace(/\/$/, "");
}
function pathMatchesFilter(filePath, filterPath) {
  const normalized = normalizePath(filterPath);
  if (normalized === "") {
    return true;
  }
  return filePath === normalized || filePath.startsWith(`${normalized}/`);
}
function shouldIncludeFilePath(filePath, filenameFilter, excludeFilter, boardFolderPath) {
  if (filenameFilter !== null) {
    const included = filenameFilter.some(
      (folder) => pathMatchesFilter(filePath, folder)
    );
    if (!included) {
      return false;
    }
  }
  if (excludeFilter && excludeFilter.length > 0) {
    const normalizedBoard = boardFolderPath !== null && boardFolderPath !== void 0 ? normalizePath(boardFolderPath) : null;
    const isExcluded = excludeFilter.some((excludePath) => {
      if (!pathMatchesFilter(filePath, excludePath)) {
        return false;
      }
      if (normalizedBoard !== null) {
        const normalizedExclude = normalizePath(excludePath);
        const excludeCoversBoard = normalizedExclude === "" || // root exclude covers everything
        normalizedBoard === normalizedExclude || normalizedBoard.startsWith(`${normalizedExclude}/`);
        if (excludeCoversBoard) {
          const fileInBoardFolder = normalizedBoard === "" || // if board is at root, every file is inside the board folder
          filePath === normalizedBoard || filePath.startsWith(`${normalizedBoard}/`);
          if (fileInBoardFolder) {
            return false;
          }
        }
      }
      return true;
    });
    if (isExcluded) {
      return false;
    }
  }
  return true;
}

// src/ui/settings/column_reorder.ts
function moveColumnRelativeTo(columns, draggedColumnId, targetColumnId, position) {
  if (draggedColumnId === targetColumnId) {
    return columns;
  }
  const draggedIndex = columns.findIndex((column) => column.id === draggedColumnId);
  const targetIndex = columns.findIndex((column) => column.id === targetColumnId);
  if (draggedIndex < 0 || targetIndex < 0) {
    return columns;
  }
  const nextColumns = [...columns];
  const [draggedColumn] = nextColumns.splice(draggedIndex, 1);
  if (!draggedColumn) {
    return columns;
  }
  const baseTargetIndex = draggedIndex < targetIndex ? targetIndex - 1 : targetIndex;
  const adjustedTargetIndex = position === "after" ? baseTargetIndex + 1 : baseTargetIndex;
  nextColumns.splice(adjustedTargetIndex, 0, draggedColumn);
  return nextColumns;
}

// src/ui/settings/column_validation.ts
function getColumnValidationError(columns, options2 = {}) {
  var _a5, _b3, _c2, _d;
  const errors = [];
  const seenSignatures = /* @__PURE__ */ new Map();
  const doneStatusMarkers = Array.from((_a5 = options2.doneStatusMarkers) != null ? _a5 : "");
  const ignoredStatusMarkers = Array.from((_b3 = options2.ignoredStatusMarkers) != null ? _b3 : "");
  const originalColumnsById = new Map(((_c2 = options2.originalColumns) != null ? _c2 : []).map((column) => [column.id, column]));
  for (const column of columns) {
    const label = column.label.trim();
    if (label.length === 0) {
      errors.push("Column labels cannot be empty.");
      continue;
    }
    const derivedTag = kebab(label);
    if (RESERVED_COLUMN_KEYS.has(derivedTag)) {
      errors.push(`Column name "${label}" conflicts with a built-in column.`);
    }
    if (usesTagMatching(column) && column.matchTags.length === 0) {
      errors.push(`Column "${label}" must define at least one explicit tag.`);
      continue;
    }
    if (usesTagMatching(column)) {
      for (const tag2 of column.matchTags) {
        if (!isValidTag(tag2)) {
          errors.push(`Column "${label}" has an invalid tag "${tag2}".`);
          break;
        }
      }
    }
    if (usesStatusMatching(column)) {
      const marker = column.matchStatus;
      if (marker == null || marker.length === 0) {
        errors.push(`Column "${label}" must define a status marker.`);
        continue;
      }
      if (Array.from(marker).length !== 1) {
        errors.push(`Column "${label}" status marker must be a single character.`);
        continue;
      }
      if (marker !== " " && /\s/.test(marker)) {
        errors.push(`Column "${label}" status marker cannot be whitespace.`);
        continue;
      }
      if (doneStatusMarkers.includes(marker)) {
        errors.push(`Column "${label}" uses done status marker "${getStatusColumnLabel(marker)}".`);
        continue;
      }
      if (ignoredStatusMarkers.includes(marker)) {
        errors.push(`Column "${label}" uses ignored status marker "${getStatusColumnLabel(marker)}".`);
        continue;
      }
    }
    if (usesPriorityMatching(column)) {
      const priority = (_d = column.matchPriority) == null ? void 0 : _d.trim();
      if (!priority) {
        errors.push(`Column "${label}" must define a priority.`);
        continue;
      }
      const originalColumn = originalColumnsById.get(column.id);
      const priorityRuleUnchanged = !!originalColumn && usesPriorityMatching(originalColumn) && columnRuleSignature(originalColumn) === columnRuleSignature(column);
      const columnPrioritySchema = getColumnPrioritySchema(column);
      const schemaMatches = options2.propertySchema === columnPrioritySchema;
      if (!schemaMatches) {
        if (priorityRuleUnchanged) {
          continue;
        }
        if (options2.propertySchema === "none" /* None */) {
          errors.push(`Column "${label}" uses priority matching, but task properties are disabled.`);
          continue;
        }
        errors.push(`Column "${label}" priority matching requires the ${columnPrioritySchema === "dataview" /* Dataview */ ? "Dataview" : "Tasks Plugin"} property schema.`);
        continue;
      }
      if (columnPrioritySchema === "tasks" /* TasksPlugin */ && !TASKS_PRIORITY_OPTIONS.some((option) => option.value === priority)) {
        errors.push(`Column "${label}" has an unknown priority "${priority}".`);
        continue;
      }
    }
    const signature = columnRuleSignature(column);
    const existingLabel = seenSignatures.get(signature);
    if (existingLabel) {
      const criterion = usesStatusMatching(column) ? "status marker" : usesPriorityMatching(column) ? `priority "${getPriorityColumnLabel(normalizePriorityMatchValue(column.matchPriority, getColumnPrioritySchema(column)))}"` : "tag";
      errors.push(`Columns "${existingLabel}" and "${label}" match the same ${criterion}.`);
    } else {
      seenSignatures.set(signature, label);
    }
    if (usesTagMatching(column) && column.matchTags.length === 1) {
      const nameEquivalent = `name:${kebab(column.matchTags[0])}`;
      const nameCollision = seenSignatures.get(nameEquivalent);
      if (nameCollision) {
        errors.push(`Columns "${nameCollision}" and "${label}" match the same tag.`);
      }
    }
    if (column.matchMode === "name") {
      const tagsEquivalent = `tags:${derivedTag}`;
      const tagsCollision = seenSignatures.get(tagsEquivalent);
      if (tagsCollision) {
        errors.push(`Columns "${tagsCollision}" and "${label}" match the same tag.`);
      }
    }
  }
  return errors.length > 0 ? errors[0] : null;
}

// src/ui/settings/suggest.ts
var import_obsidian8 = require("obsidian");
var FolderSuggest = class extends import_obsidian8.AbstractInputSuggest {
  constructor(app, inputEl, onSelectCallback) {
    super(app, inputEl);
    this.inputEl = inputEl;
    this.onSelectCallback = onSelectCallback;
  }
  getSuggestions(query) {
    const folders = this.app.vault.getAllLoadedFiles().filter(
      (f) => f instanceof import_obsidian8.TFolder
    );
    const lowerQuery = query.toLowerCase();
    return folders.filter(
      (folder) => folder.path.toLowerCase().includes(lowerQuery) && folder.path !== "/"
    );
  }
  renderSuggestion(folder, el) {
    el.setText(folder.path);
  }
  selectSuggestion(folder, evt) {
    this.setValue(folder.path);
    this.inputEl.dispatchEvent(new Event("input"));
    if (this.onSelectCallback) {
      this.onSelectCallback();
    }
    this.close();
  }
};
var PathSuggest = class extends import_obsidian8.AbstractInputSuggest {
  constructor(app, inputEl, onSelectCallback) {
    super(app, inputEl);
    this.inputEl = inputEl;
    this.onSelectCallback = onSelectCallback;
  }
  getSuggestions(query) {
    const files = this.app.vault.getAllLoadedFiles();
    const lowerQuery = query.toLowerCase();
    return files.filter(
      (file) => file.path.toLowerCase().includes(lowerQuery) && file.path !== "/"
    );
  }
  renderSuggestion(file, el) {
    el.setText(file.path);
  }
  selectSuggestion(file, evt) {
    this.setValue(file.path);
    this.inputEl.dispatchEvent(new Event("input"));
    if (this.onSelectCallback) {
      this.onSelectCallback();
    }
    this.close();
  }
};
var FileSuggest = class extends import_obsidian8.AbstractInputSuggest {
  constructor(app, inputEl, onSelectCallback) {
    super(app, inputEl);
    this.inputEl = inputEl;
    this.onSelectCallback = onSelectCallback;
  }
  getSuggestions(query) {
    const files = this.app.vault.getFiles();
    const lowerQuery = query.toLowerCase();
    return files.filter(
      (file) => file.path.toLowerCase().includes(lowerQuery)
    );
  }
  renderSuggestion(file, el) {
    el.setText(file.path);
  }
  selectSuggestion(file, evt) {
    this.setValue(file.path);
    this.inputEl.dispatchEvent(new Event("input"));
    if (this.onSelectCallback) {
      this.onSelectCallback();
    }
    this.close();
  }
};
var TagSuggest = class extends import_obsidian8.AbstractInputSuggest {
  constructor(app, inputEl, onSelectCallback) {
    super(app, inputEl);
    this.inputEl = inputEl;
    this.onSelectCallback = onSelectCallback;
  }
  getSuggestions(query) {
    const tags = Object.keys(this.app.metadataCache.getTags());
    const lowerQuery = query.toLowerCase();
    return tags.map((t) => t.replace(/^#/, "")).filter((tag2) => tag2.toLowerCase().includes(lowerQuery));
  }
  renderSuggestion(tag2, el) {
    el.setText(tag2);
  }
  selectSuggestion(tag2, evt) {
    this.setValue(tag2);
    this.inputEl.dispatchEvent(new Event("input"));
    if (this.onSelectCallback) {
      this.onSelectCallback();
    }
    this.close();
  }
};

// src/ui/settings/settings.ts
var VisibilityOptionSchema = z.nativeEnum(VisibilityOption);
var ScopeOptionSchema = z.nativeEnum(ScopeOption);
var FlowDirectionSchema = z.nativeEnum(FlowDirection);
var SettingsModal = class extends import_obsidian9.Modal {
  constructor(app, settings, onSubmit, boardFolderPath) {
    super(app);
    this.settings = settings;
    this.onSubmit = onSubmit;
    this.boardFolderPath = boardFolderPath;
    this.validationError = null;
    this.saveBtn = null;
    this.columnsEditorEl = null;
    this.headerDirtyPill = null;
    this.headerValidationPill = null;
    this.availableColumnTags = [];
    this.mountedColumnControls = [];
    this.updateExistingTaskTagsByColumnId = /* @__PURE__ */ new Map();
    this.activeColumnPopover = null;
    this.draggedColumnId = null;
    this.dragPreviewTarget = null;
    this.focusTagEditorColumnId = null;
    this.originalSettings = structuredClone(settings);
    this.originalSettingsSnapshot = JSON.stringify(settings);
  }
  isDirty() {
    return JSON.stringify(this.settings) !== this.originalSettingsSnapshot;
  }
  validateColumns() {
    var _a5, _b3, _c2, _d;
    this.validationError = getColumnValidationError((_a5 = this.settings.columns) != null ? _a5 : [], {
      doneStatusMarkers: (_b3 = this.settings.doneStatusMarkers) != null ? _b3 : DEFAULT_DONE_STATUS_MARKERS,
      ignoredStatusMarkers: (_c2 = this.settings.ignoredStatusMarkers) != null ? _c2 : DEFAULT_IGNORED_STATUS_MARKERS,
      propertySchema: (_d = this.settings.propertySchema) != null ? _d : "none" /* None */,
      originalColumns: this.originalSettings.columns
    });
    this.updateValidationBanner();
  }
  touchSettings() {
    this.validateColumns();
    this.updateDirtyBanner();
  }
  getOriginalColumn(columnId) {
    return this.originalSettings.columns.find((column) => column.id === columnId);
  }
  shouldShowRetagOption(column) {
    const originalColumn = this.getOriginalColumn(column.id);
    if (!originalColumn) return false;
    return columnRuleSignature(originalColumn) !== columnRuleSignature(column);
  }
  shouldUpdateExistingTaskTags(columnId) {
    var _a5;
    return (_a5 = this.updateExistingTaskTagsByColumnId.get(columnId)) != null ? _a5 : true;
  }
  getActivePrioritySchema() {
    return this.settings.propertySchema === "tasks" /* TasksPlugin */ || this.settings.propertySchema === "dataview" /* Dataview */ ? this.settings.propertySchema : void 0;
  }
  canSelectPriorityMode(column) {
    return !!this.getActivePrioritySchema() || usesPriorityMatching(column);
  }
  canEditPriorityValue(column) {
    return usesPriorityMatching(column) && getColumnPrioritySchema(column) === this.getActivePrioritySchema();
  }
  confirmRemoveColumn(column) {
    new ConfirmColumnRemovalModal(this.app, column.label, () => {
      var _a5;
      this.settings.columns = this.settings.columns.filter((candidate) => candidate.id !== column.id);
      this.updateExistingTaskTagsByColumnId.delete(column.id);
      if (((_a5 = this.activeColumnPopover) == null ? void 0 : _a5.columnId) === column.id) {
        this.activeColumnPopover = null;
      }
      this.renderColumnsEditor();
      this.touchSettings();
    }).open();
  }
  addColumn() {
    const usedIds = new Set(this.settings.columns.map((column) => column.id));
    this.settings.columns = [
      ...this.settings.columns,
      {
        id: createColumnId("New Column", usedIds),
        label: "New Column",
        matchMode: "name",
        matchTags: []
      }
    ];
    this.renderColumnsEditor();
    this.touchSettings();
  }
  reorderColumns(draggedColumnId, targetColumnId, position) {
    const reordered = moveColumnRelativeTo(this.settings.columns, draggedColumnId, targetColumnId, position);
    if (reordered === this.settings.columns) {
      return;
    }
    this.settings.columns = reordered;
    this.renderColumnsEditor();
    this.touchSettings();
  }
  setDragPreview(columnId, position) {
    this.dragPreviewTarget = { columnId, position };
  }
  clearDragPreview() {
    this.dragPreviewTarget = null;
  }
  clearDragState(container) {
    this.draggedColumnId = null;
    this.clearDragPreview();
    if (!container) return;
    container.querySelectorAll(".column-editor-row").forEach((candidate) => {
      candidate.removeClass("is-drop-target");
      candidate.removeClass("is-drop-before");
      candidate.removeClass("is-drop-after");
      candidate.removeClass("is-dragging");
    });
  }
  async refreshAvailableColumnTags() {
    var _a5;
    const files = this.app.vault.getMarkdownFiles().filter(
      (file) => {
        var _a6;
        return shouldIncludeFilePath(
          file.path,
          this.getScopeFilter(),
          (_a6 = this.settings.excludePaths) != null ? _a6 : [],
          this.boardFolderPath
        );
      }
    );
    const tags = /* @__PURE__ */ new Set();
    const ignoredStatusMarkers = (_a5 = this.settings.ignoredStatusMarkers) != null ? _a5 : DEFAULT_IGNORED_STATUS_MARKERS;
    for (const file of files) {
      const contents = await this.app.vault.cachedRead(file);
      for (const row of contents.split("\n")) {
        if (!row || !isTrackedTaskString(row, ignoredStatusMarkers)) continue;
        for (const tag2 of getTagsFromContent(row)) {
          if (tag2 === "archived") continue;
          tags.add(tag2);
        }
      }
    }
    const nextTags = [...tags].sort((a, b) => a.localeCompare(b));
    if (JSON.stringify(nextTags) === JSON.stringify(this.availableColumnTags)) {
      return;
    }
    this.availableColumnTags = nextTags;
    if (this.columnsEditorEl) {
      this.renderColumnsEditor();
    }
  }
  renderColumnsEditor() {
    var _a5, _b3, _c2, _d;
    if (!this.columnsEditorEl) {
      return;
    }
    for (const destroy of this.mountedColumnControls) {
      destroy();
    }
    this.mountedColumnControls = [];
    this.columnsEditorEl.empty();
    const section = this.columnsEditorEl.createDiv({ cls: "column-editor-section" });
    const sectionIntro = section.createDiv({ cls: "column-editor-intro" });
    const introText = sectionIntro.createDiv({ cls: "column-editor-intro-text" });
    introText.createEl("p", {
      text: "Rename, reorder, and map board columns. Use the color and match controls to edit each column's rules.",
      cls: "setting-item-description"
    });
    const rows = section.createDiv({ cls: "column-editor-list" });
    this.renderBookendRow(rows, {
      title: "Uncategorized",
      label: (_a5 = this.settings.uncategorizedColumnName) != null ? _a5 : "",
      placeholder: "Uncategorized",
      visibility: (_b3 = this.settings.uncategorizedVisibility) != null ? _b3 : "auto" /* Auto */,
      onLabelChange: (value) => {
        this.settings.uncategorizedColumnName = value;
        this.touchSettings();
      },
      onVisibilityChange: (value) => {
        const validatedValue = VisibilityOptionSchema.safeParse(value);
        this.settings.uncategorizedVisibility = validatedValue.success ? validatedValue.data : defaultSettings.uncategorizedVisibility;
        this.touchSettings();
      }
    });
    for (const column of this.settings.columns) {
      this.renderCustomColumnRow(rows, column);
    }
    this.renderBookendRow(rows, {
      title: "Done",
      label: (_c2 = this.settings.doneColumnName) != null ? _c2 : "",
      placeholder: "Done",
      visibility: (_d = this.settings.doneVisibility) != null ? _d : "always" /* AlwaysShow */,
      onLabelChange: (value) => {
        this.settings.doneColumnName = value;
        this.touchSettings();
      },
      onVisibilityChange: (value) => {
        const validatedValue = VisibilityOptionSchema.safeParse(value);
        this.settings.doneVisibility = validatedValue.success ? validatedValue.data : defaultSettings.doneVisibility;
        this.touchSettings();
      }
    });
    const controls = section.createDiv({ cls: "column-editor-controls" });
    const addButton = controls.createEl("button", { text: "Add column" });
    addButton.addEventListener("click", () => this.addColumn());
    if (this.focusTagEditorColumnId) {
      const targetColumnId = this.focusTagEditorColumnId;
      this.focusTagEditorColumnId = null;
      window.requestAnimationFrame(() => {
        const targetInput = section.querySelector(
          `[data-column-id="${targetColumnId}"] .column-editor-field-tag input`
        );
        targetInput == null ? void 0 : targetInput.focus();
        targetInput == null ? void 0 : targetInput.click();
      });
    }
  }
  renderBookendRow(container, options2) {
    const row = container.createDiv({ cls: "column-editor-row is-bookend" });
    row.createDiv({ cls: "column-editor-handle-spacer" });
    const content = row.createDiv({ cls: "column-editor-row-content" });
    const fields = content.createDiv({ cls: "column-editor-summary" });
    const labelField = fields.createDiv({ cls: "column-editor-field column-editor-field-label" });
    const labelInput = labelField.createEl("input", {
      type: "text",
      value: options2.label,
      placeholder: options2.placeholder
    });
    labelInput.addClass("setting-input");
    labelInput.setAttribute("aria-label", `${options2.title} column label`);
    labelInput.addEventListener("input", () => {
      options2.onLabelChange(labelInput.value);
    });
    const visibilityField = fields.createDiv({ cls: "column-editor-field column-editor-field-visibility" });
    const visibilitySelect = visibilityField.createEl("select");
    visibilitySelect.addClass("dropdown");
    visibilitySelect.setAttribute("aria-label", `${options2.title} visibility`);
    visibilitySelect.createEl("option", {
      value: "always" /* AlwaysShow */,
      text: "Always show"
    });
    visibilitySelect.createEl("option", {
      value: "auto" /* Auto */,
      text: "Hide when empty"
    });
    visibilitySelect.createEl("option", {
      value: "never" /* NeverShow */,
      text: "Never show"
    });
    visibilitySelect.value = options2.visibility;
    visibilitySelect.addEventListener("change", () => {
      options2.onVisibilityChange(visibilitySelect.value);
    });
  }
  getColumnMatchSummary(column) {
    var _a5;
    if (usesStatusMatching(column)) {
      return column.matchStatus ? `Status: ${getStatusColumnLabel(column.matchStatus)}` : "Needs status";
    }
    if (usesPriorityMatching(column)) {
      return column.matchPriority ? `Priority: ${getPriorityColumnLabel(column.matchPriority)}` : "Needs priority";
    }
    if (!usesTagMatching(column)) {
      return "Matches name";
    }
    const tags = (_a5 = column.matchTags) != null ? _a5 : [];
    if (tags.length === 0) {
      return "Needs tags";
    }
    if (tags.length === 1) {
      return `#${tags[0]}`;
    }
    return `${tags.length} required tags`;
  }
  getStatusMarkerOptions() {
    var _a5, _b3;
    const values = /* @__PURE__ */ new Set([" "]);
    for (const marker of Array.from((_a5 = this.settings.statusMarkerOrder) != null ? _a5 : "")) {
      values.add(marker);
    }
    for (const marker of Array.from((_b3 = this.settings.cancelledStatusMarkers) != null ? _b3 : DEFAULT_CANCELLED_STATUS_MARKERS)) {
      values.add(marker);
    }
    return [...values].map((value) => ({
      value,
      label: value === " " ? "Unchecked" : value
    }));
  }
  mountColumnPopoverDismiss(popover, trigger) {
    const ownerDocument = popover.ownerDocument;
    const closePopover = () => {
      this.activeColumnPopover = null;
      this.renderColumnsEditor();
    };
    const handleDocumentClick = (event2) => {
      const target = event2.target;
      if (!(target instanceof Node)) return;
      if (popover.contains(target) || trigger.contains(target)) return;
      closePopover();
    };
    const handleKeyDown = (event2) => {
      if (event2.key !== "Escape") return;
      event2.preventDefault();
      closePopover();
    };
    const timeoutId = window.setTimeout(() => {
      ownerDocument.addEventListener("click", handleDocumentClick);
      ownerDocument.addEventListener("keydown", handleKeyDown);
    });
    this.mountedColumnControls.push(() => {
      window.clearTimeout(timeoutId);
      ownerDocument.removeEventListener("click", handleDocumentClick);
      ownerDocument.removeEventListener("keydown", handleKeyDown);
    });
  }
  renderCustomColumnRow(container, column) {
    var _a5, _b3, _c2, _d, _e;
    const activePopover = ((_a5 = this.activeColumnPopover) == null ? void 0 : _a5.columnId) === column.id ? this.activeColumnPopover.kind : null;
    const row = container.createDiv({
      cls: "column-editor-row"
    });
    row.dataset.columnId = column.id;
    const dragHandle = row.createEl("button", {
      text: "\u22EE\u22EE",
      cls: "column-editor-handle clickable-icon"
    });
    dragHandle.setAttribute("aria-label", `Reorder ${column.label} column`);
    dragHandle.draggable = true;
    dragHandle.addEventListener("dragstart", (event2) => {
      this.draggedColumnId = column.id;
      this.clearDragPreview();
      row.addClass("is-dragging");
      if (event2.dataTransfer) {
        event2.dataTransfer.effectAllowed = "move";
        event2.dataTransfer.setData("text/plain", column.id);
      }
    });
    dragHandle.addEventListener("dragend", () => {
      this.clearDragState(container);
    });
    row.addEventListener("dragover", (event2) => {
      if (!this.draggedColumnId || this.draggedColumnId === column.id) {
        return;
      }
      event2.preventDefault();
      const rowRect = row.getBoundingClientRect();
      const position = event2.clientY > rowRect.top + rowRect.height / 2 ? "after" : "before";
      this.setDragPreview(column.id, position);
      row.addClass("is-drop-target");
      row.classList.toggle("is-drop-before", position === "before");
      row.classList.toggle("is-drop-after", position === "after");
      if (event2.dataTransfer) {
        event2.dataTransfer.dropEffect = "move";
      }
    });
    row.addEventListener("dragleave", () => {
      var _a6;
      if (((_a6 = this.dragPreviewTarget) == null ? void 0 : _a6.columnId) === column.id) {
        this.clearDragPreview();
      }
      row.removeClass("is-drop-target");
      row.removeClass("is-drop-before");
      row.removeClass("is-drop-after");
    });
    row.addEventListener("drop", (event2) => {
      var _a6, _b4, _c3, _d2;
      event2.preventDefault();
      const position = ((_a6 = this.dragPreviewTarget) == null ? void 0 : _a6.columnId) === column.id ? this.dragPreviewTarget.position : "before";
      const draggedColumnId = (_d2 = (_c3 = this.draggedColumnId) != null ? _c3 : (_b4 = event2.dataTransfer) == null ? void 0 : _b4.getData("text/plain")) != null ? _d2 : "";
      this.clearDragState(container);
      this.reorderColumns(draggedColumnId, column.id, position);
    });
    const content = row.createDiv({ cls: "column-editor-row-content" });
    const summary = content.createDiv({ cls: "column-editor-summary" });
    const labelField = summary.createDiv({ cls: "column-editor-field column-editor-field-label" });
    const labelInput = labelField.createEl("input", { type: "text", value: column.label });
    labelInput.addClass("setting-input");
    labelInput.setAttribute("aria-label", "Column label");
    const openPopover = (kind) => {
      this.activeColumnPopover = activePopover === kind ? null : { columnId: column.id, kind };
      this.renderColumnsEditor();
    };
    const colorAnchor = summary.createDiv({ cls: "column-editor-popover-anchor column-editor-color-anchor" });
    const colorSummary = colorAnchor.createEl("button", {
      cls: "column-editor-color-swatch column-editor-summary-swatch"
    });
    colorSummary.type = "button";
    colorSummary.setAttribute("aria-haspopup", "dialog");
    colorSummary.setAttribute("aria-expanded", activePopover === "color" ? "true" : "false");
    colorSummary.setAttribute("aria-label", `Edit color for ${column.label || "column"}`);
    colorSummary.addEventListener("click", () => openPopover("color"));
    const matchAnchor = summary.createDiv({ cls: "column-editor-popover-anchor column-editor-match-anchor" });
    const matchSummary = matchAnchor.createEl("button", {
      cls: "column-editor-pill column-editor-summary-button"
    });
    matchSummary.type = "button";
    matchSummary.setText(this.getColumnMatchSummary(column));
    matchSummary.setAttribute("aria-haspopup", "dialog");
    matchSummary.setAttribute("aria-expanded", activePopover === "match" ? "true" : "false");
    matchSummary.setAttribute("aria-label", `Edit match settings for ${column.label || "column"}`);
    matchSummary.addEventListener("click", () => openPopover("match"));
    let colorSwatchButton = null;
    let colorPickerInput = null;
    let colorInput = null;
    const updateColorSwatch = () => {
      var _a6, _b4;
      const colorValue = (_a6 = column.color) == null ? void 0 : _a6.trim();
      const hasValidColor = !!colorValue && /^#[0-9a-fA-F]{6}$/.test(colorValue);
      colorSummary.toggleClass("has-color", hasValidColor);
      colorSummary.style.setProperty("--column-editor-swatch-color", hasValidColor ? colorValue : "transparent");
      colorSummary.title = hasValidColor ? colorValue : "No color";
      if (colorSwatchButton) {
        colorSwatchButton.toggleClass("has-color", hasValidColor);
        colorSwatchButton.style.setProperty("--column-editor-swatch-color", hasValidColor ? colorValue : "transparent");
      }
      if (colorPickerInput) {
        colorPickerInput.value = hasValidColor ? colorValue : "#000000";
      }
      if (colorInput) {
        colorInput.value = (_b4 = column.color) != null ? _b4 : "";
      }
    };
    if (activePopover === "color") {
      const colorPopover = colorAnchor.createDiv({
        cls: "column-editor-popover column-editor-color-popover",
        attr: { role: "dialog", "aria-label": `${column.label || "Column"} color settings` }
      });
      colorPopover.addEventListener("click", (event2) => event2.stopPropagation());
      const colorField = colorPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-color" });
      colorField.createDiv({ cls: "column-editor-inline-label", text: "Color" });
      colorSwatchButton = colorField.createEl("button", {
        cls: "column-editor-color-swatch"
      });
      colorSwatchButton.type = "button";
      colorSwatchButton.setAttribute("aria-label", `Pick color for ${column.label}`);
      colorPickerInput = colorField.createEl("input", {
        type: "color",
        value: /^#[0-9a-fA-F]{6}$/.test((_b3 = column.color) != null ? _b3 : "") ? column.color : "#000000"
      });
      colorPickerInput.addClass("column-editor-color-picker");
      colorInput = colorField.createEl("input", {
        type: "text",
        value: (_c2 = column.color) != null ? _c2 : "",
        placeholder: "#RRGGBB"
      });
      colorInput.addClass("setting-input");
      colorInput.setAttribute("aria-label", `${column.label} color`);
      colorInput.addEventListener("input", () => {
        column.color = (colorInput == null ? void 0 : colorInput.value.trim()) || void 0;
        updateColorSwatch();
        this.touchSettings();
      });
      colorSwatchButton.addEventListener("click", () => {
        colorPickerInput == null ? void 0 : colorPickerInput.click();
      });
      colorPickerInput.addEventListener("input", () => {
        if (!colorPickerInput) return;
        column.color = colorPickerInput.value;
        updateColorSwatch();
        this.touchSettings();
      });
      this.mountColumnPopoverDismiss(colorPopover, colorSummary);
    }
    updateColorSwatch();
    let updateRenameOption = () => void 0;
    if (activePopover === "match") {
      const matchPopover = matchAnchor.createDiv({
        cls: "column-editor-popover column-editor-match-popover",
        attr: { role: "dialog", "aria-label": `${column.label || "Column"} match settings` }
      });
      matchPopover.addEventListener("click", (event2) => event2.stopPropagation());
      const matchModeField = matchPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-match" });
      matchModeField.createDiv({ cls: "column-editor-inline-label", text: "Match by" });
      const matchModeSelect = matchModeField.createEl("select");
      matchModeSelect.addClass("dropdown");
      matchModeSelect.createEl("option", {
        value: "name",
        text: "Name"
      });
      matchModeSelect.createEl("option", {
        value: "tags",
        text: "Tags"
      });
      matchModeSelect.createEl("option", {
        value: "status",
        text: "Status marker"
      });
      if (this.canSelectPriorityMode(column)) {
        matchModeSelect.createEl("option", {
          value: "priority",
          text: "Priority"
        });
      }
      matchModeSelect.value = column.matchMode;
      matchModeSelect.addEventListener("change", () => {
        var _a6, _b4;
        const activePrioritySchema = this.getActivePrioritySchema();
        column.matchMode = matchModeSelect.value === "tags" || matchModeSelect.value === "status" || matchModeSelect.value === "priority" && activePrioritySchema ? matchModeSelect.value : "name";
        if (column.matchMode === "name") {
          column.matchTags = [];
          column.matchStatus = void 0;
          column.matchPriority = void 0;
          column.matchPropertySchema = void 0;
        } else if (column.matchMode === "status") {
          column.matchTags = [];
          column.matchStatus = (_a6 = column.matchStatus) != null ? _a6 : " ";
          column.matchPriority = void 0;
          column.matchPropertySchema = void 0;
        } else if (column.matchMode === "priority") {
          column.matchTags = [];
          column.matchStatus = void 0;
          column.matchPriority = (_b4 = column.matchPriority) != null ? _b4 : "medium";
          column.matchPropertySchema = activePrioritySchema;
        } else {
          column.matchStatus = void 0;
          column.matchPriority = void 0;
          column.matchPropertySchema = void 0;
          this.focusTagEditorColumnId = column.id;
        }
        this.activeColumnPopover = { columnId: column.id, kind: "match" };
        this.renderColumnsEditor();
        this.touchSettings();
      });
      if (usesTagMatching(column)) {
        const tagsField = matchPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-tag" });
        tagsField.createDiv({ cls: "column-editor-inline-label", text: "Tags" });
        const tagPicker = tagsField.createDiv({ cls: "column-editor-tag-select-host" });
        const tagSelect = new Compact_tag_select({
          target: tagPicker,
          props: {
            items: this.availableColumnTags,
            value: [...column.matchTags],
            maxSelected: 0,
            placeholder: "",
            ariaLabel: `${column.label} match tags`
          }
        });
        const onChange = tagSelect.$on("change", (event2) => {
          column.matchTags = event2.detail;
          updateRenameOption();
          this.touchSettings();
        });
        this.mountedColumnControls.push(() => {
          onChange();
          tagSelect.$destroy();
        });
      }
      if (usesStatusMatching(column)) {
        const statusField = matchPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-status" });
        statusField.createDiv({ cls: "column-editor-inline-label", text: "Status" });
        const statusSelect = statusField.createEl("select");
        statusSelect.addClass("dropdown");
        statusSelect.setAttribute("aria-label", `${column.label} known status marker`);
        const markerOptions = this.getStatusMarkerOptions();
        for (const option of markerOptions) {
          statusSelect.createEl("option", {
            value: option.value,
            text: option.label
          });
        }
        statusSelect.createEl("option", {
          value: "custom",
          text: "Custom"
        });
        const customStatusInput = statusField.createEl("input", {
          type: "text",
          value: column.matchStatus && column.matchStatus !== " " ? column.matchStatus : "",
          placeholder: "e.g., /"
        });
        customStatusInput.addClass("setting-input");
        customStatusInput.setAttribute("aria-label", `${column.label} custom status marker`);
        customStatusInput.title = "Enter one status marker, such as / or !";
        const setStatusControlValues = () => {
          var _a6;
          const status = (_a6 = column.matchStatus) != null ? _a6 : " ";
          statusSelect.value = markerOptions.some((option) => option.value === status) ? status : "custom";
          customStatusInput.value = status === " " ? "" : status;
          customStatusInput.toggleClass("is-visible", statusSelect.value === "custom");
        };
        setStatusControlValues();
        statusSelect.addEventListener("change", () => {
          if (statusSelect.value !== "custom") {
            column.matchStatus = statusSelect.value;
            setStatusControlValues();
          } else if (!column.matchStatus || column.matchStatus === " ") {
            column.matchStatus = "";
            customStatusInput.value = "";
            customStatusInput.focus();
          }
          customStatusInput.toggleClass("is-visible", statusSelect.value === "custom");
          updateRenameOption();
          this.touchSettings();
        });
        customStatusInput.addEventListener("input", () => {
          column.matchStatus = customStatusInput.value;
          statusSelect.value = markerOptions.some((option) => option.value === column.matchStatus) ? column.matchStatus : "custom";
          customStatusInput.toggleClass("is-visible", statusSelect.value === "custom");
          updateRenameOption();
          this.touchSettings();
        });
      }
      if (usesPriorityMatching(column)) {
        const priorityField = matchPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-priority" });
        priorityField.createDiv({ cls: "column-editor-inline-label", text: "Priority" });
        if (this.canEditPriorityValue(column)) {
          if (getColumnPrioritySchema(column) === "dataview" /* Dataview */) {
            const priorityInput = priorityField.createEl("input", {
              type: "text",
              value: (_d = column.matchPriority) != null ? _d : "",
              placeholder: "high"
            });
            priorityInput.addClass("column-editor-inline-input");
            priorityInput.setAttribute("aria-label", `${column.label} priority`);
            priorityInput.addEventListener("input", () => {
              column.matchPriority = priorityInput.value;
              column.matchPropertySchema = "dataview" /* Dataview */;
              updateRenameOption();
              this.touchSettings();
            });
          } else {
            const prioritySelect = priorityField.createEl("select");
            prioritySelect.addClass("dropdown");
            prioritySelect.setAttribute("aria-label", `${column.label} priority`);
            for (const option of TASKS_PRIORITY_OPTIONS) {
              prioritySelect.createEl("option", {
                value: option.value,
                text: `${option.label} ${option.emoji}`
              });
            }
            prioritySelect.value = (_e = column.matchPriority) != null ? _e : "medium";
            prioritySelect.addEventListener("change", () => {
              column.matchPriority = prioritySelect.value;
              column.matchPropertySchema = "tasks" /* TasksPlugin */;
              updateRenameOption();
              this.touchSettings();
            });
          }
        } else {
          const schemaLabel = getColumnPrioritySchema(column) === "dataview" /* Dataview */ ? "Dataview" : "Tasks Plugin";
          priorityField.createDiv({
            cls: "setting-item-description",
            text: `${schemaLabel}: ${getPriorityColumnLabel(column.matchPriority)}. Switch Property schema to ${schemaLabel} to edit this value.`
          });
        }
      }
      const renameOption = matchPopover.createDiv({ cls: "column-editor-rename-option" });
      const renameCheckbox = renameOption.createEl("input", { type: "checkbox" });
      const renameCheckboxId = `column-editor-update-${column.id}`;
      renameCheckbox.id = renameCheckboxId;
      const renameLabel = renameOption.createEl("label", {
        text: "Update existing tasks"
      });
      renameLabel.htmlFor = renameCheckboxId;
      updateRenameOption = () => {
        const show = this.shouldShowRetagOption(column);
        renameOption.style.display = show ? "flex" : "none";
        renameCheckbox.checked = this.shouldUpdateExistingTaskTags(column.id);
        renameCheckbox.setAttribute("aria-label", `Update existing tasks for ${column.label || "column"}`);
        void renameLabel;
      };
      updateRenameOption();
      renameCheckbox.addEventListener("change", () => {
        this.updateExistingTaskTagsByColumnId.set(column.id, renameCheckbox.checked);
        this.touchSettings();
      });
      this.mountColumnPopoverDismiss(matchPopover, matchSummary);
    }
    labelInput.addEventListener("input", () => {
      column.label = labelInput.value;
      updateRenameOption();
      this.touchSettings();
    });
    const removeRail = row.createDiv({ cls: "column-editor-remove-rail" });
    const removeButton = removeRail.createEl("button", { cls: "clickable-icon" });
    removeButton.type = "button";
    (0, import_obsidian9.setIcon)(removeButton, "x");
    removeButton.setAttribute("aria-label", `Remove ${column.label} column`);
    removeButton.addEventListener("click", () => {
      this.confirmRemoveColumn(column);
    });
  }
  updateValidationBanner() {
    var _a5, _b3;
    if (this.headerValidationPill) {
      this.headerValidationPill.setText((_a5 = this.validationError) != null ? _a5 : "");
      this.headerValidationPill.toggleClass("is-visible", !!this.validationError);
      this.headerValidationPill.title = (_b3 = this.validationError) != null ? _b3 : "";
    }
    if (this.saveBtn) this.saveBtn.disabled = !!this.validationError;
  }
  updateDirtyBanner() {
    if (this.headerDirtyPill) {
      const isDirty2 = this.isDirty();
      this.headerDirtyPill.setText(isDirty2 ? "Unsaved changes" : "");
      this.headerDirtyPill.toggleClass("is-visible", isDirty2);
    }
  }
  onOpen() {
    this.modalEl.addClass("task-list-kanban-settings-modal-container");
    this.contentEl.addClass("task-list-kanban-settings-modal");
    this.scrollWrapper = this.contentEl.createDiv({ cls: "settings-scroll-wrapper" });
    const header = this.scrollWrapper.createDiv({ cls: "settings-header" });
    header.createEl("h1", { text: "Settings" });
    const headerStatus = header.createDiv({ cls: "settings-header-status" });
    this.headerValidationPill = headerStatus.createDiv({ cls: "settings-status-pill settings-status-pill-validation" });
    this.headerDirtyPill = headerStatus.createDiv({ cls: "settings-status-pill settings-status-pill-dirty" });
    const settingsBody = this.scrollWrapper.createDiv({ cls: "settings-body" });
    const settingsNav = settingsBody.createDiv({ cls: "settings-nav" });
    const settingsContent = settingsBody.createDiv({ cls: "settings-content" });
    const createSection = (id, title, description) => {
      const section = settingsContent.createDiv({
        cls: "settings-section",
        attr: { id: `settings-${id}` }
      });
      const navButton = settingsNav.createEl("button", { text: title });
      navButton.type = "button";
      navButton.addEventListener("click", () => {
        section.scrollIntoView({ behavior: "smooth", block: "start" });
      });
      const sectionHeader = section.createDiv({ cls: "settings-section-header" });
      sectionHeader.createEl("h2", { text: title });
      sectionHeader.createEl("p", { text: description, cls: "setting-item-description" });
      return section.createDiv({ cls: "settings-section-body" });
    };
    const columnsSection = createSection(
      "columns",
      "Columns",
      "Board columns, column labels, matching rules, and color accents."
    );
    const boardLayoutSection = createSection(
      "board-layout",
      "Board layout",
      "Column sizing and board flow."
    );
    const taskPropertiesSection = createSection(
      "task-properties",
      "Task properties",
      "Property parsing, card property display, and task creation defaults."
    );
    const scopeSection = createSection(
      "scope",
      "Scope",
      "Choose where the board looks for tasks, then subtract paths it should ignore."
    );
    const displaySection = createSection(
      "display",
      "Display",
      "Card metadata, filepath, and tag display behavior."
    );
    const statusMarkersSection = createSection(
      "status-markers",
      "Status markers",
      "Task status markers and status-specific board behavior."
    );
    this.columnsEditorEl = columnsSection;
    this.renderColumnsEditor();
    this.validateColumns();
    void this.refreshAvailableColumnTags();
    new import_obsidian9.Setting(boardLayoutSection).setName("Column width").setDesc("Width of task cards in pixels (200-600)").addSlider((slider) => {
      var _a5;
      slider.setLimits(200, 600, 10).setValue((_a5 = this.settings.columnWidth) != null ? _a5 : 300).setDynamicTooltip().onChange((value) => {
        this.settings.columnWidth = value;
        this.updateDirtyBanner();
      });
    });
    new import_obsidian9.Setting(boardLayoutSection).setName("Flow direction").setDesc("Direction columns flow across the board").addDropdown((dropdown) => {
      var _a5;
      dropdown.addOption("ltr" /* LeftToRight */, "Left to right").addOption("rtl" /* RightToLeft */, "Right to left").addOption("ttb" /* TopToBottom */, "Top to bottom").addOption("btt" /* BottomToTop */, "Bottom to top").setValue(
        (_a5 = this.settings.flowDirection) != null ? _a5 : "ltr" /* LeftToRight */
      ).onChange((value) => {
        const validatedValue = FlowDirectionSchema.safeParse(value);
        this.settings.flowDirection = validatedValue.success ? validatedValue.data : defaultSettings.flowDirection;
        this.updateDirtyBanner();
      });
    });
    new import_obsidian9.Setting(taskPropertiesSection).setName("Property schema").setDesc("Which format to use for extracting task properties.").addDropdown((dropdown) => {
      var _a5;
      dropdown.addOption("none" /* None */, "None").addOption("tasks" /* TasksPlugin */, "Tasks Plugin").addOption("dataview" /* Dataview */, "Dataview").setValue((_a5 = this.settings.propertySchema) != null ? _a5 : "none" /* None */).onChange((value) => {
        this.settings.propertySchema = value;
        this.updateDirtyBanner();
      });
    });
    new import_obsidian9.Setting(taskPropertiesSection).setName("Show properties").setDesc(
      'How parsed property values are displayed below task text. "Pretty" shows formatted values; "Debug (JSON)" shows the raw parsed data.'
    ).addDropdown((dropdown) => {
      var _a5;
      dropdown.addOption("none" /* None */, "None").addOption("pretty" /* Pretty */, "Pretty").addOption("debug" /* Debug */, "Debug (JSON)").setValue((_a5 = this.settings.propertyDisplay) != null ? _a5 : "none" /* None */).onChange((value) => {
        this.settings.propertyDisplay = value;
        this.updateDirtyBanner();
      });
    });
    new import_obsidian9.Setting(taskPropertiesSection).setName("Treat nested tasks as subtasks").setDesc("Display nested task rows inside their root task card instead of as separate cards.").addToggle((toggle) => {
      var _a5;
      toggle.setValue((_a5 = this.settings.treatNestedTasksAsSubtasks) != null ? _a5 : false).onChange((value) => {
        this.settings.treatNestedTasksAsSubtasks = value;
        this.updateDirtyBanner();
      });
    });
    let defaultTaskFileInputEl = null;
    let defaultTaskFileErrorEl = null;
    const setDefaultTaskFileError = (message) => {
      if (!defaultTaskFileInputEl) return;
      if (message) {
        defaultTaskFileInputEl.style.outline = "2px solid var(--text-error)";
        defaultTaskFileInputEl.style.outlineOffset = "-1px";
        defaultTaskFileInputEl.title = message;
        if (defaultTaskFileErrorEl) {
          defaultTaskFileErrorEl.setText(message);
          defaultTaskFileErrorEl.style.visibility = "visible";
        }
      } else {
        defaultTaskFileInputEl.style.outline = "";
        defaultTaskFileInputEl.style.outlineOffset = "";
        defaultTaskFileInputEl.title = "";
        if (defaultTaskFileErrorEl) {
          defaultTaskFileErrorEl.setText("");
          defaultTaskFileErrorEl.style.visibility = "hidden";
        }
      }
    };
    const validateDefaultTaskFile = () => {
      var _a5, _b3, _c2;
      const value = (_a5 = this.settings.defaultTaskFile) != null ? _a5 : "";
      if (!value) {
        setDefaultTaskFileError("");
        return;
      }
      const abstractFile = this.app.vault.getAbstractFileByPath(value);
      if (!(abstractFile instanceof import_obsidian9.TFile)) {
        setDefaultTaskFileError("File not found");
        return;
      }
      const scopeFilter = this.getScopeFilter();
      if (!shouldIncludeFilePath(value, scopeFilter, (_b3 = this.settings.excludePaths) != null ? _b3 : [], this.boardFolderPath)) {
        const excludePaths = (_c2 = this.settings.excludePaths) != null ? _c2 : [];
        const isExcludedByPath = excludePaths.length > 0 && shouldIncludeFilePath(value, scopeFilter) && !shouldIncludeFilePath(value, scopeFilter, excludePaths, this.boardFolderPath);
        setDefaultTaskFileError(
          isExcludedByPath ? "File is excluded from the board's scope" : "File is outside the board's folder scope"
        );
        return;
      }
      setDefaultTaskFileError("");
    };
    const scopeContainer = scopeSection.createDiv();
    let folderListContainer;
    let folderListEl;
    const renderFolderRow = (container, folder, removable) => {
      const row = container.createDiv();
      row.style.display = "flex";
      row.style.alignItems = "center";
      row.style.justifyContent = "space-between";
      row.style.padding = "4px 8px";
      row.style.borderBottom = "1px solid var(--background-modifier-border)";
      const label = row.createSpan();
      label.setText(folder);
      label.style.flexGrow = "1";
      if (!removable) {
        const badge = row.createSpan();
        badge.setText(" (this board)");
        badge.style.color = "var(--text-muted)";
        badge.style.fontStyle = "italic";
        badge.style.fontSize = "var(--font-smallest)";
      } else {
        const abstractFolder = this.app.vault.getAbstractFileByPath(folder);
        if (!abstractFolder) {
          const warning = row.createSpan();
          warning.setText(" (not found)");
          warning.style.color = "var(--text-error)";
          warning.style.fontStyle = "italic";
          warning.style.fontSize = "var(--font-smallest)";
        }
        const removeBtn = row.createEl("button");
        removeBtn.setText("\u2715");
        removeBtn.style.marginLeft = "8px";
        removeBtn.style.cursor = "pointer";
        removeBtn.style.background = "none";
        removeBtn.style.border = "none";
        removeBtn.style.color = "var(--text-muted)";
        removeBtn.style.padding = "2px 6px";
        removeBtn.addEventListener("click", () => {
          var _a5;
          this.settings.scopeFolders = ((_a5 = this.settings.scopeFolders) != null ? _a5 : []).filter((f) => f !== folder);
          renderFolderList();
          validateDefaultTaskFile();
          this.updateDirtyBanner();
        });
      }
    };
    const renderFolderList = () => {
      var _a5;
      folderListEl.empty();
      if (this.boardFolderPath) {
        renderFolderRow(folderListEl, this.boardFolderPath, false);
      }
      const folders = ((_a5 = this.settings.scopeFolders) != null ? _a5 : []).filter(
        (f) => f !== this.boardFolderPath
      );
      for (const folder of folders) {
        renderFolderRow(folderListEl, folder, true);
      }
    };
    const updateFolderListVisibility = () => {
      folderListContainer.style.display = this.settings.scope === "selectedFolders" /* SelectedFolders */ ? "block" : "none";
    };
    new import_obsidian9.Setting(scopeContainer).setName("Included folders").setDesc("Folders the board searches for tasks. The board's own folder is always included.").addDropdown((dropdown) => {
      dropdown.addOption("folder" /* Folder */, "This folder");
      dropdown.addOption("everywhere" /* Everywhere */, "Every folder");
      dropdown.addOption(
        "selectedFolders" /* SelectedFolders */,
        "Selected folders"
      );
      dropdown.setValue(this.settings.scope);
      dropdown.onChange((value) => {
        const validatedValue = ScopeOptionSchema.safeParse(value);
        this.settings.scope = validatedValue.success ? validatedValue.data : defaultSettings.scope;
        updateFolderListVisibility();
        validateDefaultTaskFile();
        this.updateDirtyBanner();
      });
    });
    folderListContainer = scopeContainer.createDiv();
    folderListContainer.style.marginLeft = "16px";
    folderListContainer.style.marginBottom = "12px";
    const addFolderRow = folderListContainer.createDiv();
    addFolderRow.style.display = "flex";
    addFolderRow.style.gap = "8px";
    addFolderRow.style.marginBottom = "8px";
    const folderInput = addFolderRow.createEl("input", {
      type: "text",
      placeholder: "e.g., projects/active"
    });
    folderInput.style.flexGrow = "1";
    folderInput.addClass("setting-input");
    const addFolder = () => {
      var _a5;
      const raw = folderInput.value.trim().replace(/^\//, "").replace(/\/$/, "");
      if (!raw) return;
      if (raw === this.boardFolderPath) return;
      const folders = (_a5 = this.settings.scopeFolders) != null ? _a5 : [];
      if (folders.includes(raw)) return;
      this.settings.scopeFolders = [...folders, raw];
      folderInput.value = "";
      renderFolderList();
      validateDefaultTaskFile();
      this.updateDirtyBanner();
    };
    new FolderSuggest(this.app, folderInput, () => addFolder());
    const addBtn = addFolderRow.createEl("button", { text: "Add" });
    addBtn.addEventListener("click", addFolder);
    folderInput.addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        e.preventDefault();
        addFolder();
      }
    });
    folderListEl = folderListContainer.createDiv();
    renderFolderList();
    updateFolderListVisibility();
    let excludeListEl;
    const renderExcludeRow = (container, path) => {
      const row = container.createDiv();
      row.style.display = "flex";
      row.style.alignItems = "center";
      row.style.justifyContent = "space-between";
      row.style.padding = "4px 8px";
      row.style.borderBottom = "1px solid var(--background-modifier-border)";
      const label = row.createSpan();
      label.setText(path);
      label.style.flexGrow = "1";
      const abstractPath = this.app.vault.getAbstractFileByPath(path);
      if (!abstractPath) {
        const warning = row.createSpan();
        warning.setText(" (not found)");
        warning.style.color = "var(--text-error)";
        warning.style.fontStyle = "italic";
        warning.style.fontSize = "var(--font-smallest)";
      }
      const removeBtn = row.createEl("button");
      removeBtn.setText("\u2715");
      removeBtn.style.marginLeft = "8px";
      removeBtn.style.cursor = "pointer";
      removeBtn.style.background = "none";
      removeBtn.style.border = "none";
      removeBtn.style.color = "var(--text-muted)";
      removeBtn.style.padding = "2px 6px";
      removeBtn.addEventListener("click", () => {
        var _a5;
        this.settings.excludePaths = ((_a5 = this.settings.excludePaths) != null ? _a5 : []).filter((p) => p !== path);
        renderExcludeList();
        validateDefaultTaskFile();
        this.updateDirtyBanner();
      });
    };
    const renderExcludeList = () => {
      var _a5;
      excludeListEl.empty();
      const paths = (_a5 = this.settings.excludePaths) != null ? _a5 : [];
      for (const path of paths) {
        renderExcludeRow(excludeListEl, path);
      }
    };
    const excludeContainer = scopeSection.createDiv({ cls: "settings-subsection" });
    excludeContainer.style.marginBottom = "12px";
    new import_obsidian9.Setting(excludeContainer).setName("Excluded paths").setDesc(
      "Folders and files the board skips after included folders are chosen."
    );
    const excludeInputContainer = excludeContainer.createDiv();
    excludeInputContainer.style.marginLeft = "16px";
    const addExcludeRow = excludeInputContainer.createDiv();
    addExcludeRow.style.display = "flex";
    addExcludeRow.style.gap = "8px";
    addExcludeRow.style.marginBottom = "8px";
    const excludeInput = addExcludeRow.createEl("input", {
      type: "text",
      placeholder: "e.g., templates or notes/scratch.md"
    });
    excludeInput.style.flexGrow = "1";
    excludeInput.addClass("setting-input");
    const addExcludePath = () => {
      var _a5;
      const raw = excludeInput.value.trim().replace(/^\//, "").replace(/\/$/, "");
      if (!raw) return;
      if (raw === this.boardFolderPath) return;
      const paths = (_a5 = this.settings.excludePaths) != null ? _a5 : [];
      if (paths.includes(raw)) return;
      this.settings.excludePaths = [...paths, raw];
      excludeInput.value = "";
      renderExcludeList();
      validateDefaultTaskFile();
      this.updateDirtyBanner();
    };
    new PathSuggest(this.app, excludeInput, () => addExcludePath());
    const addExcludeBtn = addExcludeRow.createEl("button", { text: "Add" });
    addExcludeBtn.addEventListener("click", addExcludePath);
    excludeInput.addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        e.preventDefault();
        addExcludePath();
      }
    });
    excludeListEl = excludeInputContainer.createDiv();
    renderExcludeList();
    const excludedTagsContainer = displaySection.createDiv({ cls: "settings-subsection" });
    excludedTagsContainer.style.marginBottom = "12px";
    new import_obsidian9.Setting(excludedTagsContainer).setName("Hidden Tags").setDesc(
      "Tags to hide from display on task cards. The tasks themselves will still appear on the board."
    );
    const excludedTagsInputContainer = excludedTagsContainer.createDiv();
    excludedTagsInputContainer.style.marginLeft = "16px";
    const addExcludedTagRow = excludedTagsInputContainer.createDiv();
    addExcludedTagRow.style.display = "flex";
    addExcludedTagRow.style.gap = "8px";
    addExcludedTagRow.style.marginBottom = "8px";
    const excludedTagInput = addExcludedTagRow.createEl("input", {
      type: "text",
      placeholder: "e.g., status"
    });
    excludedTagInput.style.flexGrow = "1";
    excludedTagInput.addClass("setting-input");
    let excludedTagsListEl;
    const renderExcludedTagsList = () => {
      var _a5;
      excludedTagsListEl.empty();
      const tags = (_a5 = this.settings.excludedTags) != null ? _a5 : [];
      for (const tag2 of tags) {
        const row = excludedTagsListEl.createDiv();
        row.style.display = "flex";
        row.style.justifyContent = "space-between";
        row.style.alignItems = "center";
        row.style.padding = "4px 8px";
        row.style.borderBottom = "1px solid var(--background-modifier-border)";
        const label = row.createSpan();
        label.setText(tag2);
        label.style.fontFamily = "var(--font-monospace)";
        label.style.fontSize = "var(--font-ui-smaller)";
        const removeBtn = row.createEl("button", { text: "Remove" });
        removeBtn.style.padding = "2px 8px";
        removeBtn.style.fontSize = "var(--font-ui-smaller)";
        removeBtn.addEventListener("click", () => {
          var _a6;
          this.settings.excludedTags = ((_a6 = this.settings.excludedTags) != null ? _a6 : []).filter((t) => t !== tag2);
          renderExcludedTagsList();
          this.updateDirtyBanner();
        });
      }
    };
    const addExcludedTag = () => {
      var _a5;
      const raw = excludedTagInput.value.trim().replace(/^#/, "");
      if (!raw) return;
      const tags = (_a5 = this.settings.excludedTags) != null ? _a5 : [];
      if (tags.includes(raw)) return;
      this.settings.excludedTags = [...tags, raw];
      excludedTagInput.value = "";
      renderExcludedTagsList();
      this.updateDirtyBanner();
    };
    new TagSuggest(this.app, excludedTagInput, () => addExcludedTag());
    const addExcludedTagBtn = addExcludedTagRow.createEl("button", { text: "Add" });
    addExcludedTagBtn.addEventListener("click", addExcludedTag);
    excludedTagInput.addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        e.preventDefault();
        addExcludedTag();
      }
    });
    const excludeColumnTagsBtn = addExcludedTagRow.createEl("button", { text: "Exclude column tags" });
    excludeColumnTagsBtn.title = "Automatically add all configured column placement tags to the exclusion list";
    excludeColumnTagsBtn.addEventListener("click", () => {
      var _a5, _b3;
      const currentExcluded = new Set((_a5 = this.settings.excludedTags) != null ? _a5 : []);
      for (const col of (_b3 = this.settings.columns) != null ? _b3 : []) {
        const tags = getColumnWriteTags(col);
        for (const tag2 of tags) {
          currentExcluded.add(tag2);
        }
      }
      this.settings.excludedTags = Array.from(currentExcluded);
      renderExcludedTagsList();
      this.updateDirtyBanner();
    });
    excludedTagsListEl = excludedTagsInputContainer.createDiv();
    renderExcludedTagsList();
    const excludedTaskTagsContainer = displaySection.createDiv({ cls: "settings-subsection" });
    excludedTaskTagsContainer.style.marginBottom = "12px";
    new import_obsidian9.Setting(excludedTaskTagsContainer).setName("Excluded task tags").setDesc(
      "Tasks containing these tags will be completely excluded from the board."
    );
    const excludedTaskTagsInputContainer = excludedTaskTagsContainer.createDiv();
    excludedTaskTagsInputContainer.style.marginLeft = "16px";
    const addExcludedTaskTagRow = excludedTaskTagsInputContainer.createDiv();
    addExcludedTaskTagRow.style.display = "flex";
    addExcludedTaskTagRow.style.gap = "8px";
    addExcludedTaskTagRow.style.marginBottom = "8px";
    const excludedTaskTagInput = addExcludedTaskTagRow.createEl("input", {
      type: "text",
      placeholder: "e.g., archived"
    });
    excludedTaskTagInput.style.flexGrow = "1";
    excludedTaskTagInput.addClass("setting-input");
    let excludedTaskTagsListEl;
    const renderExcludedTaskTagsList = () => {
      var _a5;
      excludedTaskTagsListEl.empty();
      const tags = (_a5 = this.settings.excludedTaskTags) != null ? _a5 : [];
      for (const tag2 of tags) {
        const row = excludedTaskTagsListEl.createDiv();
        row.style.display = "flex";
        row.style.justifyContent = "space-between";
        row.style.alignItems = "center";
        row.style.padding = "4px 8px";
        row.style.borderBottom = "1px solid var(--background-modifier-border)";
        const label = row.createSpan();
        label.setText(tag2);
        label.style.fontFamily = "var(--font-monospace)";
        label.style.fontSize = "var(--font-ui-smaller)";
        const removeBtn = row.createEl("button", { text: "Remove" });
        removeBtn.style.padding = "2px 8px";
        removeBtn.style.fontSize = "var(--font-ui-smaller)";
        removeBtn.addEventListener("click", () => {
          var _a6;
          this.settings.excludedTaskTags = ((_a6 = this.settings.excludedTaskTags) != null ? _a6 : []).filter((t) => t !== tag2);
          renderExcludedTaskTagsList();
          this.updateDirtyBanner();
        });
      }
    };
    const addExcludedTaskTag = () => {
      var _a5;
      const raw = excludedTaskTagInput.value.trim().replace(/^#/, "");
      if (!raw) return;
      const tags = (_a5 = this.settings.excludedTaskTags) != null ? _a5 : [];
      if (tags.includes(raw)) return;
      this.settings.excludedTaskTags = [...tags, raw];
      excludedTaskTagInput.value = "";
      renderExcludedTaskTagsList();
      this.updateDirtyBanner();
    };
    new TagSuggest(this.app, excludedTaskTagInput, () => addExcludedTaskTag());
    const addExcludedTaskTagBtn = addExcludedTaskTagRow.createEl("button", { text: "Add" });
    addExcludedTaskTagBtn.addEventListener("click", addExcludedTaskTag);
    excludedTaskTagInput.addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        e.preventDefault();
        addExcludedTaskTag();
      }
    });
    excludedTaskTagsListEl = excludedTaskTagsInputContainer.createDiv();
    renderExcludedTaskTagsList();
    const defaultTaskFileSetting = new import_obsidian9.Setting(taskPropertiesSection).setName("Default task file").setDesc(
      "New tasks from 'Add new' will be created in this file by default. Use the vault-relative path (e.g., 'folder/tasks.md'). Leave empty to always show the full file picker."
    ).addText((text2) => {
      var _a5;
      defaultTaskFileInputEl = text2.inputEl;
      text2.setPlaceholder("e.g., notes/tasks.md");
      text2.setValue((_a5 = this.settings.defaultTaskFile) != null ? _a5 : "");
      text2.onChange((value) => {
        this.settings.defaultTaskFile = value;
        validateDefaultTaskFile();
        this.updateDirtyBanner();
      });
      new FileSuggest(this.app, text2.inputEl);
    });
    defaultTaskFileSetting.controlEl.style.flexDirection = "column";
    defaultTaskFileSetting.controlEl.style.alignItems = "flex-end";
    defaultTaskFileErrorEl = createEl("div", {
      cls: "setting-error-message"
    });
    defaultTaskFileErrorEl.style.color = "var(--text-error)";
    defaultTaskFileErrorEl.style.fontSize = "var(--font-smallest)";
    defaultTaskFileErrorEl.style.fontStyle = "italic";
    defaultTaskFileErrorEl.style.marginTop = "4px";
    defaultTaskFileErrorEl.style.minHeight = "1.2em";
    defaultTaskFileErrorEl.style.visibility = "hidden";
    defaultTaskFileSetting.controlEl.appendChild(defaultTaskFileErrorEl);
    validateDefaultTaskFile();
    new import_obsidian9.Setting(displaySection).setName("Show filepath").setDesc("Show the filepath on each task in Kanban?").addToggle((toggle) => {
      var _a5;
      toggle.setValue((_a5 = this.settings.showFilepath) != null ? _a5 : true);
      toggle.onChange((value) => {
        this.settings.showFilepath = value;
        this.updateDirtyBanner();
      });
    });
    new import_obsidian9.Setting(displaySection).setName("Consolidate tags").setDesc(
      "Consolidate the tags on each task in Kanban into the footer?"
    ).addToggle((toggle) => {
      var _a5;
      toggle.setValue((_a5 = this.settings.consolidateTags) != null ? _a5 : false);
      toggle.onChange((value) => {
        this.settings.consolidateTags = value;
        this.updateDirtyBanner();
      });
    });
    new import_obsidian9.Setting(statusMarkersSection).setName("Status marker order").setDesc(
      "Ascending order for status grouping and status sorting. Unchecked tasks come first unless this order includes a literal space. Unspecified markers appear afterward alphabetically, followed by done markers."
    ).addText((text2) => {
      var _a5;
      text2.setValue((_a5 = this.settings.statusMarkerOrder) != null ? _a5 : "");
      text2.onChange((value) => {
        const errors = validateStatusMarkerOrder(value);
        if (errors.length > 0) {
          text2.inputEl.style.borderColor = "var(--text-error)";
          text2.inputEl.title = `Invalid: ${errors.join(", ")}`;
        } else {
          text2.inputEl.style.borderColor = "";
          text2.inputEl.title = "Valid status marker order";
          this.settings.statusMarkerOrder = value;
          this.touchSettings();
        }
      });
    });
    new import_obsidian9.Setting(statusMarkersSection).setName("Done status markers").setDesc(
      "Characters that mark a task as done (e.g., 'xX' for [x] and [X]). Each character should be a single Unicode character without spaces."
    ).addText((text2) => {
      var _a5;
      text2.setValue((_a5 = this.settings.doneStatusMarkers) != null ? _a5 : DEFAULT_DONE_STATUS_MARKERS);
      text2.onChange((value) => {
        const errors = validateDoneStatusMarkers(value);
        if (errors.length > 0) {
          text2.inputEl.style.borderColor = "var(--text-error)";
          text2.inputEl.title = `Invalid: ${errors.join(", ")}`;
        } else {
          text2.inputEl.style.borderColor = "";
          text2.inputEl.title = "Valid done status markers";
          this.settings.doneStatusMarkers = value;
          this.touchSettings();
        }
      });
    });
    new import_obsidian9.Setting(statusMarkersSection).setName("Cancelled status markers").setDesc(
      "Characters that mark a task as cancelled (e.g., '-' for [-]). Each character should be a single Unicode character without spaces."
    ).addText((text2) => {
      var _a5;
      text2.setValue((_a5 = this.settings.cancelledStatusMarkers) != null ? _a5 : DEFAULT_CANCELLED_STATUS_MARKERS);
      text2.onChange((value) => {
        const errors = validateCancelledStatusMarkers(value);
        if (errors.length > 0) {
          text2.inputEl.style.borderColor = "var(--text-error)";
          text2.inputEl.title = `Invalid: ${errors.join(", ")}`;
        } else {
          text2.inputEl.style.borderColor = "";
          text2.inputEl.title = "Valid cancelled status markers";
          this.settings.cancelledStatusMarkers = value;
          this.touchSettings();
        }
      });
    });
    new import_obsidian9.Setting(statusMarkersSection).setName("Ignored status markers").setDesc(
      "Characters that mark tasks to be completely ignored by the kanban (e.g., '-' for [-] cancelled tasks). Leave empty to process all task-like strings. Each character should be a single Unicode character without spaces."
    ).addText((text2) => {
      var _a5;
      text2.setValue((_a5 = this.settings.ignoredStatusMarkers) != null ? _a5 : DEFAULT_IGNORED_STATUS_MARKERS);
      text2.onChange((value) => {
        const errors = validateIgnoredStatusMarkers(value);
        if (errors.length > 0) {
          text2.inputEl.style.borderColor = "var(--text-error)";
          text2.inputEl.title = `Invalid: ${errors.join(", ")}`;
        } else {
          text2.inputEl.style.borderColor = "";
          text2.inputEl.title = "Valid ignored status markers";
          this.settings.ignoredStatusMarkers = value;
          this.touchSettings();
        }
      });
    });
    const buttonBar = this.contentEl.createDiv({ cls: "settings-button-bar" });
    const cancelBtn = buttonBar.createEl("button", { text: "Cancel" });
    cancelBtn.addEventListener("click", () => {
      this.close();
    });
    this.saveBtn = buttonBar.createEl("button", { text: "Save", cls: "mod-cta" });
    this.saveBtn.addEventListener("click", async () => {
      if (this.saveBtn) {
        this.saveBtn.disabled = true;
      }
      try {
        await this.onSubmit(this.settings, {
          updateExistingTaskTagsByColumnId: Object.fromEntries(this.updateExistingTaskTagsByColumnId)
        });
        this.close();
      } finally {
        if (this.saveBtn) {
          this.saveBtn.disabled = false;
        }
      }
    });
    if (this.validationError) {
      this.saveBtn.disabled = true;
    }
  }
  onClose() {
    for (const destroy of this.mountedColumnControls) {
      destroy();
    }
    this.mountedColumnControls = [];
    this.contentEl.empty();
  }
  getScopeFilter() {
    var _a5;
    switch (this.settings.scope) {
      case "folder" /* Folder */:
        return this.boardFolderPath ? [this.boardFolderPath] : null;
      case "selectedFolders" /* SelectedFolders */: {
        const selected = (_a5 = this.settings.scopeFolders) != null ? _a5 : [];
        return this.boardFolderPath ? [this.boardFolderPath, ...selected.filter((folder) => folder !== this.boardFolderPath)] : selected;
      }
      default:
        return null;
    }
  }
};
var ConfirmColumnRemovalModal = class extends import_obsidian9.Modal {
  constructor(app, columnLabel, onConfirm) {
    super(app);
    this.columnLabel = columnLabel;
    this.onConfirm = onConfirm;
  }
  onOpen() {
    this.contentEl.addClass("task-list-kanban-confirm-modal");
    this.contentEl.createEl("h2", { text: "Remove column?" });
    this.contentEl.createEl("p", {
      text: `Remove "${this.columnLabel || "Untitled column"}" from this board's settings?`
    });
    this.contentEl.createEl("p", {
      text: "This change is not saved until you save the settings modal.",
      cls: "setting-item-description"
    });
    const actions = this.contentEl.createDiv({ cls: "confirm-modal-actions" });
    const cancelButton = actions.createEl("button", { text: "Cancel" });
    cancelButton.addEventListener("click", () => this.close());
    const removeButton = actions.createEl("button", { text: "Remove", cls: "mod-warning" });
    removeButton.addEventListener("click", () => {
      this.onConfirm();
      this.close();
    });
    window.requestAnimationFrame(() => cancelButton.focus());
  }
  onClose() {
    this.contentEl.empty();
  }
};

// src/ui/tasks/store.ts
var import_obsidian11 = require("obsidian");

// src/ui/tasks/tasks.ts
async function updateMapsFromFile({
  fileHandle,
  taskIdsByFileHandle,
  tasksByTaskId,
  metadataByTaskId,
  vault,
  columnDefinitionsStore,
  columnPlacementTagTableStore,
  consolidateTags,
  doneStatusMarkers,
  cancelledStatusMarkers,
  ignoredStatusMarkers,
  excludedTaskTags,
  propertySchema,
  treatNestedTasksAsSubtasks
}) {
  var _a5;
  try {
    const previousTaskIds = (_a5 = taskIdsByFileHandle.get(fileHandle)) != null ? _a5 : /* @__PURE__ */ new Set();
    const newTaskIds = /* @__PURE__ */ new Set();
    const contents = await vault.read(fileHandle);
    const rows = contents.split("\n");
    const columnDefinitions = get2(columnDefinitionsStore);
    const columnPlacementTagTable = get2(columnPlacementTagTableStore);
    const parseContext = {
      columnDefinitions,
      columnPlacementTagTable,
      consolidateTags,
      doneStatusMarkers,
      cancelledStatusMarkers,
      ignoredStatusMarkers,
      propertySchema
    };
    if (treatNestedTasksAsSubtasks) {
      const { nodesByRowIndex, parentByRowIndex } = buildSourceTree({
        rows,
        fileHandle,
        parseContext,
        excludedTaskTags
      });
      for (const node of nodesByRowIndex.values()) {
        if (node.kind !== "task" || node.taskVisibility !== "visible" || hasVisibleTaskAncestor(node, parentByRowIndex)) {
          continue;
        }
        const task = new Task(
          node.rawLine,
          fileHandle,
          node.rowIndex,
          parseContext,
          node.sourceChildren
        );
        newTaskIds.add(task.id);
        tasksByTaskId.set(task.id, task);
        metadataByTaskId.set(task.id, {
          rowIndex: node.rowIndex,
          fileHandle
        });
        previousTaskIds.delete(task.id);
      }
      for (const prevId of previousTaskIds) {
        tasksByTaskId.delete(prevId);
        metadataByTaskId.delete(prevId);
      }
      taskIdsByFileHandle.set(fileHandle, newTaskIds);
      return;
    }
    for (let i = 0; i < rows.length; i++) {
      const row = rows[i];
      if (!row) {
        continue;
      }
      if (isTrackedTaskString(row, ignoredStatusMarkers)) {
        const task = new Task(
          row,
          fileHandle,
          i,
          parseContext
        );
        const hasExcludedTag = Array.from(task.tags).some(
          (tag2) => excludedTaskTags.has(tag2.trim().toLowerCase())
        );
        if (!hasExcludedTag) {
          newTaskIds.add(task.id);
          tasksByTaskId.set(task.id, task);
          metadataByTaskId.set(task.id, { rowIndex: i, fileHandle });
          previousTaskIds.delete(task.id);
        }
      }
    }
    for (const prevId of previousTaskIds) {
      tasksByTaskId.delete(prevId);
      metadataByTaskId.delete(prevId);
    }
    taskIdsByFileHandle.set(fileHandle, newTaskIds);
  } catch (error) {
    console.error(`Failed to update task cache for ${fileHandle.path}`, error);
  }
}
function buildSourceTree({
  rows,
  fileHandle,
  parseContext,
  excludedTaskTags
}) {
  var _a5;
  const nodesByRowIndex = /* @__PURE__ */ new Map();
  const parentByRowIndex = /* @__PURE__ */ new Map();
  const stack2 = [];
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
    const rawLine = (_a5 = rows[rowIndex]) != null ? _a5 : "";
    if (rawLine === "") {
      stack2.length = 0;
      continue;
    }
    const node = createSourceNode({
      rawLine,
      rowIndex,
      fileHandle,
      parseContext,
      excludedTaskTags
    });
    nodesByRowIndex.set(rowIndex, node);
    while (stack2.length > 0 && !isSourceDescendant(node.indentation, stack2[stack2.length - 1].indentation)) {
      stack2.pop();
    }
    const parent = stack2[stack2.length - 1];
    if (parent) {
      parent.sourceChildren.push(node);
      parentByRowIndex.set(rowIndex, parent);
    }
    stack2.push(node);
  }
  return { nodesByRowIndex, parentByRowIndex };
}
function createSourceNode({
  rawLine,
  rowIndex,
  fileHandle,
  parseContext,
  excludedTaskTags
}) {
  const parsedTaskLine = parseSourceTaskLine(rawLine);
  if (!parsedTaskLine) {
    return createRawNode(rawLine, rowIndex);
  }
  if (!isTrackedTaskString(rawLine, parseContext.ignoredStatusMarkers)) {
    return {
      kind: "task",
      taskVisibility: "ignored",
      rowIndex,
      rawLine,
      indentation: parsedTaskLine.indentation,
      status: parsedTaskLine.status || " ",
      content: parsedTaskLine.content,
      sourceChildren: []
    };
  }
  const task = new Task(
    rawLine,
    fileHandle,
    rowIndex,
    parseContext
  );
  const hasExcludedTag = Array.from(task.tags).some(
    (tag2) => excludedTaskTags.has(tag2.trim().toLowerCase())
  );
  return {
    kind: "task",
    taskVisibility: hasExcludedTag ? "ignored" : "visible",
    rowIndex,
    rawLine,
    indentation: parsedTaskLine.indentation,
    status: parsedTaskLine.status || " ",
    content: parsedTaskLine.content,
    sourceChildren: []
  };
}
function createRawNode(rawLine, rowIndex) {
  var _a5, _b3;
  return {
    kind: "raw",
    rowIndex,
    rawLine,
    indentation: (_b3 = (_a5 = rawLine.match(/^\s*/)) == null ? void 0 : _a5[0]) != null ? _b3 : "",
    sourceChildren: []
  };
}
function isSourceDescendant(indentation, ancestorIndentation) {
  return indentation.length > ancestorIndentation.length && indentation.startsWith(ancestorIndentation);
}
function hasVisibleTaskAncestor(node, parentByRowIndex) {
  let parent = parentByRowIndex.get(node.rowIndex);
  while (parent) {
    if (parent.kind === "task" && parent.taskVisibility === "visible") {
      return true;
    }
    parent = parentByRowIndex.get(parent.rowIndex);
  }
  return false;
}

// src/ui/tasks/actions.ts
var import_obsidian10 = require("obsidian");

// src/ui/tasks/duplicate.ts
var blockLinkRegexp3 = /\s\^[a-zA-Z0-9-]+$/;
var checkboxRegexp = /^(\s*[-*+]\s)\[([^\[\]]*)\]/;
function createDuplicateLine(rawLine) {
  return rawLine.replace(blockLinkRegexp3, "").replace(checkboxRegexp, "$1[ ]");
}

// src/ui/tasks/task_creation.ts
function createTaskLine(content, placementTags, additionalTags = [], status = " ") {
  const seenTags = /* @__PURE__ */ new Set();
  const appendedTags = [];
  for (const tag2 of [...placementTags, ...additionalTags]) {
    const normalizedTag = tag2.trim().replace(/^#/, "");
    if (!normalizedTag) continue;
    const key2 = normalizedTag.toLowerCase();
    if (seenTags.has(key2)) continue;
    seenTags.add(key2);
    appendedTags.push(normalizedTag);
  }
  return `- [${status}] ${content}${appendedTags.map((tag2) => ` #${tag2}`).join("")}`;
}

// src/ui/tasks/source_line_editor.ts
async function readFileRows(vault, fileHandle) {
  return (await vault.read(fileHandle)).split("\n");
}
async function writeFileRows(vault, fileHandle, rows) {
  await vault.modify(fileHandle, rows.join("\n"));
}
async function transformSourceRow(vault, fileHandle, rowIndex, transform) {
  const rows = await readFileRows(vault, fileHandle);
  const row = rows[rowIndex];
  if (row == null) {
    return false;
  }
  const nextRow = transform(row);
  if (nextRow === row) {
    return false;
  }
  rows[rowIndex] = nextRow;
  await writeFileRows(vault, fileHandle, rows);
  return true;
}
async function updateRow(vault, fileHandle, row, newText) {
  const rows = await readFileRows(vault, fileHandle);
  const rowIndex = row != null ? row : rows.length;
  if (rows.length < rowIndex) {
    return false;
  }
  if (newText === "") {
    rows.splice(rowIndex, 1);
  } else {
    rows[rowIndex] = newText;
  }
  await writeFileRows(vault, fileHandle, rows);
  return true;
}
async function deleteRowBlocks(vault, fileHandle, blocks) {
  const rows = await readFileRows(vault, fileHandle);
  for (const block2 of [...blocks].sort((a, b) => b.rowIndex - a.rowIndex)) {
    if (block2.rowIndex < rows.length && block2.lineCount > 0) {
      rows.splice(block2.rowIndex, block2.lineCount);
    }
  }
  await writeFileRows(vault, fileHandle, rows);
}

// src/ui/tasks/actions.ts
function createTaskActions({
  tasksByTaskId,
  metadataByTaskId,
  vault,
  workspace,
  getFilenameFilter,
  getExcludeFilter,
  getBoardFolderPath,
  getPlacementTagsForColumn,
  getColumnDefinitions,
  getDefaultTaskFile,
  getLastUsedTaskFile,
  setLastUsedTaskFile,
  getPropertySchemaOption,
  getStatusMarkerOrder,
  getCurrentDate,
  getManualOrder,
  setManualOrder
}) {
  function resolveFileIfValid(filePath) {
    if (!filePath) return null;
    const abstractFile = vault.getAbstractFileByPath(filePath);
    if (!(abstractFile instanceof import_obsidian10.TFile)) return null;
    if (!shouldIncludeFilePath(filePath, getFilenameFilter(), getExcludeFilter(), getBoardFolderPath())) return null;
    return abstractFile;
  }
  function getTargetFile() {
    var _a5;
    return (_a5 = resolveFileIfValid(getDefaultTaskFile())) != null ? _a5 : resolveFileIfValid(getLastUsedTaskFile());
  }
  async function updateRowWithTask(id, updater, transformSerialized) {
    const metadata = metadataByTaskId.get(id);
    const task = tasksByTaskId.get(id);
    if (!metadata || !task) {
      return;
    }
    updater(task);
    const serialized = task.serialise();
    const newTaskString = transformSerialized ? transformSerialized(serialized) : serialized;
    await updateRow(
      vault,
      metadata.fileHandle,
      metadata.rowIndex,
      newTaskString
    );
  }
  async function updateSourceRow(id, transform) {
    const metadata = metadataByTaskId.get(id);
    if (!metadata) {
      return;
    }
    await transformSourceRow(
      vault,
      metadata.fileHandle,
      metadata.rowIndex,
      transform
    );
  }
  function getTaskWithMetadata(id) {
    const metadata = metadataByTaskId.get(id);
    const task = tasksByTaskId.get(id);
    return task && metadata ? { task, metadata } : null;
  }
  async function assignBlockLinks(tasks) {
    var _a5;
    const resolved = /* @__PURE__ */ new Map();
    const needsAssignment = [];
    for (const task of tasks) {
      if (task.blockLink) {
        resolved.set(task.id, task.blockLink);
        continue;
      }
      const metadata = metadataByTaskId.get(task.id);
      if (metadata) {
        needsAssignment.push({ task, metadata });
      }
    }
    if (needsAssignment.length === 0) {
      return resolved;
    }
    const byFile = /* @__PURE__ */ new Map();
    for (const entry of needsAssignment) {
      const list = (_a5 = byFile.get(entry.metadata.fileHandle)) != null ? _a5 : [];
      list.push(entry);
      byFile.set(entry.metadata.fileHandle, list);
    }
    for (const [fileHandle, entries] of byFile) {
      const rows = await readFileRows(vault, fileHandle);
      const existing = /* @__PURE__ */ new Set();
      for (const row of rows) {
        const match = row.match(/\s\^([a-zA-Z0-9-]+)\s*$/);
        if (match == null ? void 0 : match[1]) existing.add(match[1]);
      }
      let changed = false;
      for (const { task, metadata } of entries) {
        const row = rows[metadata.rowIndex];
        if (row == null) continue;
        const ensured = ensureRowBlockLink(row, existing);
        rows[metadata.rowIndex] = ensured.row;
        changed = changed || ensured.changed;
        resolved.set(task.id, ensured.blockLink);
      }
      if (changed) {
        await writeFileRows(vault, fileHandle, rows);
      }
    }
    return resolved;
  }
  return {
    async changeColumn(id, column) {
      await updateRowWithTask(id, (task) => task.column = column);
    },
    async reorderTask(groupId, columnTag, displayOrderIds, draggedId, targetIndex) {
      var _a5;
      const displayOrder = displayOrderIds.map((id) => tasksByTaskId.get(id)).filter((task) => !!task);
      const plan = computeDropPlan(displayOrder, draggedId, targetIndex);
      if (plan.prefixTasks.length === 0) {
        return;
      }
      const resolved = await assignBlockLinks(plan.tasksNeedingBlockLink);
      const entries = buildOrderEntries(plan.prefixTasks, (task) => {
        var _a6;
        const link2 = (_a6 = task.blockLink) != null ? _a6 : resolved.get(task.id);
        if (!link2) {
          return task.id;
        }
        return link2;
      });
      const current = getManualOrder();
      setManualOrder({
        ...current,
        [groupId]: {
          ...(_a5 = current[groupId]) != null ? _a5 : {},
          [columnTag]: entries
        }
      });
    },
    async unpinTask(groupId, columnTag, taskId) {
      const task = tasksByTaskId.get(taskId);
      if (!task) return;
      const key2 = taskKey(task);
      if (!key2) return;
      const current = getManualOrder();
      const groupEntries = current[groupId];
      const entries = groupEntries == null ? void 0 : groupEntries[columnTag];
      const next2 = removeEntry(entries, key2);
      if (next2 === entries) return;
      const nextStore = { ...current };
      const nextGroup = { ...groupEntries != null ? groupEntries : {} };
      if (next2.length === 0) {
        delete nextGroup[columnTag];
      } else {
        nextGroup[columnTag] = next2;
      }
      if (Object.keys(nextGroup).length === 0) {
        delete nextStore[groupId];
      } else {
        nextStore[groupId] = nextGroup;
      }
      setManualOrder(nextStore);
    },
    pruneManualOrder(presentKeysByGroupAndColumn) {
      var _a5, _b3;
      const current = getManualOrder();
      let changed = false;
      const next2 = { ...current };
      for (const [groupId, entriesByColumn] of Object.entries(current)) {
        const presentByColumn = (_a5 = presentKeysByGroupAndColumn[groupId]) != null ? _a5 : {};
        const nextGroup = { ...entriesByColumn };
        for (const [columnTag, entries] of Object.entries(entriesByColumn)) {
          const present = (_b3 = presentByColumn[columnTag]) != null ? _b3 : /* @__PURE__ */ new Set();
          const pruned = entries.filter((entry) => present.has(entry));
          if (pruned.length !== entries.length) {
            changed = true;
            if (pruned.length === 0) {
              delete nextGroup[columnTag];
            } else {
              nextGroup[columnTag] = pruned;
            }
          }
        }
        if (Object.keys(nextGroup).length === 0) {
          changed = true;
          delete next2[groupId];
        } else {
          next2[groupId] = nextGroup;
        }
      }
      if (changed) {
        setManualOrder(next2);
      }
    },
    async markDone(id) {
      let shouldAddCompletionDate = false;
      await updateRowWithTask(
        id,
        (task) => {
          shouldAddCompletionDate = !task.done;
          task.done = true;
        },
        (row) => shouldAddCompletionDate ? addCompletionDateIfEnabled(row) : row
      );
    },
    async toggleDone(id) {
      let shouldAddCompletionDate = false;
      await updateRowWithTask(
        id,
        (task) => {
          shouldAddCompletionDate = task.cycleStatus(getStatusMarkerOrder());
        },
        (row) => shouldAddCompletionDate ? addCompletionDateIfEnabled(row) : row
      );
    },
    async updateContent(id, content) {
      await updateRowWithTask(id, (task) => task.content = content);
    },
    async updateSourceBlockRow(id, rowIndex, content) {
      const entry = getTaskWithMetadata(id);
      if (!entry) {
        return;
      }
      const nextRow = entry.task.updateSourceBlockRowContent(rowIndex, content);
      if (nextRow == null) {
        return;
      }
      await updateRow(vault, entry.metadata.fileHandle, rowIndex, nextRow);
    },
    async toggleSourceTaskStatus(id, rowIndex) {
      const entry = getTaskWithMetadata(id);
      if (!entry) {
        return;
      }
      const nextRow = entry.task.cycleSourceTaskRowStatus(rowIndex, getStatusMarkerOrder());
      if (nextRow == null) {
        return;
      }
      await updateRow(vault, entry.metadata.fileHandle, rowIndex, nextRow);
    },
    async addSourceBlockRow(id, rowIndex, location, kind) {
      const entry = getTaskWithMetadata(id);
      if (!entry) {
        return;
      }
      const { fileHandle } = entry.metadata;
      const rows = await readFileRows(vault, fileHandle);
      const row = rows[rowIndex];
      if (row == null) {
        return;
      }
      const block2 = getNodeBlock(rows, rowIndex);
      let targetIndex = block2.start;
      let indentation = block2.indentation;
      if (location === "child") {
        targetIndex = block2.end;
        let stepChar = "  ";
        for (const r2 of rows) {
          if (r2) {
            const match = r2.match(/^(\s+)/);
            if (match && match[1]) {
              stepChar = match[1].includes("	") ? "	" : "  ";
              break;
            }
          }
        }
        indentation = block2.indentation + stepChar;
      } else {
        targetIndex = block2.end;
      }
      let bullet = "-";
      const bulletMatch = row.match(/^(\s*)([-*+])/);
      if (bulletMatch == null ? void 0 : bulletMatch[2]) {
        bullet = bulletMatch[2];
      }
      const text2 = kind === "task" ? "New subtask" : "New note";
      const newLine = kind === "task" ? `${indentation}${bullet} [ ] ${text2}` : `${indentation}${bullet} ${text2}`;
      rows.splice(targetIndex, 0, newLine);
      await writeFileRows(vault, fileHandle, rows);
    },
    async deleteSourceBlockRow(id, rowIndex) {
      const entry = getTaskWithMetadata(id);
      if (!entry) {
        return;
      }
      const { fileHandle } = entry.metadata;
      const rows = await readFileRows(vault, fileHandle);
      const block2 = getNodeBlock(rows, rowIndex);
      rows.splice(block2.start, block2.end - block2.start);
      await writeFileRows(vault, fileHandle, rows);
    },
    async moveSourceBlockRow(id, draggedRowIndex, targetRowIndex, position, targetDepth) {
      var _a5, _b3;
      const entry = getTaskWithMetadata(id);
      if (!entry) {
        return;
      }
      const { fileHandle } = entry.metadata;
      const rows = await readFileRows(vault, fileHandle);
      const draggedBlock = getNodeBlock(rows, draggedRowIndex);
      const parentCardRow = rows[entry.task.rowIndex];
      if (parentCardRow == null) {
        return;
      }
      const parentCardIndentation = (_b3 = (_a5 = parentCardRow.match(/^\s*/)) == null ? void 0 : _a5[0]) != null ? _b3 : "";
      let stepChar = "  ";
      for (const r2 of rows) {
        if (r2) {
          const match = r2.match(/^(\s+)/);
          if (match && match[1]) {
            stepChar = match[1].includes("	") ? "	" : "  ";
            break;
          }
        }
      }
      const safeTargetDepth = Math.max(1, targetDepth);
      const newRootIndentation = parentCardIndentation + stepChar.repeat(safeTargetDepth);
      const blockRows = rows.slice(draggedBlock.start, draggedBlock.end).map((row) => {
        var _a6, _b4;
        if (row == null) return "";
        const rowIndentation = (_b4 = (_a6 = row.match(/^\s*/)) == null ? void 0 : _a6[0]) != null ? _b4 : "";
        const relativeIndentation = rowIndentation.slice(draggedBlock.indentation.length);
        const nextIndentation = newRootIndentation + relativeIndentation;
        return nextIndentation + row.slice(rowIndentation.length);
      });
      const targetBlock = getNodeBlock(rows, targetRowIndex);
      let insertIndex = position === "before" ? targetBlock.start : targetBlock.end;
      rows.splice(draggedBlock.start, blockRows.length);
      if (draggedBlock.start < insertIndex) {
        insertIndex -= blockRows.length;
      }
      rows.splice(insertIndex, 0, ...blockRows);
      await writeFileRows(vault, fileHandle, rows);
    },
    async setDateProperty(id, key2, date) {
      await updateSourceRow(
        id,
        (row) => {
          var _a5, _b3;
          return (_b3 = (_a5 = getPropertyWriteAdapter(getPropertySchemaOption())) == null ? void 0 : _a5.upsertDate(row, key2, date)) != null ? _b3 : row;
        }
      );
    },
    async clearDateProperty(id, key2) {
      await updateSourceRow(
        id,
        (row) => {
          var _a5, _b3;
          return (_b3 = (_a5 = getPropertyWriteAdapter(getPropertySchemaOption())) == null ? void 0 : _a5.removeDate(row, key2)) != null ? _b3 : row;
        }
      );
    },
    async archiveTasks(ids) {
      for (const id of ids) {
        await updateRowWithTask(id, (task) => task.archive());
      }
    },
    async cancelTasks(ids) {
      for (const id of ids) {
        await updateRowWithTask(id, (task) => task.cancel());
      }
    },
    async restoreTasks(ids) {
      for (const id of ids) {
        await updateRowWithTask(id, (task) => task.restore());
      }
    },
    async deleteTask(id) {
      const entry = getTaskWithMetadata(id);
      if (!entry) {
        return;
      }
      await deleteRowBlocks(vault, entry.metadata.fileHandle, [
        {
          rowIndex: entry.metadata.rowIndex,
          lineCount: entry.task.sourceBlockLineCount
        }
      ]);
    },
    async updateSwimlaneTag(ids, newTag, prefix, excludedTags) {
      for (const id of ids) {
        await updateRowWithTask(id, (task) => {
          const oldTag = getTaskTagGroupValue(
            task,
            { kind: "tag-prefix", prefix },
            excludedTags
          );
          task.replaceTag(oldTag, newTag);
        });
      }
    },
    async duplicateTask(id) {
      const entry = getTaskWithMetadata(id);
      if (!entry) return;
      const { fileHandle, rowIndex } = entry.metadata;
      const rows = await readFileRows(vault, fileHandle);
      if (rowIndex >= rows.length) return;
      const sourceBlockRows = rows.slice(rowIndex, rowIndex + entry.task.sourceBlockLineCount);
      const originalLine = sourceBlockRows[0];
      if (!originalLine) return;
      const duplicatedRows = [
        createDuplicateLine(originalLine),
        ...sourceBlockRows.slice(1)
      ];
      rows.splice(rowIndex + sourceBlockRows.length, 0, ...duplicatedRows);
      await writeFileRows(vault, fileHandle, rows);
    },
    async moveTasksToFile(ids, destinationFile, destinationColumn) {
      var _a5;
      const moves = ids.map((id) => {
        const task = tasksByTaskId.get(id);
        const metadata = metadataByTaskId.get(id);
        return task && metadata ? { task, metadata } : null;
      }).filter((move2) => !!move2).filter((move2) => move2.metadata.fileHandle.path !== destinationFile.path);
      if (moves.length === 0) {
        return;
      }
      const destinationRows = await readFileRows(vault, destinationFile);
      for (const { task } of moves) {
        const serializedParent = taskIsInColumn(task, destinationColumn) ? task.serialise() : task.serialiseForColumn(destinationColumn);
        destinationRows.push(...task.sourceBlockRows(serializedParent));
      }
      await writeFileRows(vault, destinationFile, destinationRows);
      const movesBySourceFile = /* @__PURE__ */ new Map();
      for (const { task, metadata } of moves) {
        const sourceMoves = (_a5 = movesBySourceFile.get(metadata.fileHandle)) != null ? _a5 : [];
        sourceMoves.push({
          rowIndex: metadata.rowIndex,
          lineCount: task.sourceBlockLineCount
        });
        movesBySourceFile.set(metadata.fileHandle, sourceMoves);
      }
      for (const [sourceFile, sourceMoves] of movesBySourceFile) {
        await deleteRowBlocks(vault, sourceFile, sourceMoves);
      }
    },
    async viewFile(id, event2) {
      const metadata = metadataByTaskId.get(id);
      if (!metadata) {
        return;
      }
      const { fileHandle, rowIndex } = metadata;
      const leaf = workspace.getLeaf(import_obsidian10.Keymap.isModEvent(event2));
      await leaf.openFile(fileHandle);
      const editorView = workspace.getActiveViewOfType(import_obsidian10.MarkdownView);
      editorView == null ? void 0 : editorView.editor.setCursor(rowIndex);
    },
    getTargetFile,
    pickFileForNewTask(column, e, onFileSelected, forceShowPicker = false) {
      if (!forceShowPicker) {
        const targetFile = getTargetFile();
        if (targetFile) {
          onFileSelected(targetFile);
          return;
        }
      }
      const onFileSelectedWithPersist = (file) => {
        setLastUsedTaskFile(file.path);
        onFileSelected(file);
      };
      const files = vault.getMarkdownFiles().filter(
        (file) => shouldIncludeFilePath(file.path, getFilenameFilter(), getExcludeFilter(), getBoardFolderPath())
      ).sort((a, b) => a.path.localeCompare(b.path));
      const target = e.target;
      if (!target) {
        return;
      }
      const boundingRect = target.getBoundingClientRect();
      const y = boundingRect.top + boundingRect.height / 2;
      const x = boundingRect.left + boundingRect.width / 2;
      const defaultTaskFilePath = getDefaultTaskFile();
      let defaultFileState = null;
      if (defaultTaskFilePath) {
        const abstractFile = vault.getAbstractFileByPath(defaultTaskFilePath);
        if (!(abstractFile instanceof import_obsidian10.TFile)) {
          defaultFileState = {
            error: `\u2605 ${defaultTaskFilePath} (not found)`
          };
        } else if (!shouldIncludeFilePath(
          defaultTaskFilePath,
          getFilenameFilter(),
          getExcludeFilter(),
          getBoardFolderPath()
        )) {
          defaultFileState = {
            error: `\u2605 ${defaultTaskFilePath} (outside scope)`
          };
        } else {
          defaultFileState = { file: abstractFile };
        }
      }
      function createMenu(folder2, parentMenu) {
        const menu = new import_obsidian10.Menu();
        menu.addItem((i) => {
          i.setTitle(parentMenu ? `\u2190 back` : "Choose a file").setDisabled(!parentMenu).onClick(() => {
            parentMenu == null ? void 0 : parentMenu.showAtPosition({ x, y });
          });
        });
        if (!parentMenu && defaultFileState) {
          if ("file" in defaultFileState) {
            const df = defaultFileState.file;
            menu.addItem((i) => {
              i.setTitle(`\u2605 ${df.path}`).onClick(() => {
                onFileSelectedWithPersist(df);
              });
            });
          } else {
            menu.addItem((i) => {
              i.setTitle(defaultFileState.error).setDisabled(
                true
              );
            });
          }
          menu.addSeparator();
        }
        for (const [label, folderItem] of Object.entries(folder2)) {
          menu.addItem((i) => {
            i.setTitle(
              folderItem instanceof import_obsidian10.TFile ? label : label + " \u2192"
            ).onClick(() => {
              if (folderItem instanceof import_obsidian10.TFile) {
                onFileSelectedWithPersist(folderItem);
              } else {
                createMenu(folderItem, menu);
              }
            });
          });
        }
        menu.showAtPosition({ x, y });
      }
      const folder = {};
      for (const file of files) {
        const segments = file.path.split("/");
        let currFolder = folder;
        for (const [i, segment] of segments.entries()) {
          if (i === segments.length - 1) {
            currFolder[segment] = file;
          } else {
            const nextFolder = currFolder[segment] || {};
            if (nextFolder instanceof import_obsidian10.TFile) {
              continue;
            }
            currFolder[segment] = nextFolder;
            currFolder = nextFolder;
          }
        }
      }
      createMenu(folder, void 0);
    },
    async createTask(file, content, column, additionalTags = [], dateProperties = {}) {
      var _a5, _b3;
      const adapter = getPropertyWriteAdapter(getPropertySchemaOption());
      const columnDefinition = getColumnDefinitions().find((definition) => definition.id === column);
      const priorityAdapter = getPropertyWriteAdapter((_a5 = getColumnPrioritySchema(columnDefinition)) != null ? _a5 : getPropertySchemaOption());
      let taskLine = createTaskLine(
        content,
        getPlacementTagsForColumn(column),
        additionalTags,
        (_b3 = getColumnStatus(columnDefinition)) != null ? _b3 : " "
      );
      const priority = getColumnPriority(columnDefinition);
      if (priority && priorityAdapter) {
        taskLine = priorityAdapter.upsertPriority(taskLine, priority);
      }
      if (adapter) {
        for (const key2 of ["due", "scheduled", "start"]) {
          const date = dateProperties[key2];
          if (date) {
            taskLine = adapter.upsertDate(taskLine, key2, date);
          }
        }
      }
      await updateRow(
        vault,
        file,
        void 0,
        taskLine
      );
    }
  };
  function addCompletionDateIfEnabled(rawLine) {
    var _a5;
    const adapter = getPropertyWriteAdapter(getPropertySchemaOption());
    if (!adapter) {
      return rawLine;
    }
    return adapter.addCompletionDateIfMissing(rawLine, formatLocalDate((_a5 = getCurrentDate == null ? void 0 : getCurrentDate()) != null ? _a5 : /* @__PURE__ */ new Date()));
  }
}
function taskIsInColumn(task, column) {
  if (column === "done") {
    return task.done || task.column === "done";
  }
  if (column === "uncategorised") {
    return !task.done && !task.column;
  }
  return task.column === column;
}
function getNodeBlock(rows, rowIndex) {
  var _a5, _b3, _c2, _d;
  const rootRow = rows[rowIndex];
  if (rootRow == null) return { start: rowIndex, end: rowIndex, indentation: "" };
  const indentation = (_b3 = (_a5 = rootRow.match(/^\s*/)) == null ? void 0 : _a5[0]) != null ? _b3 : "";
  let end = rowIndex + 1;
  while (end < rows.length) {
    const row = rows[end];
    if (row == null || row === "") {
      break;
    }
    const rowIndentation = (_d = (_c2 = row.match(/^\s*/)) == null ? void 0 : _c2[0]) != null ? _d : "";
    if (!rowIndentation.startsWith(indentation) || rowIndentation.length <= indentation.length) {
      break;
    }
    end++;
  }
  return { start: rowIndex, end, indentation };
}

// src/ui/tasks/store.ts
function getMarkerSettings(settings) {
  var _a5, _b3, _c2, _d, _e, _f, _g;
  return {
    consolidateTags: (_a5 = settings.consolidateTags) != null ? _a5 : false,
    doneStatusMarkers: (_b3 = settings.doneStatusMarkers) != null ? _b3 : DEFAULT_DONE_STATUS_MARKERS,
    cancelledStatusMarkers: (_c2 = settings.cancelledStatusMarkers) != null ? _c2 : DEFAULT_CANCELLED_STATUS_MARKERS,
    ignoredStatusMarkers: (_d = settings.ignoredStatusMarkers) != null ? _d : DEFAULT_IGNORED_STATUS_MARKERS,
    excludedTaskTags: new Set(
      ((_e = settings.excludedTaskTags) != null ? _e : []).map((t) => t.trim().toLowerCase())
    ),
    propertySchema: getSchemaImpl((_f = settings.propertySchema) != null ? _f : "none" /* None */),
    treatNestedTasksAsSubtasks: (_g = settings.treatNestedTasksAsSubtasks) != null ? _g : false
  };
}
function createTasksStore(vault, workspace, registerEvent, columnDefinitionsStore, columnPlacementTagTableStore, getFilenameFilter, getExcludeFilter, getBoardFolderPath, settingsStore, requestSave) {
  const tasksStore = writable([]);
  let timer;
  const tasksByTaskId = /* @__PURE__ */ new Map();
  const metadataByTaskId = /* @__PURE__ */ new Map();
  const taskIdsByFileHandle = /* @__PURE__ */ new Map();
  function publishTasks() {
    tasksStore.set(
      [...tasksByTaskId.values()].sort((a, b) => {
        if (a.path !== b.path) {
          return a.path.localeCompare(b.path);
        }
        return a.rowIndex - b.rowIndex;
      })
    );
  }
  function debounceSetTasks() {
    if (timer) {
      return;
    }
    timer = window.setTimeout(() => {
      timer = void 0;
      publishTasks();
    }, 50);
  }
  function publishTasksImmediately() {
    if (timer) {
      window.clearTimeout(timer);
      timer = void 0;
    }
    publishTasks();
  }
  function shouldHandle(file) {
    return shouldIncludeFilePath(file.path, getFilenameFilter(), getExcludeFilter(), getBoardFolderPath());
  }
  function processFile(fileHandle) {
    updateMapsFromFile({
      fileHandle,
      tasksByTaskId,
      metadataByTaskId,
      taskIdsByFileHandle,
      vault,
      columnDefinitionsStore,
      columnPlacementTagTableStore,
      ...getMarkerSettings(get2(settingsStore))
    }).then(() => {
      debounceSetTasks();
    });
  }
  function initialise() {
    tasksByTaskId.clear();
    metadataByTaskId.clear();
    taskIdsByFileHandle.clear();
    publishTasksImmediately();
    for (const fileHandle of vault.getMarkdownFiles()) {
      if (!shouldHandle(fileHandle)) {
        continue;
      }
      processFile(fileHandle);
    }
  }
  registerEvent(
    vault.on("modify", (fileHandle) => {
      if (fileHandle instanceof import_obsidian11.TFile && shouldHandle(fileHandle)) {
        processFile(fileHandle);
      }
    })
  );
  registerEvent(
    vault.on("create", (fileHandle) => {
      if (fileHandle instanceof import_obsidian11.TFile && shouldHandle(fileHandle)) {
        processFile(fileHandle);
      }
    })
  );
  registerEvent(
    vault.on("delete", (fileHandle) => {
      if (fileHandle instanceof import_obsidian11.TFile) {
        const tasksToDelete = taskIdsByFileHandle.get(fileHandle);
        if (!tasksToDelete) return;
        for (const taskId of tasksToDelete) {
          tasksByTaskId.delete(taskId);
          metadataByTaskId.delete(taskId);
        }
        taskIdsByFileHandle.delete(fileHandle);
        debounceSetTasks();
      }
    })
  );
  registerEvent(
    vault.on("rename", (fileHandle) => {
      if (fileHandle instanceof import_obsidian11.TFile) {
        initialise();
      }
    })
  );
  const taskActions = createTaskActions({
    tasksByTaskId,
    metadataByTaskId,
    vault,
    workspace,
    getFilenameFilter,
    getExcludeFilter,
    getBoardFolderPath,
    getPlacementTagsForColumn: (column) => {
      var _a5;
      return (_a5 = get2(columnPlacementTagTableStore)[column]) != null ? _a5 : [column];
    },
    getColumnDefinitions: () => get2(columnDefinitionsStore),
    getDefaultTaskFile: () => get2(settingsStore).defaultTaskFile || null,
    getLastUsedTaskFile: () => get2(settingsStore).lastUsedTaskFile || null,
    setLastUsedTaskFile: (path) => {
      settingsStore.update((s) => ({ ...s, lastUsedTaskFile: path }));
      requestSave();
    },
    getPropertySchemaOption: () => {
      var _a5;
      return (_a5 = get2(settingsStore).propertySchema) != null ? _a5 : "none" /* None */;
    },
    getStatusMarkerOrder: () => {
      var _a5;
      return (_a5 = get2(settingsStore).statusMarkerOrder) != null ? _a5 : "";
    },
    getManualOrder: () => {
      var _a5;
      return (_a5 = get2(settingsStore).manualOrder) != null ? _a5 : {};
    },
    setManualOrder: (next2) => {
      settingsStore.update((s) => ({ ...s, manualOrder: next2 }));
      requestSave();
    }
  });
  return { tasksStore, taskActions, initialise };
}

// src/ui/kanban_frontmatter.ts
var import_gray_matter = __toESM(require_gray_matter());
var KANBAN_PLUGIN_KEY = "kanban_plugin";
function parseKanbanSettingsFromViewData(data) {
  const parsed = (0, import_gray_matter.default)(data);
  return parseSettingsString(toSettingsPayload(parsed.data[KANBAN_PLUGIN_KEY]));
}
function writeKanbanSettingsToViewData(data, settings) {
  const parsed = (0, import_gray_matter.default)(data);
  return import_gray_matter.default.stringify(parsed.content, {
    ...parsed.data,
    [KANBAN_PLUGIN_KEY]: toSettingsString(settings)
  });
}
function toSettingsPayload(value) {
  if (typeof value === "string") {
    return value;
  }
  if (value == null) {
    return "";
  }
  return JSON.stringify(value);
}

// src/ui/settings/column_rename_migration.ts
function getChangedColumnMatchRules(oldSettings, newSettings) {
  const oldColumnsById = new Map(oldSettings.columns.map((column) => [column.id, column]));
  return newSettings.columns.flatMap((newColumn) => {
    const oldColumn = oldColumnsById.get(newColumn.id);
    if (!oldColumn) return [];
    if (columnRuleSignature(oldColumn) === columnRuleSignature(newColumn)) return [];
    return [{ id: newColumn.id, oldColumn, newColumn }];
  });
}
async function applyChangedColumnTagUpdates({
  vault,
  oldSettings,
  newSettings,
  boardFolderPath,
  updateChoices
}) {
  const changedColumns = getChangedColumnMatchRules(oldSettings, newSettings).filter(
    ({ id }) => updateChoices[id] !== false
  );
  if (changedColumns.length === 0) {
    return;
  }
  const newColumnData = createColumnData(newSettings.columns);
  const oldSettingsScope = resolveScopeSettings(oldSettings, boardFolderPath);
  const changedColumnsById = new Map(changedColumns.map((column) => [column.id, column]));
  const files = vault.getMarkdownFiles().filter(
    (file) => shouldIncludeFilePath(
      file.path,
      oldSettingsScope.filenameFilter,
      oldSettingsScope.excludeFilter,
      boardFolderPath
    )
  );
  for (const file of files) {
    await updateFileForChangedColumns(
      vault,
      file,
      changedColumnsById,
      oldSettings.columns,
      newSettings.columns,
      newColumnData.columnPlacementTagTable,
      oldSettings
    );
  }
}
async function updateFileForChangedColumns(vault, file, changedColumnsById, oldColumnDefinitions, newColumnDefinitions, newPlacementTagTable, settings) {
  var _a5, _b3, _c2, _d, _e, _f, _g;
  const contents = await vault.read(file);
  const rows = contents.split("\n");
  const oldPropertySchemaOption = (_a5 = settings.propertySchema) != null ? _a5 : "none" /* None */;
  const oldPropertySchema = getSchemaImpl(oldPropertySchemaOption);
  let changed = false;
  for (let i = 0; i < rows.length; i += 1) {
    const row = rows[i];
    if (!row || !isTrackedTaskString(row, (_b3 = settings.ignoredStatusMarkers) != null ? _b3 : DEFAULT_IGNORED_STATUS_MARKERS)) {
      continue;
    }
    const status = ((_c2 = row.match(/^\s*[-*+]\s\[([^\[\]]*)\]\s/)) == null ? void 0 : _c2[1]) || " ";
    const oldProperties = oldPropertySchema.parseProperties(row);
    const matchedColumn = resolveMatchedColumnDefinition(oldColumnDefinitions, {
      tags: getTagsFromContent(row),
      status,
      priority: getPriorityMatchValue(oldPropertySchemaOption, oldProperties),
      prioritySchema: getPriorityColumnContextSchema2(oldPropertySchemaOption),
      priorities: getPriorityMatchValues(row)
    });
    const targetColumnId = matchedColumn == null ? void 0 : matchedColumn.id;
    const changedColumn = targetColumnId ? changedColumnsById.get(targetColumnId) : void 0;
    if (!targetColumnId || targetColumnId === "archived" || !changedColumn) {
      continue;
    }
    const task = new Task(
      row,
      file,
      i,
      {
        columnDefinitions: oldColumnDefinitions,
        columnWriteDefinitions: newColumnDefinitions,
        columnPlacementTagTable: newPlacementTagTable,
        consolidateTags: (_d = settings.consolidateTags) != null ? _d : false,
        doneStatusMarkers: (_e = settings.doneStatusMarkers) != null ? _e : DEFAULT_DONE_STATUS_MARKERS,
        cancelledStatusMarkers: (_f = settings.cancelledStatusMarkers) != null ? _f : DEFAULT_CANCELLED_STATUS_MARKERS,
        ignoredStatusMarkers: (_g = settings.ignoredStatusMarkers) != null ? _g : DEFAULT_IGNORED_STATUS_MARKERS,
        propertySchema: getSchemaImpl(getMigrationSchema(changedColumn, oldPropertySchemaOption))
      }
    );
    if (!task.done) {
      task.column = targetColumnId;
    }
    const nextRow = task.serialise();
    if (nextRow !== row) {
      rows[i] = nextRow;
      changed = true;
    }
  }
  if (changed) {
    await vault.modify(file, rows.join("\n"));
  }
}
function getMigrationSchema(changedColumn, fallbackSchema) {
  var _a5, _b3;
  if (usesPriorityMatching(changedColumn.newColumn)) {
    return (_a5 = getColumnPrioritySchema(changedColumn.newColumn)) != null ? _a5 : fallbackSchema;
  }
  if (usesPriorityMatching(changedColumn.oldColumn)) {
    return (_b3 = getColumnPrioritySchema(changedColumn.oldColumn)) != null ? _b3 : fallbackSchema;
  }
  return fallbackSchema;
}
function getPriorityColumnContextSchema2(propertySchemaOption) {
  return propertySchemaOption === "tasks" /* TasksPlugin */ || propertySchemaOption === "dataview" /* Dataview */ ? propertySchemaOption : void 0;
}
function getPriorityMatchValue(propertySchemaOption, properties) {
  const priority = properties.get("priority");
  if (propertySchemaOption === "tasks" /* TasksPlugin */ && typeof (priority == null ? void 0 : priority.value) === "number") {
    return getTasksPriorityValueFromWeight(priority.value);
  }
  if (propertySchemaOption === "dataview" /* Dataview */ && typeof (priority == null ? void 0 : priority.value) === "string") {
    return priority.value.trim();
  }
  return void 0;
}
function getPriorityMatchValues(rawLine) {
  return {
    ["tasks" /* TasksPlugin */]: getPriorityMatchValue(
      "tasks" /* TasksPlugin */,
      getSchemaImpl("tasks" /* TasksPlugin */).parseProperties(rawLine)
    ),
    ["dataview" /* Dataview */]: getPriorityMatchValue(
      "dataview" /* Dataview */,
      getSchemaImpl("dataview" /* Dataview */).parseProperties(rawLine)
    )
  };
}
function resolveScopeSettings(settings, boardFolderPath) {
  var _a5, _b3;
  let filenameFilter = null;
  switch (settings.scope) {
    case "everywhere":
      filenameFilter = null;
      break;
    case "folder":
      filenameFilter = boardFolderPath ? [boardFolderPath] : null;
      break;
    case "selectedFolders": {
      const selected = (_a5 = settings.scopeFolders) != null ? _a5 : [];
      filenameFilter = boardFolderPath ? [boardFolderPath, ...selected.filter((folder) => folder !== boardFolderPath)] : selected;
      break;
    }
  }
  const excludePaths = (_b3 = settings.excludePaths) != null ? _b3 : [];
  return {
    filenameFilter,
    excludeFilter: excludePaths.length > 0 ? excludePaths : null
  };
}

// src/ui/text_view.ts
var KANBAN_VIEW_NAME = "kanban-view";
var KanbanView = class extends import_obsidian12.TextFileView {
  constructor(leaf) {
    super(leaf);
    this.filenameFilter = null;
    this.excludeFilter = null;
    this.boardFolderPath = null;
    this.icon = "kanban-square";
    this.settingsStore = createSettingsStore();
    this.destroySettingsStore = this.settingsStore.subscribe((settings) => {
      var _a5, _b3, _c2, _d, _e;
      this.boardFolderPath = (_c2 = (_b3 = (_a5 = this.file) == null ? void 0 : _a5.parent) == null ? void 0 : _b3.path) != null ? _c2 : null;
      switch (settings.scope) {
        case "everywhere" /* Everywhere */:
          this.filenameFilter = null;
          break;
        case "folder" /* Folder */: {
          this.filenameFilter = this.boardFolderPath !== null ? [this.boardFolderPath] : null;
          break;
        }
        case "selectedFolders" /* SelectedFolders */: {
          const selected = (_d = settings.scopeFolders) != null ? _d : [];
          this.filenameFilter = this.boardFolderPath !== null ? [this.boardFolderPath, ...selected.filter((f) => f !== this.boardFolderPath)] : selected;
          break;
        }
        default:
          this.filenameFilter = null;
          break;
      }
      const excludePaths = (_e = settings.excludePaths) != null ? _e : [];
      this.excludeFilter = excludePaths.length > 0 ? excludePaths : null;
    });
    const {
      columnDefinitions,
      columnTagTable,
      columnColourTable,
      columnPlacementTagTable,
      columnMatchTagTable,
      columnSubtitleTable
    } = createColumnStores(
      this.settingsStore
    );
    this.columnDefinitionsStore = columnDefinitions;
    this.columnTagTableStore = columnTagTable;
    this.columnColourTableStore = columnColourTable;
    this.columnPlacementTagTableStore = columnPlacementTagTable;
    this.columnMatchTagTableStore = columnMatchTagTable;
    this.columnSubtitleTableStore = columnSubtitleTable;
    const { tasksStore, taskActions, initialise } = createTasksStore(
      this.app.vault,
      this.app.workspace,
      this.registerEvent.bind(this),
      this.columnDefinitionsStore,
      this.columnPlacementTagTableStore,
      () => this.filenameFilter,
      () => this.excludeFilter,
      () => this.boardFolderPath,
      this.settingsStore,
      () => this.requestSave()
    );
    this.tasksStore = tasksStore;
    this.taskActions = taskActions;
    this.initialiseTasksStore = initialise;
  }
  async onLocalSettingsChange(newSettings, options2) {
    var _a5, _b3, _c2;
    const previousSettings = structuredClone(get2(this.settingsStore));
    try {
      await applyChangedColumnTagUpdates({
        vault: this.app.vault,
        oldSettings: previousSettings,
        newSettings,
        boardFolderPath: (_c2 = (_b3 = (_a5 = this.file) == null ? void 0 : _a5.parent) == null ? void 0 : _b3.path) != null ? _c2 : null,
        updateChoices: options2.updateExistingTaskTagsByColumnId
      });
    } catch (error) {
      console.error("Failed to update changed column task tags", error);
      new import_obsidian12.Notice("Failed to update existing task tags for changed columns.");
      return;
    }
    this.settingsStore.set(newSettings);
    this.initialiseTasksStore();
    this.requestSave();
  }
  openSettingsModal() {
    var _a5, _b3, _c2;
    const settingsModal = new SettingsModal(
      this.app,
      structuredClone(get2(this.settingsStore)),
      (newSettings, options2) => this.onLocalSettingsChange(newSettings, options2),
      (_c2 = (_b3 = (_a5 = this.file) == null ? void 0 : _a5.parent) == null ? void 0 : _b3.path) != null ? _c2 : null
    );
    settingsModal.open();
    return new Promise((resolve) => {
      settingsModal.onClose = () => {
        resolve();
        settingsModal.onClose = () => void 0;
      };
    });
  }
  getViewType() {
    this.leaf.openFile;
    return KANBAN_VIEW_NAME;
  }
  getViewData() {
    return writeKanbanSettingsToViewData(this.data, get2(this.settingsStore));
  }
  setViewData(data, clear) {
    this.data = data;
    this.settingsStore.set(this.getInitialSettings(data));
    this.initialiseTasksStore();
  }
  getInitialSettings(data) {
    return parseKanbanSettingsFromViewData(data);
  }
  clear() {
  }
  async onOpen() {
    this.contentEl.addClass("task-list-kanban-view");
    this.component = new Main({
      target: this.contentEl,
      props: {
        app: this.app,
        tasksStore: this.tasksStore,
        taskActions: this.taskActions,
        columnTagTableStore: this.columnTagTableStore,
        columnColourTableStore: this.columnColourTableStore,
        columnMatchTagTableStore: this.columnMatchTagTableStore,
        columnSubtitleTableStore: this.columnSubtitleTableStore,
        openSettings: () => this.openSettingsModal(),
        settingsStore: this.settingsStore,
        requestSave: () => this.requestSave()
      }
    });
  }
  async onClose() {
    var _a5;
    this.contentEl.removeClass("task-list-kanban-view");
    (_a5 = this.component) == null ? void 0 : _a5.$destroy();
    this.destroySettingsStore();
  }
};

// src/entry.ts
var Base = class extends import_obsidian13.Plugin {
  async onload() {
    this.registerView(KANBAN_VIEW_NAME, (leaf) => new KanbanView(leaf));
    this.registerHoverLinkSource("kanban-view", {
      display: "Kanban",
      defaultMod: false
    });
    this.switchToKanbanAfterLoad();
    this.registerEvent(
      this.app.workspace.on("active-leaf-change", () => {
        this.switchToKanbanAfterLoad();
      })
    );
    this.registerEvent(
      this.app.workspace.on("file-menu", (menu, file) => {
        menu.addItem((item) => {
          item.setTitle("New kanban").setIcon("square-kanban").onClick(async () => {
            var _a5;
            const newFile = await this.app.vault.create(
              file.path + "/Kanban-" + Date.now() + ".md",
              `---
kanban_plugin: {}
---
`
            );
            (_a5 = this.app.workspace.getActiveViewOfType(import_obsidian13.MarkdownView)) == null ? void 0 : _a5.leaf.openFile(newFile);
          });
        });
      })
    );
  }
  onunload() {
  }
  switchToKanbanAfterLoad() {
    this.app.workspace.onLayoutReady(() => {
      let leaf;
      for (leaf of this.app.workspace.getLeavesOfType("markdown")) {
        if (leaf.view instanceof import_obsidian13.MarkdownView && this.isKanbanFile(leaf.view.file)) {
          this.setKanbanView(leaf);
        }
      }
    });
  }
  isKanbanFile(file) {
    if (!file) {
      return false;
    }
    const fileCache = this.app.metadataCache.getFileCache(file);
    return !!(fileCache == null ? void 0 : fileCache.frontmatter) && !!fileCache.frontmatter["kanban_plugin"];
  }
  async setKanbanView(leaf) {
    await leaf.setViewState({
      type: KANBAN_VIEW_NAME,
      state: leaf.view.getState()
    });
  }
};
/*! Bundled license information:

is-extendable/index.js:
  (*!
   * is-extendable <https://github.com/jonschlinkert/is-extendable>
   *
   * Copyright (c) 2015, Jon Schlinkert.
   * Licensed under the MIT License.
   *)

strip-bom-string/index.js:
  (*!
   * strip-bom-string <https://github.com/jonschlinkert/strip-bom-string>
   *
   * Copyright (c) 2015, 2017, Jon Schlinkert.
   * Released under the MIT License.
   *)
*/

/* nosourcemap */